Engineering onboarding

How Zube works, end to end

A map of the Zube Agents platform for a new engineer: where it runs, how a message or call moves through it, how XState orchestrates the workflows, what every feature is and how mature it is, where per-client custom code lives, and where the company is heading. We build with coding agents, so the goal here is a correct mental model you can direct agents with, not a line-by-line tour.

Researched at main 8b358572d, updated to 2205e6595 (24 Oct 2026) Built from 13 code-reading passes; every claim has a file:line under "Evidence" Code wins over planning docs where they disagree

Read this first

Zube is an agentic lead-management layer for businesses with constant lead churn: real estate (hotels, student accommodation, coliving) and travel (car rental, tour operators). It talks to leads on WhatsApp, Messenger, Instagram, email, webchat and inbound voice. It runs every conversation through XState workflow machines, generates every customer reply with an LLM graph, and turns conversations into lead scores, insights and CRM updates.

Monorepo
Bun + Turborepo, TypeScript only
7 apps, 21 packages + 10 connector packages. Bun is the only package manager.
Hosting
1 GCP VM, 5 Node containers
nginx → api · webhooks · telephony-infra; worker + scheduler have no HTTP.
State
One Cloud SQL Postgres
System of record, job queue (pg-boss), workflow state, locks, vectors, HLL sketches.
Orchestration
XState v5 machines
One generic runner; durable state is a JSONB envelope on the lead row.
Lead identity
targets
Phone, email, social IDs and CRM refs map into a target; everything keys off target_id.
LLMs
Tiered client, GPT-6 first
OpenAI · Vertex Gemini · Bedrock Claude · Microsoft Decision-1, all behind packages/llm.
Voice
Telnyx + ElevenLabs
Inbound only. Telnyx call control; ElevenLabs agent over SIP; Zube hosts the agent's tools.
Web app
React SPA + tRPC
Firebase Hosting + Auth. Thin control surface; most of the logic lives in the backend.

The system in 60 seconds

  1. Ingress apps only capture. webhooks and telephony-infra verify the provider request, persist it durably (receipt row and/or GCS spool), acknowledge it, and enqueue a pg-boss job. They never run workflows. (Ingress)
  2. The worker turns jobs into events. It resolves the provider identity to an organisation and a target, merges the transcript, then calls workflowRunner.handleEvent(targetId, event). (Queue)
  3. The runner owns concurrency and durability. It takes a Postgres advisory lock on the target, rehydrates the XState snapshot from targets.workflow_state, drives the machine until it settles, and commits everything in one transaction. (Runner)
  4. Machines decide; adapters act. The text machine calls the agentic reply graph (planner → tools → finalizer). Tools reach knowledge (Nexus), calendars and per-client functions. Replies are sent after commit, outside the lock. (Agentic)
  5. Time is data. Machines never use in-memory timers. They write next_action_at or pending rows, and scheduler and worker ticks turn those back into events, so restarts and deploys lose nothing. (Timers)
  6. Analysis follows conversation. On completion, on_conversation_complete extracts the lead score, summary and structured fields. Crons then roll up insights, sync CRMs and run the knowledge and intelligence jobs. (Intelligence)

How to use this doc with agents

  • Point agents at the right package. Each chapter names the owning directories. Agents should start at those paths and read the guidance files named in CLAUDE.md / AGENTS.md before touching an area.
  • Know the invariants before asking for changes. Some rules are load-bearing and gate-enforced: no provider calls outside wrappers, no workflows in ingress apps, no xstate after: timers, no canned customer replies, no new env vars, and migrations must stay backward-compatible. Each chapter lists the relevant ones.
  • Status pills tell you what's real. GA flag: key gated admin-only custom: client dormant legacy branch planned removal scheduled ops tool. "Built" means merged on main. It does not mean deployed or switched on for a given customer; production flag state was not inspected.
  • Planning docs drift. Many planning_docs/* status lines lag the code. In both directions, things marked "draft" are built and things marked "shipped" have since changed. Sharp edges lists every drift this pass found.

Hosting & topology

Production is deliberately small. One GCP project (zube-ai-agents, region europe-west2) runs one Compute Engine VM with a Docker Compose stack of nginx plus five Node containers, and one Cloud SQL Postgres holds all durable state, including the job queue. There is no Kubernetes, no Redis and no message broker.

INBOUND TRAFFIC OUTBOUND PROVIDERS Compute Engine VM · europe-west2-c · Docker Compose Meta Graph webhooks WhatsApp · Messenger · Instagram Telnyx PSTN calls · call-control events ElevenLabs Conversational AI voice agent, SIP leg from Telnyx server tools · post-call webhook Website visitors webchat widget · WebSocket Operators (browser) React SPA · tRPC calls nginx TLS (Let's Encrypt) api.zube.ai webhooks.zube.ai link · proposals status api · Express + tRPC · :3001 web-app backend · workflow-free · enqueues previews/imports webhooks · :3002 Meta + ElevenLabs ingress · webchat WS · OAuth verify → durable capture → ack → enqueue inbound-event telephony-infra · :3002 (own container) /telnyx · /voice-tools · /client_tools · in-memory call state redeployed only at zero active calls · enqueues voice-post-call worker · no HTTP pg-boss consumers · XState runner · agentic replies + sends dispatcher ticks (handoff, target-event, pending-text, spool drain) scheduler · no HTTP · single instance 30 Croner jobs: WAKE sweep, CRM sync, email polling, insights… holds its own XState runner · stop-then-recreate on deploy uptime-kuma → status.zube.ai worker + scheduler take no HTTP traffic outbound calls only via packages/llm · external-connectors · analytics LLM providers OpenAI GPT-6 (effective primary) Vertex Gemini · Bedrock Claude Decision-1 · Vertex embeddings Email Gmail / Graph polled · SES CRMs HubSpot · Salesforce · Dynamics Freshsales · monday.com Calendars Google · Microsoft · Calendly Meta / Telnyx send APIs replies · templates · call control PostHog (EU) analytics · error tracking Prospecting / search ZoomInfo · Lusha · web search Google Cloud managed services (project zube-ai-agents, europe-west2) Firebase Hosting + Auth SPA at app.zube.ai /trpc → 307 api.zube.ai Identity Platform ID tokens Cloud SQL · Postgres system of record · targets.workflow_state pg-boss queues (no Redis, no broker) pgvector halfvec · hll · advisory locks zonal · PITR 30 days every service ↔ Postgres Cloud Storage webhook spool call recordings batch JSONL · uploads Cloud KMS wraps per-integration OAuth tokens / secrets + storage CMEK Artifact Registry · Vertex service images tagged by SHA Vertex AI: Gemini, batch, embeddings
One VM, five Node containers behind nginx, one Postgres. Ingress containers (green) only capture and enqueue; the purple containers run the XState machines and make every outbound provider call. CI and deploy run from a self-hosted GitHub Actions runner on an AWS EC2 host (see Deploy & CI).
ingress (workflow-free)runs workflowsweb appdataLLMthird party

What runs where

ComponentRuns onPort / hostRole
nginxVM80/443 · api, webhooks, link, proposals, status.zube.aiTLS (Let's Encrypt via certbot + weekly renew workflow), reverse proxy with variable upstreams so overlap deploys pick up new container IPs
api (apps/api)VM container:3001 behind api.zube.aiExpress + tRPC for the web app; REST /api/proposals. Workflow-free. Enqueues manual imports and agent previews.
webhooks (apps/webhooks)VM container:3002 behind webhooks.zube.ai (+ link.zube.ai/e/)Meta + ElevenLabs post-call ingress, OAuth callbacks, webchat WebSocket and widget bundle, email tracking pixels/clicks. Workflow-free.
telephony-infra (apps/telephony-infra)VM container:3002 in its own container; /telnyx/, /voice-tools/, /client_tools/Telnyx call control, ElevenLabs server tools, in-memory call state. Redeployed only at zero active calls.
worker (apps/worker)VM containerno HTTP · readiness fileThe only pg-boss consumer; holds an XState runner; runs dispatcher ticks behind an advisory "tick lock".
scheduler (apps/scheduler)VM containerno HTTP · no healthcheck30 Croner jobs, PostHog spend crons, phone-line LISTEN/NOTIFY directory. Holds its own runner. Single instance by design.
uptime-kumaVM, separate Compose projectstatus.zube.aiPublic status page. Same VM, so it is not independent of a VM outage.
Web SPA (apps/web)Firebase Hostingapp.zube.aiReact SPA; /trpc 307-redirects to api.zube.ai. Also serves magic-link and proposal hosts.
Webchat widgetbundled into the webhooks image/webchat/widget.jsDependency-light IIFE embed customers drop on their sites.
Cloud SQLGCP managedprivate IP (+ an SSL-only public IPv4 with no authorised networks by default); devs via proxy on 127.0.0.1:5433System of record + pg-boss schema. Zonal, PITR 30 days. Extensions: pgvector, hll, pgcrypto.
Cloud StorageGCP managed—Private CMEK bucket (webhook-spool/, recordings, tmp/llm-batch/, uploads) + public-assets bucket for audio Telnyx fetches.
Cloud KMSGCP managed—integration-credentials key wraps every OAuth token/secret; storage-encryption CMEK. 90-day rotation.
Firebase Auth / Identity PlatformGCP managed—Email-link and password sign-in, optional Google IdP. ID tokens verified in packages/auth.
CI/CD + remote checksAWS EC2 (us-east-1)SSM-SSHSelf-hosted GitHub Actions runner zube-checkremote; also runs bun run check:*:remote. Idle-reaped.

Request routing (nginx)

HostPathUpstreamNotes
api.zube.ai/api:300130 s read timeout, aligned to tRPC + DB statement timeout (added after a 2026-06 insights freeze)
testNexusQuery, generateReply, templates.testReplyapi10 min lane
admin org delete, demo generate, knowledge ingest opsapi5 min lane
reports.generateReportapi75 s lane
manualImport.callImport.*api30 min lane (TODO: durable job)
webhooks.zube.ai/webchat/wswebhooks:3002WebSocket upgrade, 20 min read timeout
/telnyx/ · /voice-tools/ · /client_tools/telephony-infra:3002path passed unchanged
/webhooks:3002all provider webhooks, OAuth callbacks, widget bundle
link.zube.ai/e/ · /webhooks · Firebaseemail tracking (access log off: tokens in URL) · magic links
proposals.zube.ai/api/proposals/ · /api · Firebaseproposal microsite
app.zube.aiallFirebase Hostingno nginx block; SPA rewrite

Constraints you must not break

InvariantWhy
Scheduler is single-instance; deploy stops it, then recreates itCroner singleton guards one process, not replicas. Scaling out needs leader election (TODO).
Two workers may overlap during a deploySafe because per-target advisory locks serialise runs, dispatcher ticks run only in the tick-lock holder, and claims use SKIP LOCKED.
No application truth on VM diskVM disk dies on redeploy; durable state lives in Postgres and GCS.
All app containers share one ../.envNo per-process env drift. An env change restarts all workflow services. No new env vars without the owner's approval: runtime behaviour goes in persisted config.
Host-managed TLS is temporaryA managed load balancer must precede any multi-VM setup.
telephony-infra only redeploys at zero active callsCall state is in memory. The deploy waits up to 30 min, then defers. There is a fortnightly Sunday 04:00 London release window.
Credentials are KMS-wrapped per-integration rows, never plaintextWrappers own decrypt → call → refresh → re-encrypt → persist.
Terraform is the source of truth for GCP resourcesNew resources get Terraform in infrastructure/terraform/. DNS, billing, initial TLS and in-DB grants are not in Terraform.
Docs disagree on a few infra facts. Terraform pins POSTGRES_18, while the guidance and the prod-SQL tooling say Postgres 16 (local and CI Postgres is 16). The Terraform default machine type is e2-standard-4, but deploys set --max-old-space-size=12288 per container (the live tfvars are untracked and may override it). Some Terraform comments still describe three containers and a GCE-hosted CI runner. Alert policies are gated by monitoring_alerts_enabled (default false), and the live value is not visible from the repo. None of these were checked against the live environment.
Evidence
  • infrastructure/terraform/variables.tf:19-74, compute.tf:10-104: VM, zone, image, disk
  • infrastructure/terraform/database.tf:1-76: Cloud SQL tier, version, PITR, users application/migration
  • infrastructure/docker-compose.yml:23-164: the six services, shared env, health checks, stop grace periods
  • infrastructure/nginx/nginx.conf:13-20,139-399: variable upstreams, per-procedure timeout lanes, host blocks
  • apps/web/firebase.json:1-53, infrastructure/terraform/firebase.tf: SPA hosting and /trpc redirect
  • infrastructure/terraform/kms.tf, storage.tf:1-229, identity-platform.tf:1-63
  • scripts/checkremote/run.ts:167-176, scripts/checkremote/ciRecovery.ts:7-9: AWS EC2 runner and remote checks
  • guidance/engineering-constraints.md:95-107: topology and single-instance constraints
  • packages/services/src/scheduler/tickLock.ts:8-22: tick lock for overlapping workers

Code layout & tiers

The monorepo is a strict, tiered DAG: a package may import only from lower tiers, and cycles (type-only ones included) fail CI. Business logic sees only interfaces (ports). Concrete adapters for providers, the database and LLMs are constructed in a handful of composition roots and injected.

apps/ api · webhooks · telephony-infra (workflow-free) worker · scheduler (hold a runner) web · webchat-widget (only webapp-contracts + utils) Tier 7 workflow-composition test-builders · test-harness (testcontainers) Tier 6 workflows (XState machines + runner + clients/) app-composition (env → runtime, wrappers; workflow-free) Tier 5 client-tools (per-client AI tools, report metadata) inbound-http (route factory, verifiers) Tier 4 services (domain logic: inbound, cadence, crmWorkflows, insights, knowledge, scheduler jobs… sees ports only) Tier 3 llm external-connectors/{crm, email, calendars, meta, telnyx, voice, …} (10 pkgs) gcp · analytics · notifications Tier 2 db (Drizzle schema, migrations, pg-boss wrapper) · repositories (~54 classes) · auth (Firebase) Tier 1 ports (interfaces + boundary errors) webapp-contracts (tRPC I/O types, DTOs) Tier 0 utilities · formatters · logging · config (env parsing only — leaf, no workspace deps) imports only point down · cycles fail CI Enforced by gates workspace-import:check (DAG) external-boundary:check (provider hosts) sdk:boundary-check · client-boundary:check ESLint: services ✗ workflows/wrappers composition roots own `new XWrapper()` posthog-* only in analytics structured-output:check (LLM via Zod)
The tiered package DAG (guidance/engineering-constraints.md). Business logic in services and workflows sees only ports. Concrete adapters are built in the composition roots (apps/*/src/composition.ts, app-composition, workflow-composition) and injected through a ServiceRuntime bag.

Where things live

PathWhat's in itTouch it when…
apps/apiExpress + tRPC (21 routers), procedure ladder (publicProcedure → trueAdminProcedure), proposals RESTadding a web-app endpoint
apps/webhooks · packages/inbound-httpprovider ingress via the createInboundRoute factory, OAuth callbacks, webchat WSa new provider webhook or callback
apps/telephony-infraTelnyx call control, ElevenLabs server tools, transfer logic, in-memory call statevoice behaviour during a call
apps/workerpg-boss consumers (inbound-event, voice-post-call, manual-import, agent-preview), per-channel inbound processors, dispatcher tickshow an inbound job becomes a workflow event
apps/scheduler · packages/services/src/schedulercron registry + every job body; Addison Lee runtime compositionanything periodic
packages/workflowsXState machines, the runner, registries, client hooks (src/clients/<client>/), cadence configs, safeguardsworkflow behaviour
packages/llmLlmClient, model tiers, agentic graph (planner/tool/finalizer), prompts, Nexus researcher, batch, embeddings, decision modelsany LLM call or prompt
packages/servicesdomain logic by area: inbound, conversations, voice, cadence, crmWorkflows, insights, knowledge, reminders, reporting, templates, webchat, whatsappBusinessApp…most product logic
packages/repositories~54 Drizzle repository classes; createRepositoriesModule(db)queries and writes
packages/dbDrizzle schema (source of truth), numbered SQL migrations (0000–0097), pg-boss wrapper, demo seedingschema changes (bun run db:generate)
packages/external-connectors/*provider wrappers: crm, email, calendars, meta, telnyx, voice, contact-center, prospecting, client-custom, sharedcalling any third party
packages/client-toolsper-client AI-callable tools, report metadata, calendar params (workflow-free)a client-specific agent tool
packages/app-composition · workflow-compositionenv → runtime inputs, wrapper factories, reply senders · runner-holding runtime + default machine registrationwiring a new adapter
packages/webapp-contractshand-written tRPC I/O types and DTOs; the only backend types the web app may importchanging an API shape
apps/webVite + React 19 + TanStack Router + tRPC client + React Query + Tailwind v4/shadcn. Two UIs: ui/classic and ui/new ("UI 2.0")frontend work (see below)
scripts/grep gates, deploy, checkremote, operations/ (prod SQL), nexus, demo, addisonLee one-offstooling
guidance/ · planning_docs/engineering contracts agents must read · 61 epic/plan folders + 2 loose docs (status lines often stale)before working in an area

Dependency injection, concretely

Services and workflows never call new HubSpotWrapper(). They depend on a port or a factory type, and a composition root supplies the implementation. HubSpot as an example:

  1. Port the service sees: HubspotWrapperPort extends CrmWrapperPort, CrmIdentityReconciliationPort. The service gets a factory BuildHubspotWrapper = (integration) => HubspotWrapperPort, a callback "so orchestrator tests can inject scripted wrappers".
  2. Ports the adapter needs: IntegrationRepositoryPort (persist rotated tokens, mark auth_error), AuthFailurePort, CryptoPort (KMS).
  3. Adapter: HubspotWrapper extends CrmWrapper owns decrypt → request → reactive 401 → singleflight refresh → re-read latest credentials → persist → retry once → flip to auth_error.
  4. Composition: buildCrmWrapperFactories in app-composition builds the closures. The worker gets them via buildDefaultRuntimeWithCrmFactories; the scheduler seeds them directly and fails boot without a KMS cipher.

Workflow-free runtime

Used by api, webhooks, telephony-infra. buildWorkflowFreeRuntime(): db pool, repositories, LLM client, analytics, services bag, with no runner and no machine registries. These apps have no @zube-agents/workflows dependency at all. They hand work over through pg-boss queues.

Runner-holding runtime

Used by worker, scheduler. buildDefaultRuntime* / createServiceRuntime adds workflowRunner, registries, dispatchers, CRM artifact/escalation dispatch. Boot asserts the exact set of registered machines and client hooks against a literal list.

The web app, briefly

The web app is a thin control surface over tRPC. Rules agents must follow: TanStack Router is the only router (no window.location). Raw tRPC calls live only in lib/Trpc.tsx and per-domain src/api/trpc/** wrappers. Types come only from webapp-contracts, never AppRouter. Files under src/routes hold route definitions, src/features/<domain> holds domain code, and shared primitives come first. Users pick Classic or New ("UI 2.0") per account; Classic is the default and some areas (Deals) exist only in New. Auth uses Firebase ID tokens, and Zube admins impersonate users via the x-persona-user-id header (see Platform).

Evidence
  • guidance/engineering-constraints.md:40-59: tier DAG and ESLint import bans
  • packages/services/src/crmWorkflows/armDeps.ts:227-238: factory-type injection
  • packages/external-connectors/crm/src/wrapper.ts:293-414: reactive refresh loop
  • packages/app-composition/src/crmWrapperFactories.ts:45-122: composition of wrapper factories
  • packages/app-composition/src/workflowFreeRuntime.ts:8-15; packages/workflow-composition/src/defaultRuntime.ts:32-78
  • packages/workflows/src/registry/expectedRegistrations.ts:30-113: boot-time registration assertions
  • apps/api/src/trpc/router.ts:24-52, apps/api/src/trpc/trpc.ts:230-425: routers and procedure ladder
  • guidance/frontend-conventions.md; apps/web/package.json

Ingress: webhooks & voice

Two Express processes take provider traffic: webhooks for messaging, OAuth and webchat, and telephony-infra for Telnyx and ElevenLabs tools. Their whole job is to verify, capture durably, acknowledge and enqueue. Neither runs XState machines. Everything after the ack happens in the worker.

Meta Graph webhooksingress app Postgresreceipts · pg-boss · targets workerjob consumer XState runneron_text_message_received LLM layeragentic graph 1 · POST /whatsapp/event (raw bytes kept) 2 · INSERT webhook_receipts (payload, sha256) 3 · pg-boss send inbound-event {source:'whatsapp', receiptId} 4 · 200 {status:'queued'} 2 s budget; on DB trouble spool to GCS, still 200 5 · NOTIFY / 5 s poll → job 6 · load receipt · phone_number_id → org resolve/create target · merge transcript 7 · handleEvent(MESSAGE_RECEIVED) 8 · pg_advisory_lock(target) · tx_load envelope 9 · machine: permissions → conversation → transcript → waitForBatch (park with next_action_at, or continue now) 10 · planner → tools → finalizer 11 · reply, or suppress + escalate 12 · tx_final: snapshot + writes + audits + handoff row · unlock 13 · claim latest reply (staleness guard) → send via Meta Graph 14 · eager handoff → on_conversation_complete (insights, score)
One inbound WhatsApp message. The HTTP request ends at step 4; everything after runs in the worker. The reply is sent after the transaction commits and the lock is released, so a crash can't lose the state change. A crash during a send leaves a send-safety hold behind instead of a silent retry.

The route factory: createInboundRoute

Every provider route under apps/*/src/inbound/ must go through packages/inbound-http/src/createInboundRoute.ts. A grep gate rejects raw router.post there. The factory captures the raw body before anything parses it (HMAC and ed25519 need exact bytes, so there is deliberately no global JSON parser). It then runs one of two paths:

Silent-200 path (Messenger, Instagram, ElevenLabs post-call, Telnyx)

  1. Raw body (413 above 2 MiB) and operation context.
  2. Verify. An invalid signature gets a silent 200, or a 401 for Telnyx. ElevenLabs alone proceeds on a bad signature (legacy parity).
  3. beforeParse durable work, parse, optional in-memory dedup (Telnyx).
  4. Durable capture before ack (beforeAck + enqueue) under a 2 s budget. On a miss or DB failure the raw body goes to the GCS spool and the request is still acked. Postgres data errors are never spooled, because a replay would fail the same way.
  5. Ack 200 {status:'ok'}.
  6. Optional background handler after the ack (Telnyx). Errors are logged, never retried.

Inline path (WhatsApp POST, Meta GET handshakes, voice tools, PostHog alerts)

  1. Raw body and context. An invalid verify throws HttpError(401).
  2. Spooling capture budget starts; beforeParse runs inside it (WhatsApp: insert webhook_receipts with raw text + sha256).
  3. Parse. A failure returns parseFailureStatus (WhatsApp: 503 so Meta retries).
  4. The handler runs inside the same budget (WhatsApp: enqueue {source:'whatsapp', receiptId}).
  5. Response: JSON, or {status:'spooled'} if it fell back to GCS. Errors use the legacy {detail} shape that ElevenLabs and Telnyx tool consumers parse.

webhooks routes

PathProviderVerificationWhat it does
POST /whatsapp/eventMeta WhatsAppNone on normal POSTs (by design). Replays need a valid X-Hub-Signature-256.Receipt row, then enqueue inbound-event by receiptId; spool on failure
POST /messenger/event · /instagram/eventMetaHMAC-SHA256 with app secret, strictEnqueue raw payload with deterministic job id uuidv5(source:sha256(body))
GET /{whatsapp,messenger,instagram}/eventMetaverify-token handshakeEcho hub.challenge
POST /elevenlabs/eventElevenLabs post-callHMAC, 30 min tolerance; proceeds on a bad signaturePersist knowledge-query capture (valid signature only), enqueue inbound-event
POST /posthog/error-tracking-alertsPostHogBearer HMACUrgent system-issue email via SES (ignores advisory-lock noise)
/e/o/:token.gif · /e/c/:token · /e/u/:tokenZube email trackingtoken hash lookupOpen pixel, click redirect, unsubscribe
GET /callbacks/{hubspot, salesforce, monday, microsoft-dynamics, calendly, microsoft-calendar, microsoft-teams, microsoft-sharepoint, google-email, microsoft-email}OAuthsigned callback stateExchange code, KMS-encrypt tokens, upsert integrations row
GET /callbacks/meta-messaging/ · /callbacks/whatsapp-business-app/Meta connectsigned statePage/IG subscribe; WhatsApp Embedded Signup (business token, no refresh)
ALL /callbacks/custom/addisonlee/zoominfocustomnoneReturns 204 and does nothing (stub)
/webchat/{widget.js, config, session, transcript} + WS /webchat/wsZube webchatorigin allowlist, 15 min HMAC session tokenWidget bundle, config, session mint, transcript replay, turns over WebSocket
Not here. There is no inbound SMS route, no Gmail push or Graph change notifications, and no CRM event webhooks. Email arrives by polling (emailPollingSyncer, every 2 min), and CRMs are pulled every 3 min (crmSyncer). The Telnyx SMS client exists but has no consumer.

telephony-infra routes

PathCallerAuthWhat it does
POST /telnyx/eventTelnyx Call Control v2ed25519, 300 s tolerance, 401 on failureAck, 3-tier in-memory dedup, switch over 13 event types (background)
POST /voice-tools/elevenlabs/inbound_call_initElevenLabsBasic auth elevenlabs:<secret>, fail-closedFirst message + dynamic variables for the caller
POST /voice-tools/elevenlabs/calendar_{list_slots,create_booking}ElevenLabs toolsameCalendar tool service (Calendly / Microsoft)
POST /voice-tools/telnyx/{transfer_to_human, check_transfer_availability}ElevenLabs toolsameHours/rules gates, LLM destination pick, blind transfer
POST /voice-tools/elevenlabs/custom/:client/:fn · legacy /client_tools/:client/:fnElevenLabs toolsame (shared secret; no org check)Dispatch to packages/client-tools per-client tool
GET /readydeploy—DB check + activeCalls (deploy gate)

The handoff contract (pg-boss payloads)

SourceQueue · payloadJob id
WhatsAppinbound-event {source:'whatsapp', receiptId}generated (dedupe happens on the receipt)
Messenger / Instagraminbound-event {source, payload}uuidv5 of body sha; JobAlreadyExistsError swallowed
ElevenLabs post-callinbound-event {source:'elevenlabs', payload}none
Webchat turninbound-event {source:'webchat', turn}, priority live, group per visitoruuidv5(widget, visitor, messageId), sent in the same tx as the outcome row
Telnyx recordingvoice-post-call {gcsUri, callSessionId, state}none (a failed send loses the post-call; logged)

Payload schemas only ever gain optional fields, and unknown fields are stripped, so old and new workers can coexist during a deploy. An unknown source is retried so a newer worker can pick it up. New kinds of work get new queues, not new source values.

Identity resolution

  • Messaging: resolved in the worker, not at ingress. For WhatsApp, phone_number_id maps to an integrations row, giving the org, and the sender becomes resolveOrCreateWhatsAppTarget (phone, or BSUID when Meta omits the phone). Messenger and Instagram resolve by (channel, platformAccountId).
  • Voice: resolved in telephony-infra. The DID is matched against callSettings.phoneLines[], then the target is found or upserted by phone, and the conversation is created by referenceCallId, all off the media path.
  • Webchat: org from the widget integration row at WS upgrade; anonymous web_chat::<visitorUuid> target until contact capture.
  • Endpoint workflow routing: if the receiving endpoint (phone line, page) has a different workflowId from the target, applyInboundEndpointWorkflowRouting repoints the target (unless it is paused or overridden).

Webchat transport

  1. The widget's loader derives REST and WS URLs from its own script src, fetches config, then mints a 15 min HMAC session (origin must be allowlisted).
  2. On each frame, webhooks rate-limits (10/min per session, 30/min per IP), inserts a pending webchat_turn_outcomes row and the pg-boss job in one transaction, then acks the frame. A failure returns a protocol error, never assistant text.
  3. The worker runs the text machine (no batching park for webchat), writes the outcome, and NOTIFYs webchat_turn_outcome.
  4. Every webhooks instance LISTENs. Only the instance holding the visitor's socket pushes the reply, and it stamps delivered_at. A reconnect to another instance resumes pending turns.

Why it's built this way

  • Ingress apps are workflow-free so they can be redeployed independently. telephony-infra in particular lags behind, because it only redeploys at zero calls, and it must never execute stale workflow code. Its one former in-process workflow step became the voice-post-call job.
  • Capture before ack, spool as last resort, so a DB outage never turns into Meta retry storms or lost messages. The worker's webhookSpoolDrainTick re-ingests the spool under the same deterministic ids.
  • Idempotency is layered: deterministic job ids, byte-identical receipt dedupe in the worker, a Telnyx dedup cache set only after successful capture, and webchat outcome primary keys.
Evidence
  • packages/inbound-http/src/createInboundRoute.ts:20-28,133-179,553-847: factory, budgets, both paths
  • scripts/grep-gates/webhooksRouteFactory.ts:44-59,125-135: route gate (narrower than its header claims; routers outside inbound/ are not gated)
  • apps/webhooks/src/inbound/whatsapp/dispatch.ts:15-17,54-75,91-147: unsigned POST, replay auth, receipt + enqueue
  • apps/webhooks/src/app.ts:110-202; apps/telephony-infra/src/app.ts:117-256: route mounts
  • packages/db/src/jobQueue/payloads.ts:3-81; inboundEventJobId.ts:5-17: payload contract and job ids
  • apps/worker/src/inbound/whatsapp/events/messages/index.ts:832-870: org + target resolution
  • apps/telephony-infra/src/inbound/telnyx/internal/inboundDidResolver.ts:86-121, ensureInboundConversation.ts:1-157
  • apps/webhooks/src/webchat/enqueueTurn.ts:58-84, frameHandler.ts:308-362, continuationBridge.ts:1-11, turnDelivery.ts:1-25
  • apps/telephony-infra/src/composition.ts:3-8: why the transcript step became a job

Queue, worker, scheduler

Background execution lives entirely in Postgres. pg-boss 12.34.0 provides four queues, the worker is their only consumer, and the scheduler runs 30 Croner jobs. Everything that must survive a crash is a row: claims, leases, pending handoffs and timers.

Queues

QueueProducerConsumer (worker)SettingsPurpose
inbound-eventwebhooks (WhatsApp, Messenger, Instagram, ElevenLabs, webchat); worker spool draincreateInboundEventConsumer → per-source processortwo subscriptions: general (concurrency 20) + live tier (priority ≥10, concurrency 2); groupConcurrency 1; retry ≤8 with backoff ≤300 s; expire 900 s; 5 s poll backstopall inbound messaging + webchat turns
voice-post-calltelephony-infra after recording savedcreateVoicePostCallConsumerconcurrency 4; expire 3600 s; no NOTIFY, so pickup can wait up to the 30 s polltranscript → persist → CALL_ENDED
manual-importapi (lead CSV/XLSX import), same tx as batch rowsbatch processor under a per-batch advisory lockconcurrency 2; heartbeat 30 s; retry 3; pg-boss failures resume≤100 rows per batch, processed in order
agent-previewapi (template test reply, conversation "Generate reply")createAgentPreviewConsumerconcurrency 4; expire 300 s; retry 1effects-free reply previews polled by the UI
Retry semantics are deliberately narrow. Only WorkflowTargetBusyError (lock contention) and RetryableJobError (cases where the provider would have redelivered) retry. Any other throw dead-letters, because side effects may already have happened. No dead-letter queue is configured, so "deadletter" means a terminal fail plus logger.error('job_queue.handler.error'). Enqueues that accompany row writes share the caller's transaction (send(..., {transaction})).

Worker process

  1. Remove the stale readiness marker, then build composition and consumers first, so a runtime without a runner fails boot before it connects.
  2. Create the pg-boss client and the tick lock, a session pg_try_advisory_lock on zube:dispatcher-ticks. Only the holder runs ticks, and only when SCHEDULER_ENABLED=true.
  3. Register consumers last, so a startup throw can't strand fetched jobs. Then write /tmp/zube-worker-ready.
  4. Shutdown order: drop readiness, stop ticks, release the tick lock (the peer takes over within one tick), stop pg-boss gracefully (≤120 s), drain consumed continuations, then shut down the runtime. Hard cap 150 s; Compose grace 170 s.

Dispatcher ticks (worker, tick-lock holder only)

TickEveryClaimsDispatches
handoffDispatcherTick15 sdue workflow_handoff_pending ids (SKIP LOCKED), 600 s in-flight janitorrunner.runPendingHandoff: the crash-recovery path for machine chaining
targetEventDispatcherTick15 starget_workflow_event_pendingTARGET_EVENT_DISPATCHED (today: cadence_step_failed)
pendingTextDispatcherTick15 sdue pending_text_events grouped by targetdrainPendingTextEvent + send reply
webhookSpoolDrainTick30 sGCS webhook-spool/ objects (≤50/provider)re-create receipt + job under deterministic ids; quarantine unclassifiable objects

Scheduler: every cron

Croner with 6-field (seconds-first) or 5-field expressions, UTC unless noted, singleton unless noted. Registry: packages/services/src/scheduler/registry.ts:53-85. A failed job logs scheduled_job_failed and never crashes the process.

JobScheduleWhat it doesGate / note
checkAwaitingActionevery 30 sThe WAKE sweep: targets awaiting_action_from_target plus due active text targets → WAKE → send replycore timer mechanism
checkStaleConversationsevery 5 minforce-complete stale voice calls → CALL_ENDEDrecovery for busy post-call
emailPollingSyncerevery 2 minpoll each Google/Microsoft mailbox → relevance gate (EU Bedrock) → MESSAGE_RECEIVED → replynon-singleton; per-mailbox in-process guard
emailCrmSyncerevery 5 minpoll crm@getzube.com, map sender domain → org, LLM-parse contacts → CRM-sync per contactStay Club / Road Scholar style CRM-by-email
crmSyncerevery 3 minpull HubSpot / Salesforce / Dynamics / Freshsales / monday deltas → CRM_RECORD_RECEIVEDneeds KMS + wrapper factories
crmSyncbackerevery 3 min (+2)write Zube target fields back to HubSpot / Salesforce / Dynamics (no Freshsales syncback)interruptible
crmEscalationTaskReconcilerevery 5 minmark expired CRM escalation-task reservations for reconciliationno provider calls
rebuildCrmConversionProjectionsevery 10 min + startuprepair/refresh conversion read modelsfeeds Conversion insights
bootstrapSalesMotionCrmOutcomesevery minutebackfill canonical CRM outcome observations
historySyncResumerhourly + startupresume stalled email / Messenger / Instagram history syncs
aggregateInsightsdaily 12:05per-org daily metrics + LLM-normalised content insights + daily loss generation; voice-privacy retention firstneeds LLM
aggregateMonthlyInsights1st of month 13:00monthly rollups from daily rows (HLL unions)
curateContentInsightsfortnightly Sun 04:00 + startuprename/merge category catalogs on gpt.ultrainterruptible
processDeferredConversationAnalyses:05 and :35half-hour batch: sentiment + custom analyzersnon-singleton; OpenAI-first batch
reconcileSalesMotionObservationsdaily 02:15enqueue the 48–72 h drop-off cohort (deterministic)
processSalesMotionObservationsevery minuteLLM drop-off cause/topic per claimed observationsurfaced admin-only
processDueRemindershourlyLLM-validate and dispose due reminders; escalation routing
processDueReportsevery minutejanitor → due scan → generate → store → email client reports4 client generators
knowledgeDeletionTickevery 15 sNexus hard delete (GCS, then rows) + ingest staging cleanup
knowledgeQueryDiagnosticshourlyobserved knowledge gaps → findings for Nexus Review
nexusTaxonomyWeeklySun 04:00 Londonbootstrap catalogs / weekly matching of findingsflag nexus_taxonomy
nexusTaxonomyPollerevery 15 mincollect batch results, publish validated rowsflag nexus_taxonomy
webchatIdleFinalizeevery minuteclose idle webchats; substantive ones get on_conversation_complete
jobQueueHealthMonitorevery minutequeue wait p95 breaches, recent failures, reconcile stuck webchat turns / dead imports / expired previewssilent-drop detection
webhookReceiptMonitorhourlyemail overdue WhatsApp receipts (30 min grace), daily digest, delete expired receipts (14 d)needs SES
publicVoiceDemoUsageRetentiondaily 00:00prune demo usage receipts older than 13 months
telnyxCostRollupevery 3 hTelnyx CDRs → PostHog vendor_usage_recorded (org via phone-line directory)POSTHOG_ENABLED
elevenLabsCostRollupevery 3 hper-call ElevenLabs cost → PostHogPOSTHOG_ENABLED
elevenLabsRateRefresherMon 04:00re-stamp the hard-coded credit→USD ratePOSTHOG_ENABLED; directional, not billing-grade
clientOutboundTickevery 30 s + startupAddison Lee UC2 media-production outbound campaign tickcustom: Addison Lee removal scheduled

The scheduler also holds its own XState runner, because cron jobs call workflowRunner.handleEvent directly. It registers the Addison Lee client asynchronously and non-fatally (addison_registration_failed log metric). It also owns the phone_lines_changed LISTEN/NOTIFY directory, used only by the Telnyx cost rollup (the file header claiming api/webhooks use it is stale). There is no 60-day data-retention purge in this checkout.

Concurrency patterns (all in Postgres)

PatternWhereProtects
Per-target session advisory lock on a reserved connectionworkflow runnerone run per target across all processes; blocking, queue-ordered, 300 s budget (15 s for eager handoffs)
Tick lock (pg_try_advisory_lock, liveness-probed)worker ticksone tick runner during overlap deploys
FOR UPDATE SKIP LOCKED claim + in-flight TTL janitorhandoffs, target events, reminders, observations, taxonomy runsno double processing; stranded rows return after 600 s / 30 min
Claim owned by the runner, not the dispatcherhandoff dispatchone code path for state transitions; a lost race is a no-op
Lease rows (claim_token, lease_expires_at)CRM pull-retry lane, reports, RevOps runs (branch)only the current claim holder applies
Handoff coalescing keyon_conversation_complete per conversationIda burst of turns queues one follow-up, not N (this was the cause of lock-timeout storms)
Tx-scoped advisory locks on identity hashestarget merge/create, CRM identity, webchat codesconcurrent events for one phone/email converge on one target
Deterministic job ids + transactional enqueueingress, imports, previews, spool drainredeliveries never duplicate; rows and jobs commit together
In-process guardsscheduler singleton, email poll guard, dedupe cachesvalid only because the scheduler is single-instance
Evidence
  • packages/db/src/jobQueue/pgBossJobQueue.ts:36-302: wrapper, concurrency, settlement, retry policy
  • packages/db/drizzle/0076_pgboss_12_34_0.sql:442-444, 0083_phase2_worker_split_queues.sql:8-10: queue DDL
  • apps/worker/src/workerProcess.ts:48-216: boot and shutdown order
  • packages/services/src/scheduler/registry.ts:53-95: crons and dispatcher ticks
  • packages/services/src/scheduler/createScheduler.ts:63-349: singleton semantics, runOnStartup, anchored intervals, stop
  • packages/workflows/src/runner/advisoryLock.ts:1-65,247-334; handoffDispatcher.ts:5-157; workflowRunnerTxFinal.ts:539-580
  • packages/db/src/phoneLineDirectory.ts:15-35,239-309; apps/scheduler/src/tasks/postHogSpendWiring.ts:96-157
  • planning_docs/multi-app-split/plan.md:116-126, worker-split.md:85-89: overlap safety, new-queue rule

XState workflow runner

Every lead workflow is an XState v5 machine (xstate ^5.30.0), and one generic runner executes them all. The design rests on three ideas: one owner per target (a Postgres advisory lock), one commit per run (tx_final), and time as data (no in-memory timers). Machines are pure-ish transducers. They decide; the runner and adapters do the I/O.

Durable state
targets.workflow_state
One JSONB envelope per lead: machineId, workflowRunId, version, xstate persisted snapshot, nextActionAt, previousState stack, optional executionSafety. No runs table.
Scan mirrors
workflow_status · next_action_at
Indexed together so the scheduler can find due work. Status enum: active · paused · awaiting_action_from_target · completed · failed.
Who runs machines
worker + scheduler only
api, webhooks and telephony-infra have no runner and no workflows dependency.
Held for the whole run: one reserved pg connection + session advisory lock pg_advisory_lock(hashtextextended(target_id)) 1 · Lock + tx_load blocking, 300 s budget busy → TargetBusyError 2 · Admission + hold check other thread's text → pending safety hold → pause + take-over 3 · Resolve run event type → machine fresh · hydrated · dropped 4 · buildInput loads data, no effects protected actor + guard 5 · Client preHook continue, or consume run (Addison Lee UC1/UC2) 6 · Dispatch until settled ≤ 240 s · lanes 7 · Capture output read snapshot.output BEFORE actor.stop() null runtime slots 8 · Derive status done → completed error → failed parked → statusOnWake 9 · postHook + getPostWorkflow terminal only; successor last call wins vs output 10 · tx_final (one transaction) lane-1 domain writes · workflow_state envelope status + next_action_at · audits (ON CONFLICT) target events · handoff row (coalesced) 11 · Post-commit + unlock CRM artifact dispatch clear send-safety hold unlock_all · release connection (destroy if unlock fails) Cadence-only hooks run inside step 6: WAKE hydrator → safeguard matrix (may rewrite WAKE → STEP_FAILED) → lane-4 provider send → PROVIDER_RESULT back into the same actor. Retryable SQLSTATEs replay only the reserved-transaction writes, under the same lock. A lost COMMIT ack is recorded as unknown commit certainty, never assumed. 12 · Caller sends the reply outside the lock, after commit claimLatestZubeTranscriptReplyForSend (staleness guard on the unanswered basis) → provider send → stamp reference id 13 · Eager handoff delivery claim workflow_handoff_pending pending→in_flight run successor now: new connection, 15 s lock budget fails? the source commit stands, and handoffDispatcherTick redelivers (15 s; 600 s janitor) Entry points on the runner handleEvent(targetId, event) runPendingHandoff(rowId) drainPendingTextEvent(targetId, now) p-limit at 80% of pool · shutdown drains 750 ms
The generic runner (packages/workflows/src/runner/workflowRunner.ts) handles every event the same way. Machines never touch the database directly. They emit lane-tagged effects, and the runner commits them in tx_final. New machines are new files plus registry entries; the runner itself is closed for extension.

House style for machines

  • setup({ types, actions, actors, guards }) with named implementations. The config references them by name; {} as X is allowed only inside setup({ types }).
  • LLM calls and read lookups are bounded promise actors (createBoundedPromiseActor, lane 6), each with a deadline. The agentic reply actor allows up to 600 s.
  • Database writes are lane-tagged repository methods. Machines never get a transaction handle.
  • Time comes from the event's now or an injected clock: no Date.now(), no new Date(), no after:.
  • actor.send is allowed only in dispatchUntilSettled.ts and machines/shared/actions.ts.
  • Snapshots must survive a JSON round-trip. Runtime-only context slots (_runner, _repos, _llm…) are nulled before persistence, and the codec rejects a Date, Map or Symbol.
  • Each machine registers a version and migrations[]. Every machine is at v1 today, and a snapshot from a newer version throws.

Lanes: how side effects are classified

LaneTag / primitiveSemantics
1@runnerPlanAndBuffer / planAndBufferBuffered write, flushed inside tx_final. Replay-safe through a deterministic id + ON CONFLICT. The machine gets a synthesised DOMAIN_RESULT.
2@runnerImmediateShort reads.
3@runnerImmediateRMWShort read-modify-write that commits before tx_final and must be self-idempotent. Allowlisted to four methods: atomicMergeTranscript, persistAgentReplyIfStillLatest, mergeAdditionalInformation, createStub.
4split-transaction provider sendCadence stage sends, executed by the runner, with results fed back as PROVIDER_RESULT/PROVIDER_FAILED.
6createBoundedPromiseActorLLM calls and read-only lookups as invoked child actors with deadlines.
Enforced by a gate. scripts/grep-gates/runnerLaneAudit.ts (bun run runner:lane-audit, part of check:static) enforces the lane tags in packages/repositories/src, the no-after: and no-clock rules in packages/workflows/src/machines, and the actor.send allowlist across packages/workflows/src. Parse stored ISO strings in machines with parseIsoToDate (runner/types.ts), because the regex can't tell parsing from a clock read.

How events reach a persisted machine

SourceEventPath
Inbound WhatsApp / Messenger / IG / email / webchatMESSAGE_RECEIVEDworker consumer or email poller → handleEvent
Voice outcomeCALL_ENDEDvoice-post-call job · ElevenLabs post-call · stale-call sweep
CRM recordCRM_RECORD_RECEIVEDcrmSyncer/emailCrmSyncer on a freshly minted bootstrap id (the machine swaps the lock to the real target)
TimerWAKEcheckAwaitingAction every 30 s
Machine chainingHANDOFF_DELIVERY → successor's first run-initiating eventeager post-commit run, else handoffDispatcherTick
Cross-machine signalTARGET_EVENT_DISPATCHED → e.g. STEP_FAILEDtargetEventDispatcherTick
Deferred textspooled MESSAGE_RECEIVEDpendingTextDispatcherTick
Operator actionnoneapps/api has no runner. Operator status changes are row writes, and machines re-read status before sending (e.g. finalSendChecks).

Run-initiating events: MESSAGE_RECEIVED, CALL_ENDED, CONVERSATION_COMPLETE_TRIGGERED, CRM_RECORD_RECEIVED, CADENCE_STARTED, HANDOFF_DELIVERY. Continuations: WAKE, DOMAIN_RESULT, PROVIDER_RESULT, PROVIDER_FAILED, REPLY_RECEIVED, CALL_COMPLETED, STEP_FAILED, TARGET_EVENT_DISPATCHED.

Machine run never uses xstate after: timers writes context.nextActionAt or output.handoff / target event → committed in tx_final targets.next_action_at index (workflow_status, next_action_at) mirrors envelope.nextActionAt workflow_handoff_pending successor queue · unique per source run coalescing key supersedes older rows target_workflow_event_pending cross-machine signals (cadence_step_failed) no reach-in envelope mutation pending_text_events text that arrived while another thread ran checkAwaitingAction · scheduler every 30 s · awaiting_action_from_target + due active text targets → WAKE handoffDispatcherTick · worker every 15 s · SKIP LOCKED · 600 s janitor → runPendingHandoff (crash recovery) targetEventDispatcherTick · worker every 15 s → TARGET_EVENT_DISPATCHED unwrapped to STEP_FAILED on the cadence pendingTextDispatcherTick · worker every 15 s → drainPendingTextEvent Runner same lifecycle, same lock, same tx_final
Timers are data, not in-memory delays. Everything a machine wants to happen later is a row or an indexed column in Postgres, and a periodic sweep turns it back into an event. That is why a restart or a two-worker deploy overlap loses nothing. Worker ticks run only in the instance holding the zube:dispatcher-ticks advisory lock.

Stacking: one machine on top of another

When a run-initiating event arrives for a target that currently holds a different machine, the runner starts a fresh run and pushes the old envelope onto previousState. A successor that finishes with output.restorePrevious === true pops it back, along with its status and nextActionAt. This is how an instant client successor (say, Lingua's post-conversation email) runs on top of a parked cadence without destroying it. instant: true machines must finish in one dispatch, and a non-terminal settle is treated as a defect (failed) so stacked work can't hide.

Known invariant gap. The workflow_status/next_action_at mirrors reflect only the top envelope, so a successor stacked on a parked delayed reply can hide that reply from the WAKE sweep (one stranded target was investigated). The instant class shipped as step 1 of the fix. The stack-aware mirror, the detector and an explicit restore/cancel contract are still planned (planning_docs/workflow-envelope-scheduler-invariant).

Send-safety hold (execution safety)

Losing a DB session can't undo a provider send that already happened, and the advisory lock is released the moment the session dies. So, before the first provider effect, the runner's effect guard commits workflow_state.executionSafety {executionId, workflowRunId, attempts[]} in its own transaction, then records each provider acceptance receipt. A healthy owner clears the hold after tx_final. If a later owner finds an unresolved hold, it pauses the target (help_needed, workflow_status=paused, next_action_at=null) and writes the standard take-over row to the client's activity log. Recovery never resends, unpauses or advances state. The deploy rollback also refuses to restart workflow services while any hold exists.

Invariants (and the reasons for them)

RuleReason
A session advisory lock, not FOR UPDATE, serialises a targetIt must persist across the run's several short transactions and survive COMMIT. If unlock fails, the connection is destroyed, because a pooled backend would keep the lock.
Reserved runs are capped at 80% of the poolA run needs a second connection; this prevents circular waits.
Output is read before actor.stop()xstate 5.30 clears output on stop.
buildInput may load data but never start provider effectsThe durable guard must see the actor's genuine initial snapshot.
Handoffs are durable rows; eager delivery is only a latency optimisationThe source commit always stands; the eager run uses a short lock budget so it doesn't starve inbound waiters.
Cross-machine signals use their own tableReaching into another machine's envelope "breaks encapsulation".
The registered set is boot-asserted against a literal listA lost registration fails boot instead of silently dropping runs.
Replies are sent by the caller after commit, after a staleness claimclaimLatestZubeTranscriptReplyForSend checks that the reply still answers the latest user message.
The runner is closed for extensionNew behaviour is a new machine file plus a registry entry. Client behaviour plugs in through typed hooks (Custom code).

Not every long-running job is a lead machine

The lead runner is target-keyed, settles within 240 s and holds a reserved connection. That is the wrong shape for multi-hour or non-lead work, so several other execution models exist:

ModelMechanismXState?
Addison Lee UC1 continuationpreHook consume + detached continuation under the runner's lease (60 min ceiling)no (runs under the lead runner's lease)
Addison Lee UC2 tick30 s cron, DB-backed claim of due actionsno
Client reportsprocessDueReports: CAS on next_run_at, janitor, report_runsno
CRM syncbackper-org orchestrator cron with preCrmSyncback hooksno
Agent previewpg-boss job → adapter preview surfaceno runner
RevOps checkpoint runs branchrevops-run queue, own claim/lease/heartbeat, in-memory actor run to completionyes, but not on the lead runner

The unapproved "managed runtime" proposal would fold these into one generic case lane on the runner core (see Direction).

Evidence
  • packages/workflows/src/runner/workflowRunner.ts:1-27,77-90,437-507,634-825: lifecycle, pool fraction, eager handoff, entry points
  • packages/workflows/src/runner/workflowRunnerExecutor.ts:116-929: admission, hold check, resolve, hooks, dispatch, tx_final, post-commit
  • packages/workflows/src/runner/workflowRunnerSettledSnapshot.ts:14-39: output before stop
  • packages/workflows/src/runner/snapshotCodec.ts:53-150: envelope validation and migrations
  • packages/db/src/schema/targets.ts:122-206,296-300,397-405: envelope schema and scan index
  • packages/workflows/src/machines/shared/actions.ts:1-142, actors.ts:1-132: lanes
  • scripts/grep-gates/runnerLaneAudit.ts:2-72,285: lane rules and scan globs
  • packages/repositories/src/workflowExecutionSafety.ts:18-275; workflowRunnerActorProtection.ts:183-258: send-safety hold
  • packages/workflows/src/runner/workflowRunnerEnvelope.ts:15-248: status derivation, restore-previous
  • planning_docs/workflow-envelope-scheduler-invariant/design.md:1-30

Machines & workflows

Nine machines are registered, and boot asserts that exact set. Five are defaults that run for every organisation. Four are client successors that only client hooks reach, and one of those looks dormant. No feature flag gates any machine. A lot of what people call "workflows" is not a machine at all: cadence configs, client hooks and crons.

TRIGGERS DEFAULT MACHINES (all orgs) SUCCESSORS CLIENT SUCCESSORS Inbound text WhatsApp · Messenger · IG jobs email poll (2 min) · webchat Voice outcome post-call job · ElevenLabs hook stale-call sweep (5 min) CRM records crmSyncer (3 min) emailCrmSyncer (5 min) on_text_message_received permissions → transcript → batch → agentic reply → send checks MESSAGE_RECEIVED Addison Lee preHook consumes run → UC1 drafts (never auto-replies) on_call_complete · instant short vs valid call · classify failure → cadence_step_failed CALL_ENDED on_crm_sync · instant CRM ref → phone → email → stub swap lock bootstrap → target CRM_RECORD_RECEIVED on_conversation_complete instant · coalesced per conversation Call Insights: score, summary, fields not-interested · reminders · WA follow-up handoff client getPostWorkflow (Stay Club · Lingua · MiCampus) outbound_messaging_cadence START → CALLING → COMPLETED WhatsApp template + email stages kill switch: outboundCadenceEnabled WAKE via next_action_at stay_club_crm_requested_ viewing_booking Stay Club · books viewing → cadence lingua_conversation_complete templated email, then restore micampus_call_complete extract booking · WA + emails client getPostWorkflow micampus_outbound_ whatsapp_dry_run · dormant Not machines CRM syncback · reports · UC2 tick Nexus jobs · insights rollups
The event type chooses the machine; org configuration never does. Org config (Foundry template, workflow_id, channel permissions, delays) is read inside a run. Client code plugs in only through typed hooks (preHook, getPostWorkflow, preCrmSyncback) keyed by (organizationId, machineId, businessWorkflowId).

Machine catalogue

machineIdStatusPurposeKey statesStarts onFlags
on_text_message_receivedGAInbound text on WhatsApp, Messenger, Instagram, email and webchat: permissions, conversation, transcript merge, batching wait, multimodal, agentic reply, persist, final send checks. Hands off to conversation-complete.checkPermissions → resolveConversation → mergeTranscript → waitForBatch → checkNewMessages → resolveAgenticTemplateStep → invokeAgenticReply → persistResponse / statusUpdateOn{Guardrail, HumanIntervention, NoResponse, NexusEscalation} → finalSendChecksMESSAGE_RECEIVED, WAKEstatusOnWake active; batching delay 180 s text / 600 s email unless configured; webchat never parks
on_call_completeGAFinalise a voice call: short vs valid, classification, not-interested write. On failure, signals cadence_step_failed to a sibling cadence.loadingConversation → classifyShortCall → invokingClassifier → short/validCallTerminalEmitCALL_ENDEDinstant
on_conversation_completeGAPost-conversation analysis: not-interested classifier, Call Insights (lead score 0–100, summary, structured fields), reminder reconciliation, WhatsApp follow-up template, transcript translation.shortCircuitLowTokens → classifyingNotInterested → generatingInsights → reconcilingReminders → applyingUpdates → triggeringFollowUp → translateTranscripthandoff from text / call machinesinstant; coalesced per conversationId
on_crm_syncGAResolve identity (CRM ref → phone → email → stub) on a bootstrap id, swap the lock to the real target, create or update the target from the CRM record, sync HubSpot owner.resolvingCrmRef → resolvingPhone → resolvingEmail → creatingStub → swappingLock → … → applyingHookGatesCRM_RECORD_RECEIVED (also used by manual import)instant
outbound_messaging_cadenceGA machine reached via client hooksA pure transducer for multi-stage outbound WhatsApp-template and email cadences. The runner does the scheduling maths, safeguards and provider sends.START → CALLING → COMPLETEDCADENCE_STARTED via handoff, WAKE, STEP_FAILED, REPLY_RECEIVED, PROVIDER_*per-org kill switch outboundCadenceEnabled (default true). The only producers are Stay Club, Lingua and MiCampus hooks.
lingua_conversation_completecustom: LinguaSend the templated post-conversation email (campus, language), then restore the predecessor.idle → delivering → doneLingua getPostWorkflow on conversation-completeinstant, restorePrevious
stay_club_crm_requested_viewing_bookingcustom: Stay ClubBook a CRM-requested viewing via calendar tools; confirmed / unavailable / clarification emails; may hand off to a cadence.idle → delivering → doneStay Club getPostWorkflow on CRM syncinstant; successor: cadence
micampus_call_completecustom: MiCampusAfter a MiCampus call: LLM booking extraction (confidence floor 70), WhatsApp template follow-up, per-residence booking-info emails.idle → delivering → doneMiCampus getPostWorkflow (prod + internal test org)instant
micampus_outbound_whatsapp_dry_runcustom: MiCampus dormantInternal-only observation cadence with no provider ports: it validates the handoff and restores. It was used before the live MiCampus cadence launched.idle → donenothing in code hands off to it any moreinstant

"Workflows" that are not machines

ThingWhat it isStatus
Outbound cadence configsZod-validated TypeScript data run by outbound_messaging_cadence. Stages are a discriminated union of whatsappTemplate | email, with windows, blackout dates and stop rules. SMS stages are not supported. There is no cadence builder UI; the only operator control is the account-level toggle.custom: Stay Club (12 contact cadences, university fair, Meta Ads variants, Hanger Lane redirection), MiCampus (Google Ads, en/es/pt), Lingua outbound (es / pt_BR / en by phone region); Lingua revival cadence registered, no producer found
Client hookspreHook (can consume a run), postHook, getPostWorkflow (pick a successor), shouldRunPost*, preCrmSyncback, keyed by (organizationId, machineId, businessWorkflowId). Registered in code at boot, never in a DB table.custom (see Custom code)
Addison Lee UC1preHook on on_text_message_received for the sales inbox: consumes every run (Zube never auto-replies) and runs a draft-only prospecting pipeline under the leasecustom: Addison Lee, scheduler only
Addison Lee UC2campaign-reply preHook + 30 s cron for a one-off cold outbound campaigncustom: Addison Lee removal scheduled late Nov 2026
on_crm_syncbacka hook key used by the non-XState syncback serviceGA service
workflow_outboxtable retained after outbound customer webhooks were deletedlegacy, unused

How org configuration maps onto machines

  • The event type picks the machine. MESSAGE_RECEIVED → text, CALL_ENDED → call-complete, CRM_RECORD_RECEIVED → CRM sync, CADENCE_STARTED → cadence. Handoffs name their successor explicitly. Configuration never selects a machine.
  • targets.workflow_id is a free-text "business workflow id" (default __default__). It keys Foundry template lookup, client hook lookup and cadence ownership. There is no workflow-definition table and no "goals" entity in the schema.
  • Foundry templates (agentic_messaging_templates) are where orgs configure the agent. Each has templateKind text|voice. Text templates require a persisted graphDefinition; voice templates forbid one and point at an ElevenLabs externalAgentId. Templates also carry channelScope, workflowId, guardrails[], fast-reply settings, disableHumanHandoff, restrictKnowledgeToWorkflowOnly and status draft|active|inactive. Inside a run, resolveAgenticTemplate picks the webchat widget's template first, else the active template for (org, workflowId, channel), with a default-workflow fallback. Multiple matches raise an urgent audit.
  • Channel permissions (read, send, help-needed) live on each integration row and are resolved per channel inside the machine.
  • Delays come from contactPreferences.{text,email}ResponseDelaySeconds or a per-target override.
Evidence
  • packages/workflows/src/registerDefaultMachines.ts:186-303; packages/workflow-composition/src/defaultMachines.ts:27-90
  • packages/workflows/src/clients/registerClients.ts:62-167,176-542: expected machine ids, hook keys, client successors, cadence registry
  • packages/workflows/src/runner/workflowRunnerResolution.ts:153-183: event → machine
  • packages/workflows/src/machines/textMessageGraph.ts:24-943, onConversationComplete.machine.ts:173-946, onCrmSync.machine.ts:33-72, onCallComplete.machine.ts:1-113, outboundMessagingCadence.machine.ts:1-998
  • packages/workflows/src/clients/micampus/cadences/outboundDryRunCadence.ts:7-78: dormant dry run
  • packages/workflows/src/registry/outboundCadenceRegistry.ts:49-273; packages/workflows/src/runner/cadenceProviderSendHook.ts:34-35 (no SMS stages)
  • packages/db/src/schema/agenticMessagingTemplates.ts:133-286; packages/workflows/src/machines/textMessageTemplateActor.ts:150-243
  • packages/db/src/schema/contactPreferences.ts:93-99; workflowRunnerCadence.ts:535-557: cadence kill switch

Agentic replies & the LLM layer

All model traffic goes through one client, LlmClient in packages/llm. Call sites name a semantic tier (gpt.fast, claude.smart…), never a model id. Customer replies come from a persisted planner → tools → finalizer graph that each organisation configures in Foundry. Deterministic host code validates every output, and no reply is ever canned: when nothing valid comes back, Zube stays silent and escalates to a human.

Context assembly agenticReplyAdapter.ts • Foundry template graph • base + node prompts • company profile JSON • contact profile + local time • transcript (+ webchat continuation context) • guardrails · images • tool schemas ∩ graph keys webchat: fast path (gpt.nano) Persisted graph (executeAgenticGraph) · ≤ 20 steps · ≤ 6 tool rounds · never retried as a whole Planner node(s) structured step output (Zod) tool_task · guardrail_directive escalate / redirect · routeHints Nexus is invisible to the planner Tool node allowedToolKeys enforced Zod-validated input · timeouts write success ⇒ exit loop selection loop on gpt.smart Finalizer gpt.smart · 3 attempts host validation of draft Nexus grounding rules action + value guards tools_condition returnTo planner done (or forced exit after a Nexus result) Knowledge: knowledge_search_rag · knowledge_get_full_context → Nexus researcher (not webchat) Calendar: get_availabilities · create_booking (write) · get_booking_link (magic link) Also: internal_escalate_to_human · client custom tools (MiCampus, Road Scholar, Lingua) responded persistAgentReplyIfStillLatest → finalSendChecks → send (after commit, outside lock) responded_and_escalated respondAndEscalate guardrail, partial / conflicting Nexus suppress + escalate no usable generated reply → help_needed + take-over row NEVER a canned fallback Guardrails: the LLM matches, code counts Template guardrails (redirect · escalate · respondAndEscalate) carry a stable guardrailId. The planner only reports a guardrail_directive; deterministic code counts prior hits per id over a 3-day lookback and decides escalation (escalateAfterX 1–10). Model routing (packages/llm/src/models.ts) Call sites name a tier, never a model id. gpt.ultra = gpt-6.1-sol; gpt.smart/fast/nano = gpt-6-luna; claude.* = Bedrock Sonnet 5; gemini.* = gemini-3.8-flash. Authored gemini.* tiers run on gpt.* first, with cross-provider structured-output fallback. UK/EU-pinned Bedrock clients disable fallback.
Customer replies always come from this graph. Every LLM output is a Zod-validated object, and deterministic host code decides what ships: send-ability, guardrail counts, Nexus grounding, action claims and numbers. When nothing valid comes back, the system escalates silently rather than sending text a human didn't write and the model didn't produce.

The reply pipeline, step by step

  1. The machine reaches invokeAgenticReply in on_text_message_received, after the permission, transcript and batching steps. It invokes generateAgenticReply, a bounded actor (600 s) built by buildGenerateAgenticReply (packages/workflows/src/defaults/agenticReplyAdapter.ts). The agentic graph is the only reply path; legacy non-agentic paths were removed.
  2. Template gate. With no active template or graph, the result is no_response_needed, treated as a config issue already reported upstream.
  3. Context assembly. Inputs are the default system prompt plus the company profile JSON, the template base prompt, node prompts, a contact profile (target minus internal fields, plus local time; ad-click attribution is pinned in it), transcript lines (and, for webchat continuations, a block of historical context marked as never-instructions), knowledge snippets, guardrails, images, and client tool schemas intersected with the graph's allowedToolKeys.
  4. Webchat fast path. On web_chat, a single generateObject (default tier gpt.nano) can produce the planner stage and the final output together, under the same finalizer validation. If a tool is needed or the output is invalid, it falls back to the full graph. It never executes tools.
  5. Planner node(s). Structured step output (Zod): tool_task, guardrail_directive (which guardrail id matched), escalate/redirect directives, route hints. Generation is retried up to 3 times; "missing planner output must never become a hardcoded conversational reply".
  6. Tool node. Enforces allowedToolKeys, Zod-validates inputs, applies per-tool timeouts, and skips duplicate successes. Any successful write side effect forces the loop to exit, so it can't double-book or double-send. Limits: ≤6 tool rounds and ≤20 graph steps.
  7. Finalizer. Defaults to gpt.smart (the template node can set its own tier), 3 attempts. The draft must pass host validation (guardrail and escalation overrides, usable-draft check, Nexus grounding/action/value guards, the human-handoff-disabled rule). When attempts run out, suppressUnusableReply sets shouldRespond=false, escalateToHuman=true.
  8. Adapter post-processing. The whole graph is never retried, because tools may already have acted. shouldRespond with an empty message becomes an escalation. The result's completionReason is one of responded · responded_and_escalated · guardrail_violated · human_intervention_requested · no_response_needed. The adapter also returns a Nexus citation snapshot and a knowledge-gap observation draft.
  9. Machine post-steps. A deterministic guardrail hit count (3-day lookback per guardrailId), then persistAgentReplyIfStillLatest (rejects a stale basis), then finalSendChecks (re-reads status; override, help_needed or paused blocks the send). The caller sends after commit.

Tools the agent can call

Tool keyEffectNotes
knowledge_search_rag (+ typo alias knowledge_serach_rag) · knowledge_get_full_contextreadOn every text channel except webchat, bound to the Nexus researcher (full-corpus, evidence-only). On webchat, bound to legacy vector search, which is disabled unless preloaded. See Nexus.
calendar_get_availabilitiesreadCalendly / Microsoft calendar slots, shared with the voice tool service
calendar_create_bookingwrite, non-repeatable240 s timeout; cross-process slot lock
calendar_get_booking_linkwriteIssues a 7-day magic booking link
internal_escalate_to_humanwriteAlways allowed
Client custom toolsper toolMiCampus get_properties, get_booking_link, send_booking_link_via_whatsapp (write); Road Scholar get_trip_list; Lingua get_enrollment_link. The same definitions serve voice and text.

There is no CRM-lookup tool. CRM data reaches the agent only as fields on the target profile. The default system prompt hard-codes an education "enrollment advisor" persona; templates override it through base and node prompts (unverified how fully that neutralises it for non-education tenants).

Model tiers

TierProvider · modelEffortTypical use
gpt.ultraOpenAI · gpt-6.1-solhighNexus source-memo researcher, content-insight curation, demo draft generator
gpt.smartOpenAI · gpt-6-lunahighfinalizer, Call Insights, multimodal analysis, tool selection, image OCR
gpt.fastOpenAI · gpt-6-lunalowclassifiers, reminders, client semantic routing, drop-off explanation, lead assignment
gpt.nanoOpenAI · gpt-6-lunanonewebchat one-call fast path, calendar param normalisation
gemini.smart/fast/nanoVertex · gemini-3.8-flashmedium/low thinkingRewritten to gpt.* on the first attempt (except video); Gemini becomes the fallback
claude.smart/fast/nanoBedrock · us.anthropic.claude-sonnet-5 (one model, three efforts)high/medium/lowstructured-output fallback; eu. prefix when the AWS region is EU
  • Residency-pinned clients. buildRegionalInferenceLlmClient serves gb (Bedrock eu-west-2, Sonnet 4.6 / Opus 4.6: Addison Lee pipeline) and eu (eu.anthropic.claude-sonnet-5-5: the email relevance/spam gate for every tenant), with no cross-provider fallback. The per-org llmInferenceRegion setting exists but only the lead-lifecycle classifier reads it.
  • Decision model. Small probabilistic choices (escalation rule Tier 2 at ≥0.95 confidence, the shadow lead-lifecycle stage, Lingua campus selection, Nexus taxonomy matching) go to microsoft/microsoft-decision-1 via OpenRouter. The code calls it "Jev". On the unmerged RevOps branch, all Decision-1 traffic moves to Azure Foundry and needs new prod keys before deploy.
  • Other models. Vertex gemini-embedding-2 (3072-dim) for knowledge; ElevenLabs Scribe (fallback OpenAI gpt-4o-mini-transcribe) for audio; OpenAI web_search with a Gemini grounding fallback; OpenAI batch first and Vertex batch as fallback for scheduler batch work.

Client mechanics worth knowing

ConcernBehaviour
Structured outputCallers pass natural Zod to generateObject. The client transforms it for OpenAI strict mode (all fields required, optionals nullable), then reconciles back before Zod parses. A gate forces every production caller through this path; dynamic JSON-Schema access is allowlisted to three files (custom analyzers among them). OpenAI uses Chat Completions, not Responses, for structured output.
Retries & fallbackThe client owns retries (ai-sdk retries are off): up to 3 on the primary, 1 per fallback provider, 5 total, 45 s per attempt by default. 401/403 and deterministic 4xx don't retry. The fallback chain is cross-provider unless disabled per client or per call.
CancellationEvery call merges the caller's abort signal with the workflow-execution authority and asserts that the lease is still held.
Telemetry$ai_generation + vendor_usage_recorded to PostHog, metadata only (prompts and completions never leave). Cost rates are best-effort; vendor invoices are the truth. There is no spend cap.
Prompt cachingOpt-in Bedrock cache points exist in the client, but no production caller uses them yet.
EvalsOnly deterministic gates: bun run llm:migration-evals (scripted doubles per workload group) and the phase-2 baseline harness. There is no LLM-judge or golden-reply suite. Live probes must use the production buildLlmClient and the exact prompt (guidance/local-oneoff-llm-probes.md).

Guardrails: "the LLM matches, code counts"

Template guardrails come in three types: redirect, escalate and respondAndEscalate (redirect and respondAndEscalate carry escalateAfterX 1–10). Each carries a stable hidden guardrailId. The planner only reports which id matched. Deterministic code counts prior hits for that id in the same conversation over a 3-day lookback and decides: escalate always escalates, respondAndEscalate escalates once total hits reach the threshold, and redirect escalates once prior hits do. Urgent rows then go through escalation-rule routing: structured rules, then the decision model, then the default (see Intelligence).

Every other LLM-backed feature (by where it runs)

Runs inFeatures (tier)
on_conversation_completeCall Insights: lead score, summary, ~15 structured fields, reminder extraction (gpt.smart) · not-interested (gpt.fast) · audit-event classification · transcript translation · reminder reconciliation · WhatsApp follow-up template pick/fill
text machineinbound media: audio, image, document (gpt.smart); video (gemini.smart, no fallback)
voiceinbound call dynamic variables · call result classification · transfer destination matcher (gpt.fast) · imported-call speaker attribution (gpt.smart)
cadencesemail stage content (persisted tier, default gpt.fast) · WhatsApp stage template selection
client hooksStay Club cadence selection and booking extraction, Lingua email routing / CRM fields / campus, MiCampus call-complete extraction (gpt.fast + Decision-1)
apiFoundry graph generation (gpt.smart) · public voice demo draft (gpt.ultra) · Nexus ingest curation · Test Nexus
schedulercontent normalisation + daily loss reasons (batch) · deferred sentiment + custom analyzers (batch) · curation (gpt.ultra) · drop-off explanation · reminders · email relevance gate (EU Bedrock) · crm@ contact parsing · knowledge-gap grouping + embeddings · Nexus taxonomy · Addison Lee pipeline (GB Bedrock)
Evidence
  • packages/llm/src/models.ts:37-250: tiers, rates, gemini→gpt rewrite, EU prefix, fast-mode notes
  • packages/llm/src/clientGeneration.ts:146-153,494-498; structuredOutputFallbacks.ts:4-17; providerRetry.ts:18-121
  • packages/llm/src/regionalInference.ts:18-124; packages/services/src/insights/leadLifecycle/conversationClassifier.ts:125-130
  • packages/llm/src/agentic/executor.ts:207-371, plannerNode.ts:294-533, toolNode.ts:755-978, finalizerNode.ts:296-945, webchatOneCall.ts:50-760, constants.ts:1-27
  • packages/workflows/src/defaults/agenticReplyAdapter.ts:114-984: context, tool binding, outcomes
  • packages/llm/src/agentic/builtInToolCatalog.ts:26-170; packages/client-tools/src/tools/clientVoiceTools.ts:54-130
  • packages/workflows/src/machines/textMessageGuardrails.ts:23-569: deterministic guardrail counting
  • scripts/grep-gates/structuredOutputBoundary.ts:1-58; packages/llm/src/openAiStrictSchemaTransform.ts:1-440
  • packages/analytics/src/llmHook.ts:44-170; packages/llm/src/jevTransport.ts:12-45; escalationRuleDecision.ts:17-89

Voice

Voice is inbound-only. Telnyx carries the PSTN call and Zube's telephony-infra drives call control. The AI voice is an ElevenLabs Conversational AI agent reached over a SIP leg, and it calls back into Zube for tools (calendar, transfer, per-client functions). After the call, the recording becomes a voice-post-call job and the same workflow machines as text take over.

Caller dials a Zube DID Telnyx Leg A caller · Leg B AI (SIP) Leg C human transfer recording · signed events telephony-infra POST /telnyx/event → ack, then background handler 1 · call.initiated: DID → org, template, externalAgentId · answer 2 · disclosure / consent gather (DTMF) 3 · ensureInboundConversation (background) 4 · dialSip → sip.rtc.elevenlabs.io 5 · bridge / ambient conference 6 · hangup teardown · recording saved call state in memory: deploys wait for 0 calls webhooks commands ElevenLabs Conversational AI agent configured in ElevenLabs (not from this repo) calls Zube server tools (Basic auth): /voice-tools/elevenlabs/inbound_call_init calendar_list_slots · calendar_create_booking telnyx/transfer_to_human · custom/:client/:fn knowledge: synced KB folder (manual, admin) SIP leg tool calls worker · voice-post-call consumer find conversation by callSessionId native ElevenLabs transcript, else Scribe STT (stereo) persist → runner.handleEvent(CALL_ENDED) pg-boss voice-post-call job webhooks · POST /elevenlabs/event post-call webhook → inbound-event job worker skips it when Telnyx owns the call CALL_ENDED → machines on_call_complete → on_conversation_complete lead score, summary, fields, WA follow-up Transfer to a human (blind) agent calls transfer_to_human (or auto check) schedule + hours gates; LLM picks destination leave conference, bridge AI back to caller, then Telnyx transferCall on Leg A per destination in order exhausted → no-consent audio, or back to AI (Leg D re-dial) no warm/whisper transfer code exists
Inbound voice. The AI voice is ElevenLabs, reached over SIP from Telnyx. Zube owns call control, the server tools the agent calls, and all post-call processing. No code path places an outbound AI phone call to a lead. Public website voice demos are a separate path (Retell / ElevenLabs web sessions from apps/api).

Components and responsibilities

PieceOwns
TelnyxPSTN legs, answer/gather/playback/record, SIP dial, transfer, bridge, conferences; ed25519-signed webhooks; CDRs for cost rollups
telephony-infraDID → org/template resolution, disclosure and consent IVR, dialling ElevenLabs, AI handoff (bridge or ambient conference), transfers, hangup teardown, recording download to GCS, enqueuing post-call work. Call state is an in-memory store keyed by call_control_id (600 s TTL), which is why deploys wait for zero active calls.
ElevenLabs agentThe conversation itself. It is configured in ElevenLabs, and no code in this repo creates or updates agents (the wrapper's createAgent/updateAgent have no production caller). Knowledge comes from a KB folder that Zube syncs manually (admin action).
Zube server toolsinbound_call_init (first message + dynamic variables, partly LLM-filled), calendar list/book, transfer tools, custom client tools. Basic auth with a shared secret.
workervoice-post-call: find conversation by callSessionId, prefer the native ElevenLabs transcript, else ElevenLabs Scribe STT on the stereo recording (speaker by channel), persist, then handleEvent(CALL_ENDED).
Machineson_call_complete (short vs valid, classification) → on_conversation_complete (Call Insights, follow-up WhatsApp template) → client successors such as micampus_call_complete.

Call state progression

answering → gathering_ivr → playing_no_consent → dialing_elevenlabs → ringing_and_dialing → bridging → bridged_to_ai → transferring → bridged_to_human | transfer_failed → ended

  • Consent. If a disclosure is configured, a DTMF gather plays it. Digit 1 or a timeout means consent; digit 2 plays the no-consent audio. If the gather fails to start, the call is hung up rather than skipping the disclosure.
  • DB work is off the media path. ensureInboundConversation (target and conversation upsert, endpoint workflow routing) runs in the background while the SIP dial proceeds.
  • Transfer is blind. Forwarding schedules and hours rules gate it, and an LLM matches the destination label. The AI leg is bridged back to the caller, then Telnyx transferCall runs on the caller's leg for each destination in order. When destinations run out, the call either plays no-consent audio or returns to the AI (a fresh SIP leg if needed). There is no warm or whisper transfer code.
  • Transfer outcome buckets in insights: completed · reachedNoPickup · callerHangup · failed · notAttempted.
  • Duplicate post-call paths. ElevenLabs also posts a post-call webhook. The worker skips it when Telnyx owns the call, and dispatches CALL_ENDED itself only for calls Telnyx didn't route.

What voice does not do

CapabilityStatusDetail
Outbound AI calls to leadsremovedRemoved on purpose in the multi-app split Phase 2 ("all AI outbound calling (legal)"). Some comments still mention an "outbound bootstrap" that no longer exists.
Zube-side knowledge retrieval during callsnot builtVoice knowledge is whatever ElevenLabs retrieves from the synced KB folder. Workflow-scoped knowledge doesn't reach voice.
Native realtime audio (OpenAI Realtime / Gemini Live)plannedplanning_docs/native_audio is a draft test plan ("voice actor + stronger supervisor"); there is no code and Telnyx has no media streaming yet.
Outbound voice hold detectionplannedResearch only, off-repo (per owner notes, not verifiable from the repo).
Imported calls (Vodafone OneNet)platform code built for MiCampusZip upload → mono diarised STT → LLM speaker attribution → completed voice conversation. Backfill only: no workflows fire. See Channels.
NICE CXonepartialConnect and settings only; no call sync job.
Public website voice demosadmin-managedBrowser WebRTC sessions via Retell or ElevenLabs tokens from apps/api, with no telephony involved. See Platform.
Evidence
  • apps/telephony-infra/src/inbound/telnyx/dispatch.ts:12-16,139-449: ack-then-background, dedup, event switch
  • apps/telephony-infra/src/inbound/telnyx/events/callInitiated.ts:66-226, callAnswered.ts:1-446, internal/dialElevenLabs.ts:10-210, internal/elevenLabsSipUri.ts:3-45
  • apps/telephony-infra/src/inbound/telnyx/state/callState.ts:14-37, stateStore.ts:1-36: in-memory state
  • apps/telephony-infra/src/inbound/telnyx/internal/transferSequence.ts:1-333, toolCalls/transferToHuman.ts:1-91
  • apps/telephony-infra/src/app.ts:78-115,146-161: /ready active calls, voice-post-call enqueue
  • apps/worker/src/inbound/telnyx/internal/processRecordingTranscript.ts:109-166, recordingCompletion.ts:110-186
  • apps/worker/src/inbound/elevenlabs/eventProcessor.ts:1-15,775: skip when Telnyx owns the call
  • packages/ports/src/elevenLabs.ts:250-258: agent CRUD with no production caller
  • planning_docs/multi-app-split/worker-split.md:7,27; commit 2b5147e32: outbound AI calling removed
  • packages/services/src/insights/dailyMetricsReducer.ts:133-204: transfer outcome buckets

Data model & connectors

Postgres is the only system of record. The Drizzle schema in packages/db/src/schema/** is the source of truth: over 110 tables (plus the pg-boss schema, which Drizzle does not model) and 98 migrations (0000–0097; the baseline is locked). Tenancy is enforced in the application through organization_id plus dozens of composite (organization_id, id) foreign keys; there is no row-level security. Every third-party call goes through a connector wrapper that owns its KMS-wrapped credentials.

targets (one row per lead) identity: phone · email · socialMediaAccounts · targetChannelRefs crmSourceReferenceId · crmInformation · attribution analysis: leadScore · summary · interest · concerns… workflow: workflowId · workflowStatus · workflowState · nextActionAt ownership: primaryOwnerUserId · assignment events organizations (tenant root)settings JSONB: companyProfile,escalationRules, callSettings… users · user_groupsFirebase uid, ACL, channel scope,CRM owner ids, locale, uiMode integrationsone row per (org, type, instance)18 types · KMS creds · status agentic_messaging_templatesFoundry: graph, guardrails, voice agent id conversationsone thread per target per channel;messages = JSONB transcript voice callsconversations with channel='voice'recording → file_storage CRM Sync V2sync states, snapshots, ledgers,outcomes, conversion projections audit_trail · remindersthe client's activity log insights aggregatesdaily/monthly metrics + content (HLL)HMAC pseudo-id facts, observations knowledge (Nexus)versioned, workflow-scoped docsvector(3072) + halfvec HNSW · gaps runner & ingress tablesworkflow_handoff_pending · target_workflow_event_pending · pending_text_events · webhook_receipts · pgboss.*
Provider identifiers map into a target, never the other way round. Conversations, calls, workflow state, CRM sync and analytics all key off target_id. Automated writers may fill only blank identity fields.

Schema by domain

DomainKey tablesNotes
Tenancy & accessorganizations, users, user_groups, organization_feature_flags, customer_change_requestsOrg settings live in JSONB columns. Feature flags are per-org booleans by key.
Lead identitytargets, target_assignment_events, target_lifecycle_stagesWhatsApp looks up by phone or BSUID; Messenger/IG by (channel, platformAccountId); webchat by web_chat::<uuid>. targets.attribution (migration 0097) holds the first and last ad click.
Conversationsconversations, pending_text_events, webchat_turn_outcomes, email_tracking_events, sentiment_analysis_observations, file_storagechannel_type: voice, zube, sms, whatsapp, email, web_chat, messenger, instagram. Transcript messages carry source, provider ids, delivery status, edit history, generatedReplyBasis.
Workflows & templatesagentic_messaging_templates, workflow_handoff_pending, target_workflow_event_pending, agent_preview_runs, workflow_outbox (unused)Workflow state itself is on targets.
Integrationsintegrations, monday_oauth_app18 types: whatsapp, hubspot, monday, salesforce, freshsales, dynamics, microsoft_email, google_email, facebook_messenger, instagram_account, microsoft_calendar, calendly, api (legacy), web_chat, custom_secret, nice_cxone, microsoft_teams, microsoft_sharepoint. configVersion is a CAS token for saves.
CRM synccrm_sync_states (lanes: target_property, conversation_artifact, outcome_read, field_provisioning, pull_retry), snapshots, ledgers, field verification, outcome configs/observations, stage measurements, conversion projectionsOutcome configs are immutable epochs; observations are change-only; projections are rebuildable read models.
Bookingscalendar_booking_slot_locks, magic_links, magic_links_daily_metricsNo bookings/appointments table; booking truth is still targets.callBooked (calendar-booking-truth is planned).
Audit & remindersaudit_trail, reminders, notification_cooldown_ledgersystem_issue rows are diverted to logger.error instead of being stored.
Insightsdaily_metrics, daily/monthly content insights, content_insight_facts, insight_categories, curation state, drop-off/loss/lifecycle/sales-motion observations, 8 historical_regeneration_* tablesHLL sketches for unique counts; HMAC pseudo-ids in facts. See Intelligence.
Knowledgeknowledge_documents, knowledge_chunks, ingest sessions/sources/candidates, corpus revisions, query observations, gap findings/occurrences, 12 taxonomy tablesSee Nexus.
Jobs & ingresspgboss.* (migrations 0076/0083, not modelled by Drizzle), manual_import_batches/_rows, scheduler_checkpoints, webhook_receipts (14 d expiry, PII)
Reports · proposals · demos · RevOpsreport_definitions/report_runs · client_proposals/_accesses · public_voice_demo* · revops_deals, revops_deal_targets, revops_conversations, revops_deal_daysProposals and demo tables are global (no org).
Schema change workflow. Edit the schema, run bun run db:generate, and commit the numbered SQL, its snapshot and _journal.json; delete the previous snapshot. Never push to production. Migrations run on deploy, from the api image with the migration role, and are never reversed on rollback, so they must stay compatible with the previous release (expand, then contract). CREATE EXTENSION for vector/hll/pgcrypto is not in the migrations; production presumably enabled them out of band (unverified).

Connectors (packages/external-connectors/*)

PackageProvidersCapabilitiesAuth
crmHubSpot · Salesforce · Dynamics 365 · Freshsales · monday.comupsert/find contact, delta lists, batch read/write, activities/tasks, owners, identity candidates + merge (Freshsales: no property syncback, but it can create tasks and log activities)OAuth + KMS (HubSpot, Salesforce, monday); Freshsales API key; Dynamics Entra app-user via MSAL (nothing persisted)
emailGmail · Microsoft Graph mail · Gmail service account (crm@getzube.com)list/get, send, reply, draft, forward, delta (Microsoft)delegated OAuth + reactive refresh; mismatch guard
calendarsCalendly · Microsoft Graph calendarslots, booking, event types, scheduling linksOAuth + KMS. No Google Calendar.
metaWhatsApp Business (Cloud API, Embedded Signup, coexistence) · Messenger · Instagramsend, media, templates, webhook verification, WABA admin, history syncTech Provider business token, no refresh; 401/403 → auth_error, operator re-onboards
telnyxCall Control · Messaging (SMS, unused)call legs, SIP dial, transfer, conferences, CDRsplatform key from env
voiceElevenLabs · Retellconversations, transcripts, recordings, KB docs, agent CRUD (unused) · Retell web calls for demosplatform key · KMS envelope for Retell
contact-centerNICE CXoneread-only: token exchange, completed contacts, routing optionsKMS access key
prospectingLushalookalikes, decision makers, email revealscustom_secret (decrypted in the scheduler composition root; a deviation from "wrappers own decrypt")
client-customZoomInfo (Addison Lee only)search, enrich, lookalikes, usagecustom_secret
shared—fetch client, runWithAuthRefresh loop, refresh locks, test doubles—

The wrapper rules: decrypt → request → on a 401, take a singleflight refresh, re-read the latest credentials (a sibling may have rotated them), persist, mark healthy and retry once; otherwise flip to auth_error. Refresh is reactive only, never proactive. Provider responses are parsed with non-strict Zod (schema only what you read). Every package ships /testing doubles; vi.mock of connectors is gate-banned. scripts/grep-gates/noDirectExternalProviderAccess.ts keeps provider hostnames out of every other package. New hosts go in PROVIDER_HOST_TOKENS in the same change (the list currently misses a few hosts used inside connectors, e.g. gmail.googleapis.com).

Supporting adapters

  • packages/gcp: KMS cipher with a versioned envelope, GCS (signed uploads, knowledge store, webhook spool), Vertex batch, the Cloud SQL backup monitor job.
  • packages/notifications: Amazon SES only (escalation emails, system-issue emails, report delivery, password setup, proposal codes). No Slack, no push. Audit-row dispatch happens after commit and is stripped inside transactions.
  • packages/analytics: PostHog (EU). Closed event-name union, PII redaction, sampling, LLM cost telemetry, and the error-reporting logger that mirrors every logger.error to PostHog error tracking.

CRM sync in one paragraph

All CRM sync runs in the scheduler. Pull: crmSyncer walks each org's enabled mappings every 3 min, lists records updated since the mapping's lastSyncAt anchor, and dispatches CRM_RECORD_RECEIVED into on_crm_sync. Push: crmSyncbacker runs on a 5 min window with 2 min of overlap. It builds per-object payloads from slot mappings (summary, leadScore, leadStatus, insights, conversationHistory), applies client preCrmSyncback hooks, batch-upserts; the HubSpot arm also runs a drift filter against current CRM values. Freshsales syncback is structurally impossible. Escalation tasks and conversation notes go through reserve→resolve ledgers. CRM Sync V2's Track A (outcome read) and the Track B safety substrate are built; replacing the split legacy/V2 target-property writer with one canonical writer is approved but not verified in code.

Evidence
  • packages/db/src/tenantModel.ts:3-191: tenant invariants
  • packages/db/src/schema/targets.ts:80-405, conversations.ts:22-673, integrations.ts:419-695, integrationCredentials.ts:4-216
  • packages/db/src/schema/knowledgeEmbeddings.ts:4-18: halfvec cast for 3072 dims
  • packages/repositories/src/repositoryModule.ts:184-306; targets/identityWriteAuthority.ts:5-8
  • packages/external-connectors/shared/src/authRefreshFlow.ts:1-11; meta/src/whatsappBusinessApp.ts:705-751
  • packages/services/src/crmWorkflows/syncOrchestrator.ts, syncBackOrchestrator.ts:2-46, shared/syncAnchor.ts:1-20, shared/hooks.ts:1-25
  • packages/notifications/src/index.ts; packages/analytics/src/errorReportingLogger.ts:128-178
  • guidance/engineering-constraints.md:84-93,113-119

Everything that exists

The master inventory: every machine, client hook, cadence, channel, cron, queue, page, admin tool, ops script, removed feature and branch-only item found in this checkout, each with its maturity status. Much of Zube is not visible in the UI. It lives in per-client code, scheduler crons and true-admin pages, so read this list before assuming something does not exist.

How gating works. A status label here is code evidence only. It never claims adoption. Which organisations use what (flags on, UI mode, settings) cannot be determined from code; it would need a tracked prod-db-read.
  • Org feature flags (4, all default off). Rows in organization_feature_flags; a missing row means off. Keys: insights_conversion, nexus_taxonomy, lead_lifecycle_stage (shadow), revops_deals. Server gate organizationFeatureProcedure(permission, featureKey): a true admin bypasses both ACL and flag; everyone else needs both. The web OrganizationFeatureGate renders not-found when the flag is off. Toggled at /admin/feature-flags; each toggle writes an internal Changes entry.
  • UI mode. Per-user users.ui_mode: classic (default) or new ("UI 2.0"). Users switch it themselves in User settings. Some pages exist in only one mode (Deals and per-channel setup are New-only; the Reminders page is Classic-only).
  • Env gates. SCHEDULER_ENABLED (default false): when false, the scheduler registers no crons and the worker registers no dispatcher ticks. POSTHOG_ENABLED (job enabledEnvVar) gates the three vendor-cost crons. OPENROUTER_API_KEY wires the Decision-1 clients. GCP_STORAGE_BUCKET enables the webhook spool drain.
  • Settings toggles. defaultContactPreferences.outboundCadenceEnabled (default true, an account kill switch), emailSettings.oneClickUnsubscribeEnabled, accessControlSettings.assignment.enabled / .escalation.enabled, voice no-consent and human-transfer routing .enabled, phone-line ambientSound, escalation-rule CRM-task directives. All default off except the cadence switch and escalation rules. revivalSettings and inferenceSettings are admin-only to write.
  • Per-widget config. Web chat is set up per widget; webchat continuation to WhatsApp/email is disabled by default per widget.
  • Admin-only. trueAdminProcedure (server), AdminOnlyGate (routes) and AdminOnlyOverlay (sections inside customer pages) follow the logged-in Zube human (@getzube.com domain), so an impersonating admin keeps access. adminProcedure is defined but has no call sites.
  • Per-client code. Hard-wired to an organisation ID under packages/workflows/src/clients/** or packages/client-tools/src/clients/**, registered at startup with no DB table; boot fails if expected machines or hooks are missing (Addison Lee is checked separately and does not block boot).
  • No "beta" labels. No route or UI string says beta, experimental, coming soon or labs. The only explicit maturity label is "(shadow)" on the lead_lifecycle_stage flag. The "Gated" filter below is this document's label for built-but-off-by-default features.
AreaFeature / workflowStatusWhat it does (one line)Runs inTrigger / surfaceNotes
Lead workflowson_text_message_receivedGAAgentic reply to an inbound text: permissions, conversation, batching wait, reply, persist, final send checks.worker / scheduler (runner)MESSAGE_RECEIVED from WhatsApp, Messenger, Instagram, email poll, web chatHands off to on_conversation_complete. Default machine for every org.
Lead workflowson_call_completeGAFinalises a voice call: short-call vs valid, classification, not-interested write.worker / scheduler (runner)CALL_ENDED from ElevenLabs post-call, Telnyx recording completion, stale-call sweepOn failure enqueues cadence_step_failed for a sibling cadence. Hands off to on_conversation_complete.
Lead workflowson_conversation_completeGAPost-conversation analysis: Call Insights, categories, not-interested, reminders, audit classification, follow-up WhatsApp template, transcript translation.worker / scheduler (runner)Handoff from text or call; webchatIdleFinalize for web chatAlso starts the lead_lifecycle_stage shadow classifier when that flag is on. Client getPostWorkflow may add a successor.
Lead workflowson_crm_syncGAResolves identity (CRM ref → phone → email → stub) and creates or updates the target from a CRM record.scheduler / worker (runner)CRM_RECORD_RECEIVED from crmSyncer, emailCrmSyncer, manual CSV importRuns for any org with a CRM integration.
Lead workflowsoutbound_messaging_cadenceGA engine custom: startPure transducer for multi-stage WhatsApp-template and email cadences; the runner does scheduling, safeguards and sends.scheduler / worker (runner)CADENCE_STARTED via handoff; woken by checkAwaitingActionThe only producers are client hooks (Stay Club, Lingua, MiCampus). No cadence builder UI. Honours outboundCadenceEnabled.
Lead workflowsChannel-to-workflow routing (endpoint assignment)GAAn inbound message on an endpoint moves the target onto that endpoint's business workflow and writes a config_change audit row.worker / telephony-infraInbound Instagram, Messenger, ElevenLabs, TelnyxPaused and override targets are protected. (planning doc says "Status: draft" — stale.)
Lead workflowsSend-safety hold (execution-safety hold)GAPersists a hold before a provider send so a second runner never repeats a send of unknown outcome; pauses and escalates instead.worker / scheduler (runner)Any provider send under a lost DB sessionWrites a deterministic take-over audit row. Conservative false-positive holds are possible.
Lead workflowsReply delaysGAText and email reply delays from contactPreferences or a target override (defaults 180 s / 600 s).runnerOrg contact preferencesWeb chat never parks.
Client machines & hookslingua_conversation_completecustom: LinguaPicks and sends a templated post-conversation email (template key, campus, language), then restores the predecessor.worker / scheduler (runner)Handoff from Lingua on_conversation_complete getPostWorkflowHTML templates en/es.
Client machines & hooksstay_club_crm_requested_viewing_bookingcustom: Stay ClubBooks a CRM-requested viewing through calendar tools; sends confirmed / unavailable / clarification emails.runnerHandoff from Stay Club on_crm_syncMay hand on to the outbound cadence.
Client machines & hooksmicampus_call_completecustom: MiCampusAfter a voice conversation: LLM booking extraction (confidence floor 70), WhatsApp template, per-residence booking emails.runnerHandoff from MiCampus on_conversation_completeAlso bound to a MiCampus internal test org. Faults go to Zube-only audit rows.
Client machines & hooksmicampus_outbound_whatsapp_dry_runcustom: MiCampus dormant"Internal-only observation cadence": no provider ports, stages, CRM writes or audits.runnerHANDOFF_DELIVERY (no producer found)Registered and boot-asserted. Whether data or a script enqueues it is undetermined.
Client machines & hooksMiCampus CRM-sync post-workflow (Google Ads WhatsApp cadence)custom: MiCampus liveStarts the locale-resolved WhatsApp cadence for new Salesforce leads with no prior communication.runneron_crm_sync getPostWorkflowEligibility: Google AdWords source, unknown residence or recent lead creation. (epic's first-name requirement — stale.)
Client machines & hooksMiCampus preCrmSyncbackcustom: MiCampusSalesforce only: rewrites LeadSource (outbound WhatsApp vs Zube inbound) and moves a lone first name into last name.scheduleron_crm_syncback hook key, via crmSyncbackerSyncback hardening: 2 h quiet period (approval doc's 15 min — stale).
Client machines & hooksMiCampus cadence pre-send guardcustom: MiCampusClient guard run before the immediate send and before every cadence WAKE.runnerCadence send
Client machines & hooksTool get_propertiescustom: MiCampusPlanner-callable read tool searching bundled properties.json.worker / telephony-infraAgent tool callFeeds knowledge_query diagnostics.
Client machines & hooksTool get_booking_linkcustom: MiCampusPlanner read tool returning the official pricing/visit URL.worker / telephony-infraAgent tool call
Client machines & hooksTool send_booking_link_via_whatsappcustom: MiCampusPlanner write tool sending a WhatsApp text via client tool effects.worker / telephony-infraAgent tool call
Client machines & hooksTool send_booking_infocustom: MiCampusWrite tool sending booking-info email; not planner-callable, so voice-only.telephony-infraVoice tool call
Client machines & hooksLingua CRM-sync post-workflowcustom: LinguaHands a new CRM record to lingua_outbound_cadence.runneron_crm_sync getPostWorkflow
Client machines & hooksLingua conversation-complete post-workflowcustom: LinguaHands off to lingua_conversation_complete.runneron_conversation_complete getPostWorkflow
Client machines & hooksLingua preCrmSyncbackcustom: LinguaResolves preferred campus and area of interest and sets those CRM fields.schedulercrmSyncbackerSkips Dynamics. Exact lookup → Decision-1 → gpt.fast fallback.
Client machines & hooksLingua campus prediction (Decision-1, files named "Jev")custom: LinguaProbabilistic campus choice for non-exact text; accepted at confidence and support ≥ 0.75.schedulerLingua syncback hook; needs OPENROUTER_API_KEYTargets microsoft/microsoft-decision-1 via OpenRouter. (docs say behind a default-off org flag — no flag check found in code.)
Client machines & hooksTool get_enrollment_linkcustom: LinguaPlanner tool; the runtime owns the URL and appends it to the final reply with dedupe.worker / telephony-infraAgent tool call
Client machines & hooksStay Club CRM-sync post-workflowcustom: Stay ClubFor 5 business workflows (null, university_fair, meta_ads, meta_ads_students, meta_ads_professional) selects and starts a cadence, optionally wrapped in a viewing booking.runneron_crm_sync getPostWorkflowOrder: named-workflow rule → auto-reply suppression → guardrail cadence → LLM selector.
Client machines & hooksStay Club LLM cadence selector / scenario classifiercustom: Stay Clubgpt.fast structured outputs choosing the cadence; failures route to help_needed.runnerInside Stay Club CRM-sync post-workflowPart of client semantic routing (ZUBEA-310, doc "implemented; in review").
Client machines & hooksstayClubCrmSyncPostHookcustom: Stay ClubWrites a help-needed escalation when auto-reply is suppressed.runneron_crm_sync post hook, default workflow only
Client machines & hooksStay Club no-op conversation-complete post hookcustom: Stay ClubRegistered so the hook slot exists; does nothing.runneron_conversation_complete
Client machines & hooksStay Club calendar booking paramscustom: Stay ClubInvite email, optional attendees by event type, LLM transcript summary for bookings.runner / telephony-infraGeneric calendar tool serviceNo custom agent tools registered for Stay Club.
Client machines & hooksEmail-CRM parsers (Stay Club, Road Scholar)custom: Stay Club custom: Road ScholarParse notification/enquiry emails in the shared CRM inbox into contacts and dispatch on_crm_sync.scheduleremailCrmSyncer every 5 minStay Club parses Salesforce notifications. Road Scholar sets road_scholar_trip_interest (TODO pending client mapping).
Client machines & hooksTool get_trip_listcustom: Road ScholarPlanner read tool searching bundled trips.json by program number, keyword or trip type.telephony-infra / workerVoice tool callDeploy probe smoke-tests it on both tool paths.
Client machines & hooksCall param road_scholar_trip_interestcustom: Road ScholarExposed as a voice call parameter inside generic services.telephony-infraInbound call init
Client machines & hooksAddison Lee UC1 sales-inbound prospectingcustom: Addison LeeConsumes every inbound email to the shared sales inbox and runs lookalikes → enrichment → per-contact drafts into an Outlook "Zube Drafts" folder. Never sends.scheduler onlyon_text_message_received pre-hook (consume + continuation under the workflow lease)Mounted only by the scheduler; failure logs addison_registration_failed, does not block boot. 60-min ceiling.
Client machines & hooksAddison Lee prospecting providerscustom: Addison LeeZoomInfo (client-custom wrapper), Lusha V3 connector, Gemini grounded web search, wrapped as ports in the client folder.schedulerUC1 pipelineLusha is the only consumer of external-connectors/prospecting.
Client machines & hooksAddison Lee UC2 media-production outboundcustom: Addison Lee removal scheduledCold email + LinkedIn campaign for one salesperson: campaign-reply interceptor, DB-backed state machine, daily caps, Day 3/Day 9 schedule, Freshsales runner.schedulerclientOutboundTick every 30 s + reply pre-hookTODO(delete-addison-lee-uc2-one-off), late Nov 2026. Own 09:00–17:00 London window. (epic says tick is a disabled shell — stale.)
Client machines & hooksZoomInfo callback /callbacks/custom/addisonlee/zoominfocustom: Addison LeeReturns 204. A stub.webhooksHTTP callback
Outbound cadencesstay_club_outbound_cadencecustom: Stay ClubShell for 12 standard legacy-ported contact cadences (coliving/student follow-ups, WhatsApp openings).runnerStay Club CRM-sync selectionAlso covers long-stay student promo (id not given in research).
Outbound cadencesstay_club_university_fair_cadencecustom: Stay ClubCadence for university-fair leads.runneruniversity_fair business workflow
Outbound cadencesstay_club_meta_ads_cadencecustom: Stay ClubMeta ads cadences with parent, students and professional maps.runnermeta_ads* business workflows
Outbound cadencesstay_club_hanger_lane_north_acton_redirection_emailcustom: Stay ClubGuardrail cadence redirecting short-stay enquiries.runnerStay Club guardrail selection
Outbound cadencesstay_club_general_enquiry_{email,whatsapp}custom: Stay ClubGeneral-enquiry cadences by channel.runnerStay Club selection
Outbound cadencesmicampus_outbound_whatsapp_cadencecustom: MiCampus liveWhatsApp cadence in en, es and pt with a pre-send guard.runnerMiCampus CRM-sync post-workflowCRM-sync cadences delay the first stage by ≥ 900 s.
Outbound cadenceslingua_outbound_cadencecustom: Linguadefault_outbound_initial at 0 s, default_followup at +24 h; template language by phone country.runnerLingua CRM-sync post-workflowMultilingual templates need a deploy plus one sync step.
Outbound cadenceslingua_revival_cadencecustom: Lingua dormantRevival cadence mixing email and WhatsApp stages.runnernone foundRegistered, no in-code producer. Revival is a deferred product.
Outbound cadencesCadence safeguard matrixGA6 pure rules (stage-0 no-history, live WhatsApp conversation, resend cap, multiple conversations, expected-before-stage, attempt counters); violation → STEP_FAILED + WARNING audit.runnerBefore each stage send
Outbound cadencesAccount cadence kill switch outboundCadenceEnabledGAWhen false, cadence handoffs are refused and checkAwaitingAction skips cadence work.runner / schedulerContact-preferences settings toggleDefault true. The only operator lever over cadences.
Outbound cadencesCadence quiet hours (message window)unverifiedConfigs carry message-window hours, weekend flags and blackout dates.runnerCadence configNo enforcement found on WhatsApp/email stages; next stage is plain now + delay. Confirm with the owner.
ChannelsWhatsApp Cloud APIGAInbound and outbound WhatsApp.webhooks → worker/whatsapp webhook → inbound-eventReceipts stored in webhook_receipts (14-day expiry).
ChannelsWhatsApp Business App coexistenceGAHistory import, contact-book (app-state) sync and SMB echoes.webhooks → workerWhatsApp webhook events
ChannelsWhatsApp BSUID / username identityGATreats the WhatsApp BSUID as first-class identity for inbound and replies.workerInbound WhatsAppCadences remain phone-only.
ChannelsWhatsApp edit safetyGAEdit handling and transcript convergence for edited messages.workerInbound edits(doc says uncommitted — stale.)
ChannelsMultilingual WhatsApp templatesGATemplate language chosen per contact/phone country.runnerCadence and follow-up sendsUsed by Lingua; needs a deploy plus one sync step.
ChannelsMessenger / InstagramGAMeta connections, OAuth, media persistence, profile fetch, rate limiting.webhooks → worker/messenger, /instagram
ChannelsAd-click attribution (ENG-30)GARecords the first and last ad click (WhatsApp click-to-chat, Instagram click-to-Direct, click-to-Messenger) on targets.attribution; shown to the agentic planner.workerMeta referral fields on inbound messages, postbacks and Messenger messaging_referrals eventsNo backfill. Pages connected before ENG-30 need scripts/integrations/resubscribeMessengerPageWebhooks.ts (dry run by default, --apply to subscribe).
ChannelsEmail (Gmail / Outlook)GAMailbox polling, reply sending and inbound dispatch.scheduleremailPollingSyncer every 2 min
ChannelsHistory sync (email, Messenger, Instagram)GAImports channel history; stalled syncs are resumed hourly.schedulerhistorySyncResumer
ChannelsEmail open / click / unsubscribe trackingGATracked links and pixels via link.zube.ai/e.webhooks/o/:token.gif, /c/:token, /u/:tokenScanner opens separated by an ops review script.
ChannelsOne-click unsubscribegatedOne-click unsubscribe on tracked email.webhooksemailSettings.oneClickUnsubscribeEnabledDefault false.
ChannelsGuardrail email forwarding / bypass-forwardcode presentForwards guardrail-matched email after commit.schedulerEmail inboundGuardrail doc says slice 6 is post-June fast-follow; the jobs manifest marks bypass-forward deferred; code exists. Current status undetermined.
ChannelsHard bounces and email ignore listGABounce handling and sender ignore list inside the email service.schedulerEmail inbound/outbound
ChannelsMicrosoft email auth recoveryGARecovers Microsoft mailbox auth failures.schedulerEmail integration errorsBuilt after an Addison Lee incident.
ChannelsWeb chat (embeddable widget)GAWebsite chat on the same targets and agent machine as other text channels.webhooks → worker/webchat HTTP + WS, apps/webchat-widgetPer-org setup: session secret, escalation rules, web_chat/all template, origin allowlist. Built for two unnamed clients.
ChannelsWebchat continuation to WhatsApp / emailgatedCarries a webchat conversation to WhatsApp or email and correlates the next message.webhooks / workerPer-widget toggleDisabled by default per widget; live-provider checks remain deployment prerequisites.
ChannelsCalendar integrations + agent tools (Calendly, Microsoft)GASlot listing and booking with locks, timezone and attendees.runner / telephony-infraAgent tool calls
ChannelsMagic booking linkGAA lead self-books a meeting from a tokenised link.api / web/magic/book-meeting?token=(doc says draft — stale.)
ChannelsLink domain short links / redirectsresolve planned: create UIRedirect slugs on link.zube.ai resolve publicly with daily click metrics.api / web/$slug on link.zube.aiNo admin create UI; no setup-account flow. Magic-link type coverage undetermined.
ChannelsChannel read / send / help-needed permissionsGAPer-integration flags decide whether a channel replies or escalates.runnerIntegration configSMS and zube have no mapping and fail loud.
ChannelsSMS (Telnyx)dormantA TelnyxSmsClient exists; no inbound handler and no importer.—noneCadence SMS stages were dropped.
Channelszube channel enum valueinternal enumInternal conversation channel value with no ingress.—none
ChannelsMicrosoft SharePoint / Teamsconnect-onlyOAuth connect with nothing consuming the connection.api / webNew UI integration pagesClassic redirects to /integrations?add=.
ChannelsLead CSV / XLSX importGABatch import that dispatches CRM_RECORD_RECEIVED per row.api → worker/integrations/manual-upload → manual-import queueUses the legacy label object_type="external_api".
VoiceTelnyx inbound call controlGAAMD, consent, forwarding schedule, ambient conference, inbound call init.telephony-infra/telnyx
VoiceElevenLabs voice agents and post-callGAVoice agent runtime; post-call webhook drives CALL_ENDED.webhooks → worker/elevenlabs → inbound-event
VoiceTelnyx recording completionGATranscribes the recording and emits CALL_ENDED.telephony-infra → workervoice-post-call queueA failed enqueue is logged and the post-call is lost.
VoiceElevenLabs calendar toolsGAcalendar_list_slots, calendar_create_booking and the custom client tool route.telephony-infra/voice-tools, / (legacy client tools)
VoiceHuman transfergatedcheck_transfer_availability, transfer_to_human.telephony-infraHuman-transfer routing .enabledDefault false.
VoiceNo-consent call routinggatedRoutes calls where consent is not given.telephony-infracallSettings no-consent .enabledDefault false.
VoiceAmbient soundgatedBackground sound (office / cafe / nature) on a call.telephony-infraPhone line ambientSoundDefault null.
VoiceOutbound routes callSettings.outboundRoutesdormantWorkflow-to-line mapping for outbound voice, still stored and editable.api / web/integrations/phone-callsNo runtime reader outside settings validation and UI since AI outbound calling was removed.
VoiceTransfer outcome reclassificationGADaily metrics classify each transfer into five buckets (e.g. reachedNoPickup, callerHangup).scheduleraggregateInsightsHistorical backfill: whether applied is unverified.
VoiceManual call-audio import (Vodafone OneNet ZIP)custom: MiCampus MVPImports call recordings: STT/diarisation, LLM speaker attribution.api/integrations/manual-uploadSources disagree: the inventory lists the manual-import queue; the platform research cites callImport.ts processing synchronously in the API ("MVP shortcut for internal use only"). Whether it dispatches workflows also differs between notes — unverified.
VoiceNICE CXone recording importconnect-onlyConnect, test and update settings; no ingest job.api / web/integrations/recording-imports/nice-cxoneConnector imported only by apps/api.
VoicePublic voice demosadmin-only public pageConfigurable public demo pages (ElevenLabs or Retell) with rate limits and usage receipts.api / web/admin/demos; public /demo/$demoSlugPublished slugs immutable. (doc says "Proposed" — stale.)
VoiceDemo notes generatoradmin-onlyFrom pasted notes, drafts demo page copy and a transient voice-agent prompt; writes nothing.apiadmin.demos.generateTier gpt.ultra, no fallback.
Agent & knowledgeFoundry text templatesGA create/delete: adminAgentic templates bound to a workflow_id and channel_scope; lifecycle draft/active/inactive.api / web/foundryMultiple active matches emit an URGENT audit.
Agent & knowledgeFoundry voice templatesGAVoice agent templates; provider elevenlabs only.api / web/foundry
Agent & knowledgeTemplate test reply / Generate reply (agent preview)GARead-only reply preview through the adapter's preview surface.api → workeragent-preview queueContact-detail generation panel is admin-only.
Agent & knowledgeTemplate graph generationadmin-onlyLLM generation of a template graph definition.apitemplates.generateGraph
Agent & knowledgeTemplate guardrailsGATemplate- and node-level guardrails (e.g. redirect with escalateAfterX); "LLM matches, code counts".runnerTemplate configSlices 0–5 and 7 done; slice 6 was a fast-follow.
Agent & knowledgeWorkflow-scoped knowledgeGArestrictKnowledgeToWorkflowOnly scopes Nexus documents to named workflows.runnerTemplate setting(doc says draft — stale.)
Agent & knowledgeNexus corpus, chunking, embeddingsGASources and documents stored in GCS with chunked embeddings.api/nexus/documents
Agent & knowledgeHard delete + citation snapshotsGAImmediate corpus exclusion, then physical deletion; replies keep citation snapshots.scheduler / runnerknowledgeDeletionTick
Agent & knowledgeCurated ingest / publication (ZUBEA-263)GASource-backed proposals published atomically after human approval.api/nexus/ingest
Agent & knowledgePre-publication conflict checkGAChecks a proposal against the corpus before publishing.apiIngest flow
Agent & knowledgeNexus researcher in production (ZUBEA-261)GAEvidence-only researcher over the eligible corpus; source memo on GPT-6.1 Sol.runnerAll text channels except web chatPlanning doc says "implemented, default-off"; Nexus research reports it live. Prefer the code-cited Nexus research.
Agent & knowledgeTest / Ask NexusGAOperator test console using the same researcher.apiNexus UICorpus details behind admin overlay.
Agent & knowledgeObserved knowledge gaps (ZUBEA-268)GACaptures knowledge attempts; hourly classification and grouping into Review findings.runner / webhooks / scheduler/nexus/review; knowledgeQueryDiagnosticsRollout verification pending per doc. Covers get_properties and get_trip_list.
Agent & knowledgeNexus taxonomy (diagnostics automation)flag: nexus_taxonomyAssigns findings to per-org category catalogs; Review shows category groups instead of raw findings.schedulernexusTaxonomyWeekly + nexusTaxonomyPoller(doc says design only — stale.) Decision-client provider wiring not traced.
Agent & knowledgeNexus diagnostics recoveryS1 planned: S2–S4Fixes a capture regression; recovery of lost history is planned and blocked.runner—
Agent & knowledgeGeneric parity contract (Nexus 2.0)GAOne knowledge product for all clients; missing information means respond honestly and escalate.runnerFinalizerThe org-flag part of the contract is superseded.
Agent & knowledgeElevenLabs KB syncadmin-onlyPushes Nexus to the ElevenLabs knowledge base.api (detached microtask)knowledgeBase.syncElevenLabs, manual
Insights & intelligenceDaily / monthly insights aggregationGAPer-org daily metrics, LLM-normalised content insights, monthly rollups.scheduleraggregateInsights, aggregateMonthlyInsightsFor insights.view. Docs' "Gemini primary" is stale: Gemini tiers are rewritten to GPT.
Insights & intelligenceContent-insight curationGARenames and merges each workflow's category catalog from recent evidence.schedulercurateContentInsights
Insights & intelligenceCall Insights, lead score, summary, not-interestedGAExtracts structured lead intelligence onto the target after each conversation.runneron_conversation_completeAuthored as gpt.smart.
Insights & intelligenceRemindersGAReminder reconciliation per conversation and LLM validation when due.runner / schedulerprocessDueReminders; Home, /remindersActive-user orgs only.
Insights & intelligencewaitingOnTargetadmin-onlyMax-five list of what the lead owes, produced by Call Insights.runnerContact Insights tab (true admin)Missed its precision gate (77.3% vs 80%); not GA.
Insights & intelligenceSentiment Analysis (deferred)admin-only readCategorical per-snapshot sentiment for non-voice conversations from the previous half hour.schedulerprocessDeferredConversationAnalysesBest effort: no online fallback, retry or backfill. Model is gpt-6-luna via OpenAI-first batch (doc's Vertex Gemini — stale).
Insights & intelligenceCustom analyzersGAOrg-defined JSON-Schema analyses run per target in the deferred batch.scheduler / api/account/analyzers
Insights & intelligenceAudit trail, take-over rows, escalation rulesGAActivity log, "cannot respond" take-over rows, 3-tier escalation synthesis, 24 h notification cooldown.runner / apiHome, /reminders/audit-trail, /account/escalationsRaw audit details are admin-only.
Insights & intelligenceEscalation rule Tier 2 (Decision-1)gated: env keyOne choice question over candidate rules; used only at confidence ≥ 0.95.runnerEscalation routingActive wherever OPENROUTER_API_KEY is set; production setting not inspected.
Insights & intelligenceCRM escalation task per rulegatedOptionally writes a CRM task when an escalation rule fires.runner / schedulerEscalation-rule CRM-task directive (opt-in)Expired reservations reconciled by a cron.
Insights & intelligenceAudit acknowledgement metricsGAWhether urgent audit events get human acknowledgement.api/insights/audit-metrics
Insights & intelligenceConversion workspaceflag: insights_conversionWin rates, funnel, time-to-convert, time-in-stage, loss reasons from CRM outcomes.api / web/insights/conversionTrue admin sees it grouped as "Internal" when off.
Insights & intelligenceCRM conversion projection + stage-run measurementsGAVersioned, rebuildable read model (attribution v4) and J0 stage measurements.schedulerrebuildCrmConversionProjectionsFeeds the flagged Conversion workspace.
Insights & intelligenceLead lifecycle stage (shadow)flag: lead_lifecycle_stageClassifies the lead as prospect / customer / not a customer and stores an observation. Displays and sends nothing.runneron_conversation_completeAlso needs inference region global; enabling is refused without OPENROUTER_API_KEY.
Insights & intelligenceDrop-off observation ("SalesMotion")admin-onlyDeterministic 48–72 h drop-off detection plus gpt.fast cause/topic explanation.scheduler / api/contacts/revivalActive-user orgs only. (four-state LLM adjudication design — superseded.)
Insights & intelligenceDrop-off analytics proceduresadmin-onlyhasDropoffData, getDropoffOverviewKPIs, getDropoffByReason.apitRPCRead legacy drop-off tables.
Insights & intelligenceLegacy drop-off tableslegacythread_dropoff_events, daily_dropoff_metrics, monthly_dropoff_metrics.schedulerMonthly rollup onlyNo production writer; writers called only from tests.
Insights & intelligenceLoss-reason intelligenceadmin-onlyExplains CRM-lost leads; imported MVP plus daily generation in the aggregateInsights tick.scheduler / api/insights/loss-recordsInitial import scope: MiCampus and Lingua; Stay Club excluded.
Insights & intelligenceCategory curation and loss-reason categoriesadmin-onlyCreate, edit, delete and consolidate categories and loss reasons; suggestions.api / web/insights/categories overlay
Insights & intelligenceRevival shared categories + historical regenerationinternalOne org-scoped causal vocabulary shared by loss and drop-off; manifest-driven regeneration of historical explanations.scripthistoricalDropoffRegeneration.tsWhether the production regeneration ran is unverified.
Insights & intelligenceRevival (product)deferred admin writerevivalSettings.enabled (default false); settings writable only by admins.apiSettingsRevival jobs are deferred.
Insights & intelligenceManual lead assignmentGAAtomic ownership change with audit and target_assignment_events history.apiContacts
Insights & intelligenceAuto lead assignmentgatedOn target creation: inbound_channel_owner, round_robin, random or llm strategy.runner / api / scheduleraccessControlSettings.assignment.enabledDefault false.
Insights & intelligenceOwner → group escalation after N hourssetting onlyaccessControlSettings.escalation (primaryToGroupAfterHours, groupToAllUsersAfterHours).—SettingsThe inventory lists it as an opt-in setting; the platform research found no job referencing it (ACL slice 10 "Not started").
Insights & intelligenceClient reports frameworkGA types per clientReport definitions and runs, CSV/TSV/XLSX writers, scheduled delivery.scheduler / api/integrations/reports; processDueReportsA report type exists only for orgs with a generator. (epic says V1 ships empty — stale.)
Insights & intelligenceReport: Salesforce lead cohortcustom: MiCampusLead cohort workbook from Salesforce.schedulerprocessDueReports
Insights & intelligenceReport: Salesforce conversion performancecustom: MiCampus"Manual conversion-performance report".schedulerprocessDueReports
Insights & intelligenceReport: Meta ads efficacycustom: Stay ClubMeta ads acquisition efficacy workbook (Europe/London).schedulerprocessDueReports
Insights & intelligenceReport: media production weeklycustom: Addison LeeWeekly UC2 campaign report.schedulerprocessDueReportsTied to UC2, which is scheduled for removal.
CRMHubSpotGAPull sync and sync-back.schedulercrmSyncer, crmSyncbackerOwner sync from CRM inside on_crm_sync.
CRMSalesforceGAPull sync and sync-back.schedulercrmSyncer, crmSyncbacker
CRMMicrosoft Dynamics 365 / DataverseGAPull sync and sync-back with app-user S2S auth.schedulercrmSyncer, crmSyncbackerChannels research: release gates pending, pilot TBD.
CRMFreshsales (pull)GA read-onlyPulls Freshsales records into targets.schedulercrmSyncerPilot: Addison Lee. Deals not built.
CRMMondayGAPull sync and sync-back.schedulercrmSyncer, crmSyncbackerThe crmSyncbacker job description lists only HubSpot/Salesforce/Dynamics; the orchestrator includes Monday. The scheduler seeds buildMondayWrapper since 262bcf0a0 (before that the Monday arms threw "Monday wrapper factory is missing").
CRMShared Monday OAuth app configadmin-onlyOrg-shared Monday OAuth app credentials.apiintegrations.mondayApp.{get,save}
CRMCRM Sync V2 canonical writerGASync states, output snapshots, field verification and outcome tables.schedulerCRM sync armsTrack A + B substrate implemented; A5 continues per doc.
CRMCRM identity convergence (ADR-021)GARepairs duplicate targets that reference one CRM object.runneron_crm_sync
CRMSyncback reliability recoveryGARecovery replay for failed syncbacks (MiCampus Salesforce, Lingua HubSpot).schedulercrmSyncbackerRecovery replay is operational.
CRMLock-contention pull deferral (S0)GAA busy target defers the CRM record without audit, cursor advance or attempt burn.schedulercrmSyncer, emailCrmSyncer
CRMCRM introspection and field verificationGAField discovery, verification and owner listing for setup.api/integrations/crm/*
CRMMy CRM identity / Home CRM cardGAA user links their CRM owner identity; Home shows the CRM identity card.api / web/user-settings, /
Background jobsclientOutboundTickcustom: Addison Lee removal scheduledOne UC2 campaign tick.schedulerEvery 30 s, run on startupSkips outside the London send window. Delete late Nov 2026.
Background jobsaggregateInsightsGADaily metrics, content insights, daily loss generation; deletes expired voice-privacy rows first.scheduler0 5 12 * * * (12:05 UTC)Described as "nightly" but fires at noon UTC; reason not found.
Background jobscurateContentInsightsGACurates content-insight catalogs.schedulerAnchored fortnightly Sundays 04:00 UTC, run on startupMissing from the stale jobs manifest.
Background jobsaggregateMonthlyInsightsGAMonthly rollup from daily aggregates.scheduler0 0 13 1 * *
Background jobsbootstrapSalesMotionCrmOutcomesGABackfills canonical CRM outcome observations for sales-motion targets.schedulerEvery minute at :15 sHubSpot, Salesforce, Dynamics wrappers.
Background jobscheckAwaitingActionGAWAKE sweep for delayed replies and cadence timeouts.schedulerEvery 30 sHonours outboundCadenceEnabled.
Background jobscheckStaleConversationsGACloses or replays stale ongoing voice conversations (CALL_ENDED).scheduler5 */5 * * * *
Background jobscrmEscalationTaskReconcilerGAMarks expired opt-in CRM escalation-task reservations for operator reconciliation.scheduler40 */5 * * * *No provider calls.
Background jobscrmSyncbackerGAWrites targets back to the CRM.scheduler0 2-59/3 * * * *Freshsales disabled.
Background jobscrmSyncerGAPulls CRM records into targets.scheduler0 */3 * * * *
Background jobsemailCrmSyncercustom parsersPolls the shared CRM inbox, parses contacts, dispatches on_crm_sync.scheduler30 */5 * * * *Sender domain → org via a domain map. Parsers: Stay Club, Road Scholar.
Background jobsemailPollingSyncerGAPolls each mailbox, dispatches on_text_message_received, sends the reply.scheduler15 */2 * * * *, not singletonPer-mailbox in-process guard.
Background jobshistorySyncResumerGAResumes stalled Google, Microsoft, Messenger, Instagram history syncs.scheduler45 0 * * * *, run on startup
Background jobsjobQueueHealthMonitorops toolLogs queue-tier wait breaches and failures; settles stuck webchat turns, dead import batches, expired previews.schedulerEvery minute at :20 s
Background jobsknowledgeDeletionTickGAPhysically removes deleted Nexus objects, then their rows.schedulerEvery 15 s
Background jobsknowledgeQueryDiagnosticsGAMaterialises knowledge attempts and groups unanswered results for Review.schedulerHourlyActive-user orgs only.
Background jobsnexusTaxonomyPollerflag: nexus_taxonomyCollects completed Vertex batches; publishes validated taxonomy results.scheduler*/15 * * * *Missing from the stale jobs manifest.
Background jobsnexusTaxonomyWeeklyflag: nexus_taxonomyBootstraps missing taxonomies and submits inference per unprocessed finding.scheduler0 4 * * 0 Europe/LondonMissing from the stale jobs manifest.
Background jobsprocessDueRemindersGAValidates and disposes due reminders (LLM).scheduler20 0 * * * *
Background jobsprocessDeferredConversationAnalysesGAHalf-hour Sentiment Analysis and custom analysis via batch.scheduler5,35 * * * *, not singletonNeeds llmBatch.
Background jobsprocessDueReportsGA per-client generatorsGenerates and stores pending reports; delivers scheduled ones.schedulerEvery minute at :30 sJanitor reclaims runs stuck past 30 min.
Background jobsreconcileSalesMotionObservationsfeeds admin viewEnqueues the prior 48–72 h drop-off cohort.scheduler15 2 * * *
Background jobsprocessSalesMotionObservationsfeeds admin viewProcesses a batch of daily sales-motion snapshots with the LLM.schedulerEvery minuteActive-user orgs only.
Background jobspublicVoiceDemoUsageRetentionGAPrunes public-demo receipts older than 13 months.schedulerDaily 00:00 UTC
Background jobsrebuildCrmConversionProjectionsGARepairs missing and refreshes active CRM conversion projections.scheduler*/10 * * * *, run on startup
Background jobstelnyxCostRollupgated: POSTHOG_ENABLEDTelnyx CDR → PostHog vendor_usage_recorded per billable leg.scheduler15 */3 * * *Internal spend telemetry; org attribution via the phone-line directory.
Background jobselevenLabsCostRollupgated: POSTHOG_ENABLEDPer-call ElevenLabs cost → PostHog.scheduler25 */3 * * *"Directional, not billing-grade".
Background jobselevenLabsRateRefreshergated: POSTHOG_ENABLEDWeekly re-stamp of the hard-coded credit→USD ratio.scheduler0 4 * * 1
Background jobswebchatIdleFinalizeGAFinalises idle web chat conversations (CONVERSATION_COMPLETE_TRIGGERED).schedulerEvery minute
Background jobswebhookReceiptMonitorops toolEmails ops about unprocessed WhatsApp receipts, daily digest, prunes expired receipts.scheduler15 * * * *Needs sesConfig.
Background jobsScheduler heartbeatops toolDebug log line.schedulerSCHEDULER_HEARTBEAT_CRON, default */5 * * * *
Background jobshandoffDispatcherTickGADrains workflow_handoff_pending via runPendingHandoff.workerEvery 15 s, behind tick lock
Background jobstargetEventDispatcherTickGADrains target_workflow_event_pending to successor machines.workerEvery 15 s, behind tick lockDead-letters at max attempts.
Background jobspendingTextDispatcherTickGAResumes WhatsApp/Messenger conversations waiting behind another reply.workerEvery 15 s, behind tick lock(worker-split doc says 2 ticks — stale.)
Background jobswebhookSpoolDrainTickgated: GCP_STORAGE_BUCKETTurns spooled WhatsApp/Messenger/Instagram bodies into inbound-event jobs; quarantines bad ones.workerEvery 30 s, run on startup
Background jobsPhone-line directory LISTEN/NOTIFYops toolIn-memory DID → org map for Telnyx cost attribution.schedulerpg_notify('phone_lines_changed')File header claiming api/webhooks consumers is stale.
Background jobsCloud SQL backup monitorops toolChecks the daily automated backup from SQLAdmin metadata and alerts.Cloud Run job (out of band)Cloud Scheduler 0 11 * * * UTCDeployment opt-in.
Queuesinbound-eventGAWhatsApp, Instagram, Messenger, ElevenLabs post-call and web chat turns; two subscriptions with reserved live-tier slots.webhooks → workerpg-boss
Queuesvoice-post-callGATelnyx recording completion → transcript → CALL_ENDED.telephony-infra → workerpg-bossNo notify, so a job may wait up to about 30 s (unverified).
Queuesmanual-importGACSV import batches (and call-audio per the inventory).api → workerpg-boss, concurrency 2
Queuesagent-previewGAFoundry test replies and manual reply generation.api → workerpg-boss, concurrency 4, 300 s expiry
Queuesrevops-runbranchExecutes RevOps checkpoint runs.worker (branch)Started only by true-admin tRPCOnly on claude/revops.
Web app surfacesHome / (+ /home, /dashboard aliases)GAUrgent audit items, reminders, recent conversations, CRM identity card; in New UI also reminders and audit trail.web / apiLogged in + workspace setupClassic and New.
Web app surfaces/contacts, /target/$idGAContacts list and contact detail (conversations, activity, insights, CRM rail).web / apileads.viewSeveral detail panels are admin-only.
Web app surfaces/reminders, /reminders/audit-trailGAReminders list and audit trail with acknowledge.web / apiremindersAndAuditTrails.viewClassic only; New UI redirects to Home and hides the nav item.
Web app surfaces/insights/{overview,performance,content,time-patterns,categories,audit-metrics}GAInsights dashboards.web / apiinsights.viewCategory create/edit is admin-only.
Web app surfaces/insights/conversionflag: insights_conversionConversion workspace.web / apiFlag + insights.view
Web app surfaces/insights/loss-recordsadmin-onlyLoss records explorer.web / apiAdminOnlyGate
Web app surfaces/contacts/revival (/insights/revival redirects)admin-onlySales-motion / drop-off Revival workspace.web / apiAdminOnlyGate
Web app surfaces/nexus/{documents,ingest,review}GANexus knowledge base, ingest proposals, Review.web / apinexus.view (writes nexus.update)New UI merges Nexus and Foundry into "Agents".
Web app surfaces/foundry, /foundry/template/$templateIdGAAgent text and voice templates and setup.web / apifoundry.viewClientConfigCreate and admin fields behind overlays.
Web app surfaces/integrations homeGAProvider registry across channels, CRMs, calendars, Microsoft 365, recording imports.web / apiintegrations.manageOwn
Web app surfaces/integrations/channel/{whatsapp,gmail,outlook,meta,web-chat}GAPer-channel setup, including the webchat widget and continuation toggle.web / apiintegrations.manageOwnNew only; Classic redirects to /integrations/communication-channels.
Web app surfaces/integrations/crm/*, /integrations/calendar/*GACRM and calendar provider setup.web / apiintegrations.manageOwnShared CRM app config is admin-only.
Web app surfaces/integrations/phone-calls (+ Classic /integrations/call-management)GAPhone lines, routing, outbound routes.web / apiorganizationSettings.viewNew redirects call-management to phone-calls.
Web app surfaces/integrations/{crm,communication-channels,calendars}GAClassic aggregate settings pages.web / apiintegrations.manageOwnCommunication channels redirects to per-provider pages in New.
Web app surfaces/integrations/developersGACustom connectors and KMS-encrypted custom secrets (custom_secret).web / apiintegrations.manageOwnKept when /api/v1 was removed.
Web app surfaces/integrations/manual-uploadGACSV lead import and call-audio import.web / apileads.update
Web app surfaces/integrations/reportsGA types per clientReport definitions, runs, downloads.web / apiorganizationSettings.view (.manage to edit)
Web app surfaces/account, /account/{contact-settings,analyzers,escalations}GACompany profile and business workflows, contact defaults, custom analyzers, escalation rules.web / apiorganizationSettings.viewInference region is admin-only.
Web app surfaces/account/usersGAUsers, groups, ACL (incl. channel scope), invites.web / apiorganizationSettings.manage
Web app surfaces/user-settingsGAUI mode (Classic/New), locale (en-US / en-GB), My CRM identity.web / apiLogged in
Web app surfaces/deals/{overview,pipeline,$dealId}flag: revops_dealsRevOps deals reconstructed from email threads: overview, pipeline, per-deal graph.web / apiFlag + conversations.viewNew only; Classic renders not-found. Data comes only from the ops loader.
Web app surfacesDeals sidebar itemflag: revops_dealsNew UI nav entry.webFlag alone"No admin preview": hidden for admins when the flag is off.
Web app surfacesPublic: /auth/* (login, forgot/setup password, access-required)GAFirebase login and password flows.webPublicAuthGate
Web app surfaces/auth/signupinternal-facing"Internal Signup" explainer for company Google accounts; customers are provisioned manually.webPublic
Web app surfacesproposals.zube.ai/$sluggated: hostname pendingClient proposal viewer with code-verified session.web / apiSeparate app host; /api/proposals/*Production hostname activation and pilot rehearsal pending per plan; live state not determinable.
Web app surfaces/settings/*, /account/callslegacyURL aliases redirecting to /integrations/* or account pages.webLogged in
Web app surfaces/_dev, /_dev/{primitives,charts,forms}ops toolDev workbench and UI primitive playground.webVite dev server or localhost only
Web app surfaces/adminadmin-onlyClients: create client, impersonation targets, user activation, delete organisation, password invites.web / apiAdminOnlyGateDelete organisation is the only tenant-wide hard delete.
Web app surfaces/admin/changesadmin-onlyInternal customer change-request log with evidence uploads.web / apiAdminOnlyGate
Web app surfaces/admin/feature-flagsadmin-onlyList and toggle the 4 org feature flags.web / apiAdminOnlyGate
Web app surfaces/admin/demosadmin-onlyPublic voice demo management: create, generate, Retell credential, usage.web / apiAdminOnlyGate
Web app surfaces/admin/proposalsadmin-onlyClient proposals list and detail.web / apiAdminOnlyGateNo update/publish API; created via the create-proposal skill.
Admin & internal toolsImpersonation (persona)admin-onlyA true admin acts as a customer user; true-admin access follows the human, so /admin stays available.api / webadmin.listImpersonationTargetsAdmins can preview either UI mode while impersonating.
Admin & internal toolsOverlay: Foundry admin fieldsadmin-onlyTemplate creation and admin-only template fields.webAdminOnlyOverlay
Admin & internal toolsOverlay: contact detail internalsadmin-onlySentiment, internal target insights, outcome rail, raw audit metadata, reply-generation panel.webAdminOnlyOverlay
Admin & internal toolsOverlay: WhatsApp template actions / syncadmin-onlyTemplate actions and syncTemplates.web / apiAdminOnlyOverlay, trueAdminProcedure
Admin & internal toolsOverlay: Account inference settingsadmin-onlyLLM region global / us / european.web / apiClassic Account pageRegion also gates the lead-lifecycle classifier.
Admin & internal toolsOverlay: Nexus internalsadmin-onlyEvidence internals, toolbar admin actions, test-query corpus details.webAdminOnlyOverlay
Admin & internal toolsOverlay: audit event raw detailsadmin-onlyRaw audit event details.webTrue admin
Admin & internal toolsDemo-organisation policyinternalOrgs whose users are all inactive suppress external escalation side effects; demo_insights_reference_at gives demo Insights a virtual "now".runner / apiOrg dataDoc: "implemented; awaiting deploy review".
Admin & internal toolszube-demo-org skillops toolBuilds prospect demo orgs in production from fabricated data (rehearse locally, then prod-db-write).agent sessionSkillSeeds Nexus docs with a deliberate gap and Review findings.
Admin & internal toolscreate-proposal skillops toolAuthors and validates client proposals on the proposal engine.agent sessionSkill
Admin & internal toolsPostHog LLM cost eventsinternal$ai_generation events with modelled cost per call.all LLM callersWhen the caller supplies telemetryDirect batch paths bypass it. No hard spend cap exists.
Admin & internal tools/posthog alert intakeinternalPostHog error-tracking alert emails.webhooksHTTP
Admin & internal toolsStatus page status.zube.aiops toolUptime Kuma in a separate Compose project behind nginx.VM—Infra merged; operator steps (bucket, MFA admin, domain mapping) unverified.
Admin & internal toolsSecurity scanningops toolSemgrep + bun audit in CI; production vulnerability evidence job (VM Manager, Trivy per image digest).CIPRs, main, weeklyThe planning-doc table says host scanning is not built; the platform research cites the CI job and assessor script. Prefer the latter.
Admin & internal toolscheck:remote (AWS)ops toolRemote checks on AWS EC2 via SSM-proxied SSH.AWSbun run check:remoteGCP target in staged retirement.
Admin & internal toolsCI validation reuseops tool shadowReuses validation of identical inputs across checks.CIvalidationShadow.tsPartial: normal commands and workflows do not call it yet.
Ops scriptsprod-db-read / prod-db-writeops toolOnly general-purpose production SQL entrypoints; single-statement AST validation; read-only or rollback by default.scriptbun run prod-db-*
Ops scriptsrevops-deal-loadops toolRehearse and apply one as-of RevOps deal export into an org; insert-only.scriptbun run revops-deal-loadThe only loader for revops_deals data on main.
Ops scriptsContent-insight bootstrapops toolPrepare, rehearse and apply content-insight bootstrap with fresh-capture guards.scriptprodDbContentInsightBootstrap*.ts
Ops scriptsInsight lock proofops toolLock-behaviour proof against a disposable Postgres.scriptprodDbInsightLockProof.ts
Ops scriptsHistorical drop-off regenerationops toolGenerate, preview, rehearse, apply, verify per org and cohort date.scripthistoricalDropoffRegeneration.tsNo all-tenant default.
Ops scriptsEmail tracking signature reviewops toolSeparates scanner opens from real opens.scriptbun run email-tracking:signature-review
Ops scriptsPhase-2 deploy runbook and data stepops toolTask 0 deletions, worker split, monitoring alert definitions.scriptphase2*.ts, phase2*.md
Ops scriptsworkspace:cleanops toolStale worktree and artefact clean-up (dry run by default).scriptbun run workspace:clean
Ops scriptsoperations:checkops toolTypecheck plus vitest for operations and Nexus scripts.scriptbun run operations:check
Ops scriptsnexus:prepare-approved-backfillops toolRehearses seeding three approved taxonomy catalogs per tenant into disposable Postgres; no production writes.scriptscripts/nexus/*
Ops scriptsConfigurable demo data generatorops toolPortable demo bundle (Workspace London, Starline Tours or custom) for a chosen local database.scriptbun run demo:data:generate:configurableSeed with demo:data:seed.
Ops scriptsVisible showcase rehearsalops toolShowcase rehearsal on a disposable testcontainer; never reads env or a live database.scriptrehearseVisibleShowcase.ts
Ops scriptsreconcileSixFreshsalesDay3Tasks.tscustom: Addison Lee removal scheduledOne-off UC2 Freshsales task reconciliation.scriptManualDelete late Nov 2026.
Ops scriptsimportUc2Campaign.tscustom: Addison Lee removal scheduledUC2 campaign cohort import.scriptManualDelete late Nov 2026.
Ops scriptscollectUc2ReplyBackfill.tscustom: Addison Lee removal scheduledBackfill of UC2 campaign replies.scriptManualDelete late Nov 2026.
Ops scriptspreviewOutboundCampaignEmail.tscustom: Addison Lee removal scheduledOffline preview of one UC2 email; cannot send or draft.scriptManualDelete late Nov 2026.
Ops scriptsrunUc2SealedRehearsal.tscustom: Addison Lee removal scheduledSealed UC2 rehearsal.scriptManualDelete late Nov 2026.
Removed featuresAI outbound callingremovedon_cadence_call_start and cadence call stages (Task 0, T0.1).——Rollback must not restore it ("a legal issue"). outboundRoutes residue remains.
Removed featuresOutbound customer webhooksremovedCustomer-facing outbound webhooks (T0.2).——workflow_outbox table and emit_outbound_webhook enum remain with no consumer; the outbox dispatcher is gone.
Removed features/api/v1 external REST APIremovedNine target/conversation routes, /api/docs, OpenAPI, API-key auth and the Developers API-key card (T0.3).——Residue: api integration type, sanitizeAdditionalInformationForExport.
Removed featuresScheduler job detectDropoffEventsdroppedDropped by product decision.——Recorded in the jobs manifest.
Removed featuresScheduler job processAdvancedInsightObservationsdroppedDropped by product decision.——advanced_insight_observations table dropped.
Removed featuresScheduler job reconcileAdvancedInsightObservationsdroppedDropped by product decision.——
Removed featuresScheduler job runEmailCampaigndroppedDropped by product decision.——
Removed featuresScheduler job sendEmailRemindersdroppedDropped by product decision.——
Removed featuresJobs revivalGateSweep, revivalOutcomeLookback, calendarBookingMagicLinkSweepdeferredDeferred by product decision; not registered.——
Removed featuresFreshsales CRM sync-backdisabledSync-back to Freshsales.——TODO(freshsales-syncback) "intentionally disabled".
Removed featuresCadence SMS stagesdroppedSMS stages were not in the legacy stage union and were dropped.——
Removed featuresInsights V2 additive-action and semantic drop-off streamsretiredRoutes /insights/additive-v2, /insights/dropoffs, /insights/sentiment-v3 retired; /insights/revival now redirects.——Retired with no fallback.
Removed featuresrevival_metrics tabledroppedRevival metric storage.——(README still lists revival metric fields — stale.)
Removed featuresFour-state "Sales Motion" design and sales_motion_observation flagsupersededLLM-adjudicated lost/won/active/dropped_off states and a UI flag.——Neither the flag nor the state-adjudicating LLM exists; replaced by deterministic detection.
Removed featuresStandalone Nexus Conflicts tabsupersededSeparate conflicts UI.——Not present.
Removed featuresNexus semantic remediation groupsstoppedExperiment grouping findings by remediation.——
Removed featuresGemini 3.6 upgradesupersededPlanned tier move to Gemini 3.6 Flash.——Tiers now map to gemini-3.8-flash.
Removed featuresSchema cleanup phase 2merged; follow-up openVerified dead-schema cleanup (migration 0065).——(doc says not merged — stale.) The planned "contract" drop of nexus_enabled / activation_packet_id has not happened.
Branch-only & plannedRevOps checkpoint-run pipelinebranch dormantResumable, cost-capped XState machine: one deal at one checkpoint; publishes revops_deal_days in one fenced transaction.worker (branch)True-admin tRPC onlyclaude/revops, not merged. Dormant by construction: crmReader: null, no scheduler entry. Only "intelligence-only" orgs are eligible.
Branch-only & planned/admin/revops-runs + RevOps admin APIbranch admin-onlyCheckpoint grid, run list, spend; start/cancel/resume runs, org config.api / web (branch)trueAdminProcedure
Branch-only & plannedDeals forecast, renewals and past-blockers pagesbranch flag: revops_dealsPortfolio, forecast, renewals pages reading a fictional demo dataset.api / web (branch)/deals/forecast, /deals/renewals, /deals/past-blockersDeterministic clock-simulation forecast; renewals "schema" is a Zod schema in the demo dataset, not a table.
Branch-only & plannedRevOps demo portfolio generatorbranchSeeded generator of invented portfolios (facilities seller, football-club hospitality).script (branch)bun run revops:demo-portfolio:generateNewer datasets only on a separate step-2 branch.
Branch-only & plannedRevOps ingest librarybranchTurns Freshsales email-conversation pages into write-once stored messages.script (branch)Probe scripts onlyNo production trigger.
Branch-only & plannedRevOps loader conversations-only modebranchLoads a deal and its conversations only.script (branch)revops-deal-load
Branch-only & plannedRevOps Intelligence plan (art_f7b5664c)plannedExec "exceptions" MVP on up to 5 Addison Lee deals: Exceptions list → Blockers / Timeline / Evidence.——Draft rev 4, approval pending.
Branch-only & plannedIdentity substrate (art_73a5ddf7)plannedMulti-stakeholder email threading and a Freshsales deal mirror behind a proposed multi_stakeholder_deals flag.——Draft rev 9; branch has 0 commits; no tables exist.
Branch-only & plannedManaged runtime for custom client workflows (art_e7fce6a6)plannedA "case lane" on the XState runner core; first tenant hotel chargebacks.——Not approved, nothing built.
Branch-only & plannedCustom-client scalabilityparkedMove per-client literals into persisted config, then hooks-as-data.——761 client-name hits in 41 shared production files. Only a gate-only baseline is planned now.
Branch-only & plannedCalendar booking truthplannedDurable appointments ledger with voice correlation.——Approved; no appointments table (only slot locks).
Branch-only & plannedOutbound voice hold detectionplannedStop vendor billing while outbound calls sit on hold.——Off-repo plan only; no code.
Branch-only & plannedNative audio (OpenAI / Gemini realtime)plannedReplace the ElevenLabs agent platform with native realtime audio.——Draft MVP testing plan; no runtime code.
Branch-only & plannedAccount / OAuth provider linkingplannedLink Google/Microsoft OAuth to existing email/password identities.——Web wires only GoogleAuthProvider.
Branch-only & plannedOrg language settings / Spanish UIplannedOrg base language plus user override (en/es); localised emails.——Only en-US and en-GB exist.
Branch-only & planned21 Degrees pilotplannedCommunication and data-normalisation layer above a trades/renewables group's CRM/FSM.——"No implementation started"; planned custom_client_polls action, syncback hooks, sub-organisations.
Branch-only & planned60-day data retention purgenot foundOpt-in customer-data purge.——No job, setting or script in this checkout; the embedded-webchat epic records it as a dependency being built on a separate track.
Branch-only & plannedFreshsales dealsplannedDeal sync for Freshsales.——Not built.
Branch-only & plannedUser ACL slice 10plannedReminder acknowledgement flows, escalation job, notification preferences.——"Not started"; only the settings contract exists.
Branch-only & plannedWorkflow envelope stack-aware mirror (steps 2–4)plannedStack-aware scheduler mirror and invariant detector.——Step 1 (instant machines) is built; successor contract is still restorePrevious: boolean.
Branch-only & plannedWorkflow lock contention Q1–Q7plannedTarget-busy semantics everywhere, durable target mailbox, shorter lock ownership, CRM replay.——Unapproved; only S0 deferral is built.
Branch-only & plannedOpenAI usage control (remaining)plannedTelemetry envelope with daily reconciliation, response-quality gate, MiCampus downshift, OpenAI Batch lifecycle.——Only the tier mapping and cost telemetry shipped.

Per-client view

ClientWhat is custom for themDetail
Stay ClubCRM-sync post-workflow for 5 business workflows with an LLM cadence selector; viewing-booking successor; cadence shells (standard, university fair, Meta ads, North Acton redirection, general enquiry); email-CRM parser; calendar booking params; Meta ads efficacy report.#custom
LinguaOutbound and (dormant) revival cadences; lingua_conversation_complete email successor; syncback pre-hook with Decision-1 campus prediction; get_enrollment_link tool; en/es email templates.#custom
MiCampusGoogle Ads WhatsApp cadence (en/es/pt) with pre-send guard; dormant dry-run machine; micampus_call_complete successor; Salesforce syncback pre-hook; 4 agent tools; two Salesforce reports; Vodafone call import.#custom
Road ScholarEmail-CRM parser; get_trip_list tool; road_scholar_trip_interest call param. No hook slots.#custom
Addison LeeUC1 prospecting pre-hook (drafts only, scheduler-mounted); UC2 outbound campaign, tick, report and scripts (removal scheduled late Nov 2026); ZoomInfo callback stub; Freshsales pilot; RevOps Deals pilot.#custom
OthersNo client code: 21 Degrees (planning only), LBF Travel (voice demo slug), demo presets Workspace London and Starline Tours.#custom
Evidence
  • packages/db/src/schema/organizationFeatureFlags.ts:8-27 — flag table, enabled default false.
  • packages/webapp-contracts/src/admin/index.ts:225-272 — the 4-key catalog, all defaultEnabled: false.
  • packages/repositories/src/organizationFeatureFlags.ts:13-14,57-120 — missing row = false; toggle writes an internal Changes entry.
  • apps/api/src/trpc/trpc.ts:326-372 — organizationFeatureProcedure with true-admin bypass (:333); :403 trueAdminProcedure; :374 adminProcedure unused.
  • apps/web/src/routes/AuthGates.tsx:90-128,294-301 — OrganizationFeatureGate and AdminOnlyGate.
  • apps/web/src/components/AdminOnlyOverlay.tsx:88,102 — overlay defaults to access='true-admin'; apps/web/src/lib/authAccess.ts:12-31 — effective vs true admin.
  • packages/webapp-contracts/src/uiMode/index.ts:3-11; packages/db/src/schema/users.ts:127,161 — UI mode, default classic.
  • packages/config/src/env.ts:336; packages/services/src/scheduler/createScheduler.ts:188-209; apps/worker/src/workerProcess.ts:150-166 — SCHEDULER_ENABLED, enabledEnvVar, spool-drain condition.
  • packages/webapp-contracts/src/settings/index.ts:15,323-336,351-375,446-461,521-603 — settings toggles and admin-only sections; packages/services/src/settings/index.ts:55-60,473-476.
  • packages/services/src/scheduler/registry.ts:53-95 — scheduler crons and worker dispatcher ticks.
  • packages/workflows/src/registerDefaultMachines.ts:186-303 — 5 default machines; packages/workflows/src/clients/registerClients.ts:65-75,149-167,176-541 — expected machine IDs, Addison registration, successors, cadence registry.
  • packages/workflows/src/registerClientHooks.ts:1-49; packages/workflows/src/registry/clientRegistry.ts:246-275 — client hooks in code, keyed by org, machine and business workflow.
  • apps/scheduler/src/composition.ts:786-874 — Addison Lee UC1/UC2 mounted only by the scheduler.
  • packages/services/src/support/manifest.ts:107-151 — shipped (stale), dropped and deferred jobs.
  • planning_docs/multi-app-split/worker-split.md:27,403-425 — Task 0 removals (outbound calling, outbound webhooks, /api/v1).
  • apps/web/src/routes/router.ts:106-889; apps/web/src/routes/dealsRoutes.ts:15-63 — route table and gating.
  • apps/web/src/features/admin/messages/featureDefinitions.ts:13 — "(shadow)", the only maturity label in the UI.

Nexus: Zube's knowledge system (deep dive)

Nexus is the tenant knowledge base and everything around it: ingesting documents, answering customer factual questions from them, diagnosing the gaps those questions expose, and the operator tools (Test Nexus, Review). The key fact: the text agent's knowledge tool sends the whole workflow-scoped corpus (capped at 50 documents / about 27k tokens) to an evidence-only researcher. There is no top-k. Voice does no Zube-side retrieval at all.

Web route
/nexus
Documents · Review (+ Ingest in the old UI)
Permissions
nexus.view / nexus.update
true admin for ElevenLabs sync
Researcher
gpt.ultra
source-memo strategy; claude.smart structured-output fallback
Corpus cap
50 docs · ~27k tokens
above it: unavailable, reply suppressed

What Nexus is: 1.0 versus 2.0

  • Nexus 1.0 (legacy RAG). Vector search returned the top-k raw chunks and the general agent interpreted them. The researcher epic gives two complaints: operators could not ask the knowledge layer what it knows or see which exact source spans support an answer, and the general agent could over-interpret snippets.
  • Nexus 2.0. It replaces only the implementation of a knowledge tool once the ordinary planner has selected it. It is a complete-corpus, evidence-only researcher, and the server validates every evidence reference. The planner never sees Nexus as a separate concept (more on the planner and finalizer in the agentic chapter).
Read this first: docs and code disagree, and the code is newer.
  • Researcher model. The planning docs describe Vertex Gemini (gemini.fast, minimal reasoning, no cross-provider fallback). The code defaults to a source-memo strategy on gpt.ultra (gpt-6.1-sol, reasoning high) with a claude.smart (Bedrock Claude Sonnet 5) structured-output fallback. It returns research_completed, not the epic's four typed statuses.
  • GPT-first routing. Generations authored as gemini.* are remapped to gpt.* at initial generation, so curation and the generic Nexus generations run on gpt-6-luna first; Gemini serves as fallback or for token accounting.
  • No per-org toggle. organizations.nexus_enabled is gone from the Drizzle schema and no longer read (the physical column remains until a later contract migration). The runtime rule is channel !== 'web_chat': Nexus is on for every text channel except web chat (planning docs describe a per-org toggle — stale).
  • No Conflicts tab. The conflict scanner runs only as a pre-publication check inside curated ingest (researcher epic specifies a Conflicts tab — stale).
  • Terminal path. The researcher epic said a Nexus answer never returns to an unconstrained final LLM. The later generic-parity design and the code route it through the finalizer with host guards.
Evidence
  • apps/web/src/routes/router.ts:498-526 — /nexus route
  • packages/webapp-contracts/src/userAcl/index.ts:254-255 — nexus.view, nexus.update
  • planning_docs/nexus-researcher/epic.md:14-18,41-46; handoff.md:53-59 — problem statement
  • planning_docs/nexus-generic-parity/epic.md:8,19-29 — 2.0 replaces the tool implementation only
  • packages/llm/src/nexusResearchMemoGeneration.ts:80-86; packages/llm/src/nexusResearcher.ts:741 — source memo on gpt.ultra; commit 665ed4eeb (2026-10-06)
  • packages/llm/src/models.ts:89-97,105-114,159-166,196-209; clientGeneration.ts:145-151 — model ids and GPT-first remap
  • packages/db/drizzle/0065_daffy_strong_guy.sql:1-5 — nexus_enabled no longer selected; agenticReplyAdapter.ts:176-179 — channel rule
  • planning_docs/nexus-researcher/epic.md:177-182,386-392 — stale tab and terminal-path designs

Data model

All Postgres, with original bytes in GCS. Embeddings are pgvector vector(3072) stored full-width; the HNSW index and the <=> distance operator cast to halfvec(3072) with halfvec_cosine_ops, because vector operator classes are limited to 2,000 dimensions.

GroupTable / fieldWhat matters
Documentsknowledge_documentsOne row per immutable version. Unique on (organization_id, workflow_id, document_key, version); at most one active version per key (partial unique index); active only if ingestion_status = 'ready'. source_type upload | url (pasted text is stored as upload). workflow_id defaults to '__default__'. Keys: upload:<uuid>, text:<uuid>, url:<normalized url>. Points at a file_storage row.
Documentsstaging + deletion columnsingest_session_id, ingest_batch_id, staging_expires_at must be set together and only on inactive rows. deletion_requested_at, deletion_next_attempt_at, deletion_attempt_count, deletion_last_error, deletion_objective_alerted_at drive hard delete (migration 0030 moved every legacy archived row into this lifecycle).
Chunksknowledge_chunkscontent, token_count, chunk_index (unique per document), embedding vector(3072), HNSW halfvec index.
Revision guardknowledge_corpus_revisionsOne integer revision per organisation; the compare-and-swap guard for curated publication.
Curated ingestknowledge_ingest_sessionsmode add | update; status staging → preparing → review → applying → applied or failed/abandoned/expired; base snapshot id + base corpus revision, proposal_revision, per-org-unique idempotency_key. TTL 7 days idle, 30 days max.
Curated ingestknowledge_ingest_sourcesExtracted text per submitted source (upload | url | text), with expires_at, content_deleted_at.
Curated ingestknowledge_ingest_candidatesProposed documents per proposal revision: operation create | replace, staged document id, target document/version/content hash, rendered_content, fact_evidence ({unitId, sourceId, startOffset, endOffset, quote}), operator_edited, excluded.
Observed gapsknowledge_query_capture_eventsTransient durable inbox for ElevenLabs post-call payloads (provider = elevenlabs only); unique per provider event; lease/retry columns.
Observed gapsknowledge_query_observationsOne runtime knowledge attempt: org, target, conversation, channel, template, workflow run, primary_workflow_id, sorted effective_workflow_ids + scope key, source_key (nexus or a custom tool key), request text, bounded context, tool I/O, direct_disposition, atomic_unresolved_aspects, model/token metrics. Unique on (org, source_key, source_execution_id).
Observed gapsknowledge_gap_findingsOne UI-visible gap. type partial | missing | conflict; canonical_subject, atomic_requirement, operator_reason; canonical_fingerprint; embedding vector(3072); lifecycle open | resolved | dismissed. Unique per partition (org, primary workflow, scope key, source key, fingerprint).
Observed gapsknowledge_gap_occurrencesObservation → finding link; unique on (observation_id, atomic_aspect_index).
Taxonomyknowledge_gap_taxonomy_*Per-org diagnostics_enabled (default true); versioned catalogs, categories, descriptors; runs (initial_backfill | weekly_matching, can be blocked with corpus_too_large | matcher_unavailable); provider attempts, items, results, unmatched aspects. Migration 0080.
ProvenancenexusCitationSnapshotOptional field in the transcript's agentic_response metadata: researchTaskHash, workflowIds, corpusSnapshotId, status, generatedAt, and per evidence item documentId, version, chunkId, exactQuote, citedTitle, workflowId.
Removedknowledge_query_diagnostics, knowledge_review_runsOld diagnostic and corpus-review tables; created in 0044, dropped in 0046.
Evidence
  • packages/db/src/schema/knowledgeDocuments.ts:23-34,39-145 — enums, indexes, staging and deletion columns
  • packages/utilities/src/workflowId.ts:6; packages/services/src/knowledge/library.ts:70-72,743 — default workflow id, key formats, text stored as upload
  • packages/db/drizzle/0030_natural_mister_fear.sql:1-19 — deletion columns and archived-row migration
  • packages/db/src/schema/knowledgeChunks.ts:21-60; knowledgeEmbeddings.ts:4-18; 0000_initial.sql:219 — chunks, halfvec cast
  • packages/db/src/schema/knowledgeCuration.ts:26-158; knowledgeIngestSessions.ts:42-98; packages/repositories/src/knowledgeCuration.ts:36-37 — curated tables, TTLs
  • packages/db/src/schema/knowledgeGaps.ts:34-355 — gap tables (migration 0045_heavy_morbius.sql)
  • packages/db/src/schema/knowledgeGapTaxonomy.ts:27-645 — taxonomy tables
  • packages/db/src/schema/conversations.ts:79-126 — citation snapshot schema
  • packages/db/drizzle/0046_nifty_cardiac.sql:1,5 — dropped tables

Pipeline at a glance

INGEST · API · nexus.update Direct document path upload / URL / text / bulk / edit extract → GCS → file_storage new version → chunk → embed gemini-embedding-2, 3072-d activate vN; vN-1 deletion-requested Curated ingest (Add) session: corpus snapshot + revision LLM knowledge units + truth check LLM document proposals conflict probe against corpus staged inactive drafts → review apply: corpus-revision CAS synchronous HTTP (5-min nginx lane) Corpus (Postgres + GCS) knowledge_documents (versions) knowledge_chunks + halfvec(3072) scoped by workflow_id: __default__ and/or named workflow only active + ready rows are read knowledgeDeletionTick every 15 s hard-deletes GCS then rows objective 5 min, else urgent system_issue audit Text agent (runner) all text channels except web chat planner picks knowledge tool Nexus researcher, whole corpus gpt.ultra source memo cap: 50 docs / ~27k tokens Finalizer + host guards server-validated evidence respond / respond-and-escalate or suppress + silent escalation citation snapshot in metadata nexusEffect audits ElevenLabs sync true admin, manual, fire-and-forget wipes folder, re-uploads chunks no auto re-sync on change ElevenLabs KB folder voice agent retrieves internally (outside this repo) no Zube-side researcher Test Nexus (operator) same answerNexusQuestion effects-free, ephemeral 2 concurrent · 10 starts/min/org observation staged in tx_final ElevenLabs post_call_transcription webhook (eligible tools) knowledgeQueryDiagnostics (hourly) materialise capture events → observations direct Nexus disposition, or LLM classify (gpt.fast) fingerprint → embed top-8 → LLM match dismissed findings absorb repeats → knowledge_gap_findings / occurrences Review tab findings: partial / missing / conflict open / resolved / dismissed new UI: Repair · Test Weekly taxonomy flag: nexus_taxonomy (off) Sun 04:00 UK + 15-min poller matcher: microsoft-decision-1 → category groups in Review Repair → Add with the atomic requirement as context (new UI)
Two ingest paths write one workflow-scoped corpus. Three consumers read it. Real knowledge attempts from text and voice feed the hourly gap job, whose findings operators review and repair through ingest.

Ingestion

Accepted inputs and chunking

InputExtraction
txt / mdread as UTF-8
docxmammoth
docword-extractor
PDFpdf-parse
PNG / JPEG / WebPLLM OCR via llmClient.generateText on gpt.smart, temperature 0
URLfetched with a 15 s timeout; HTML via html-to-text; PDF handled; titles derived; URL normalised (hash dropped, query params sorted)
  • Direct uploads: 5 MB per file.
  • Chunking (chunkKnowledgeDocument) estimates about 4 characters per token. A document of ≤2,000 estimated tokens is one chunk. Larger documents split on blank-line paragraphs and pack up to 1,000 tokens per chunk; oversized paragraphs split by sentence, then word. No overlap. Legacy helpers rebuild a document from old overlapping chunks when preparing an Update.

Direct document path

Used by Documents → Add/upload/URL/text/bulk/edit/move. All procedures are aclProcedure('nexus.update'): createDocumentFromFile, createDocumentFromText, createDocumentFromUrl, bulkCreateTextEntries, updateDocumentContent, updateDocumentWorkflow, deleteDocument, deleteAllDocuments.

  1. Transport. The browser sends the file base64 in a tRPC mutation. Express accepts JSON up to 8 MB (the 5 MB raw limit grows under base64). Nginx routes knowledge mutations through a 5-minute lane. "Bulk" is pasted text split into entries[] in the browser.
  2. Extract text (table above).
  3. Upload bytes to GCS at knowledge-base/<orgId>/<yyyy>/<mm>/<uuid>-<sanitized name> (needs GCP_STORAGE_BUCKET).
  4. Insert file_storage (category knowledge-base, provider GCS).
  5. Insert the next version of knowledge_documents, inactive and ready.
  6. Chunk and embed, each chunk sequentially, on Vertex gemini-embedding-2 through the direct @google/genai SDK (location us, taskType: 'RETRIEVAL_DOCUMENT'). A code comment calls this SDK path temporary. The model list holds one locked model.
  7. Insert chunks and update chunk_count.
  8. Activate. activateVersion in one transaction marks the previous active version inactive and deletion-requested, then activates the new one. On failure before activation, the file row and GCS object are deleted.
  9. Hard delete in the background. knowledgeDeletionTick runs every 15 s, 4 batches of 50 per tick, GCS object first then DB rows. Objective 5 minutes; backoff 30 s to a 5 min cap; a missed objective writes one urgent audit_trail system_issue ("Nexus source deletion is delayed"). Retrieval drops the document immediately because requestDeletion sets isActive=false and corpus reads require it.
Evidence
  • packages/services/src/knowledge/library.ts:27-39 — MIME types, 5 MB
  • packages/services/src/knowledge/extraction.ts:11,26-27,111-161,167-224,263-326 — extractors, OCR tier, URL fetch
  • packages/services/src/knowledge/ingestion.ts:1-3,38-196,214-275 — chunking
  • apps/api/src/trpc/knowledge-base/index.ts:604-782 — direct procedures
  • apps/api/src/app.ts:237-239; apps/api/src/trpc/nginxTimeoutContract.test.ts:66-83 — 8 MB body, 5-min lane
  • apps/web/src/ui/new/knowledge/KnowledgeBulkPanel.tsx:82-110; packages/webapp-contracts/src/knowledge/index.ts:148 — bulk
  • packages/gcp/src/storage/knowledge.ts:16-31,83; library.ts:451-628 — GCS key, insert, embed, activate, rollback
  • packages/llm/src/embeddings.ts:9-14,28,152-172,221-263 — embedding model and SDK
  • packages/repositories/src/surfaces/knowledge.ts:125-126,333-360,596-655 — active-only reads, requestDeletion, activateVersion
  • packages/services/src/scheduler/jobs/knowledgeDeletionTick.ts:8-55; packages/services/src/knowledge/deletionLifecycle.ts:3-6,125-137 — deletion tick and alert

Curated ingest path

The "Ingest/Add" journey: no generated content goes live without human approval. Procedures in nexusIngestProcedures.ts: createNexusIngestSession, prepareNexusIngest, reviseNexusIngestProposal, applyNexusIngest, abandonNexusIngest, getNexusIngestSession.

  1. Create session. Snapshot the selected workflow's corpus (snapshot id + org corpus revision); persist with mode add or update.
  2. Prepare: claim and limits. Hash inputs; combined sources ≤5 MB; claim with expectedRevision 0.
  3. Prepare: store sources. Pasted text stored directly; files type- and size-checked, uploaded to GCS, extracted, recorded as file_storage + ingest source. Extracted text capped at an estimated 75k input tokens ("Split it into smaller batches").
  4. Prepare: knowledge units. The LLM proposes atomic units with exact source quotes. validateAndRenderNexusCuration checks spans, exact quotes, critical facts and duplicates (codes include missing_source_span, non_exact_source_span, ambiguous_source_span, critical_fact_mismatch, unsupported_fact, duplicate_atomic_fact). One retry feeds the errors back (NEXUS_PREPARE_VALIDATION_ATTEMPTS = 2).
  5. Stale-corpus check. If the snapshot changed since session creation: "Start a new ingest session".
  6. Prepare: documents. Update mode loads exactly one target document and rebuilds its text from chunks. The LLM proposes documents; Update mode classifies each fact as duplicate, replacement or novel (classifyKnowledgeUpdateFacts, batch 40).
  7. Conflict check before publication. Each rendered proposal becomes a probe; probes plus the current corpus go through nexusResearcher.scanConflicts. A direct_conflict against anything but the proposal's own replace target throws CONFLICT.
  8. Stage drafts as inactive documents with chunks and embeddings (createKnowledgeDocumentFromText with staging).
  9. Operator review. Edit, split/combine, exclude or retarget; reviseNexusIngestProposal bumps proposal_revision.
  10. Apply (applyApprovedBatch): check idempotency key, expiry and proposal revision; increment knowledge_corpus_revisions only if it still equals base_corpus_revision (CAS); recompute snapshot; verify staged docs are not active or deleting; activate the whole batch in one transaction.
  11. Cleanup. Raw staging and proposal content are deleted on apply, abandon or expiry; the deletion tick runs processKnowledgeIngestCleanupBatch first.
Limit / settingValue
Per file and combined sources5 MB
Extracted text~75k estimated tokens
Session TTL7 days idle, 30 days max
Prepare / propose modelauthored gemini.fast, reasoningEffort: 'minimal'; remapped to gpt.fast at runtime
Prepare attempt120 s timeout, 32k output cap
Fact classifier, conflict scan30 s attempt timeouts
Large-file fix. Commit 4c9be01a7 (2026-10-22, in HEAD): an 11.7 KB source produced about 2.7× its size in output and timed out at 45 s, so prepare got 120 s / 32k and the classifier and conflict scan 30 s. Prepare and apply are still synchronous, long-held HTTP requests; nginx carries TODO(ZUBEA-263 durable Nexus jobs).
Evidence
  • apps/api/src/trpc/knowledge-base/nexusIngestProcedures.ts:47-49,144-845 — procedures, limits, stale check, update mode, conflict check (:564-627), staging (~:720-770)
  • packages/services/src/knowledge/nexusCurationTruth.ts:458-477,805-910,955 — validation codes
  • apps/api/src/trpc/knowledge-base/nexusCurationOrchestration.ts:13,91 — one retry
  • packages/llm/src/nexusResearcher.ts:33-40,784-822 — classifier, timeouts
  • packages/repositories/src/knowledgeCuration.ts:365+,396-552 — applyApprovedBatch CAS
  • packages/services/src/knowledge/deletionLifecycle.ts:25-70; knowledgeDeletionTick.ts:20-25 — cleanup
  • packages/llm/src/prompts/knowledge/nexusCuration.ts:3-18 — curation models and limits
  • apps/api/src/trpc/nginxTimeoutContract.test.ts:85-91 — durable-jobs TODO
  • planning_docs/nexus-knowledge-curation/epic.md:7; adr.md:22-37 — built status

ElevenLabs sync (voice)

  1. syncElevenLabs is a trueAdminProcedure using env ELEVENLABS_API_KEY. It returns {status:'scheduled'} and runs on a microtask; an in-process guard returns already_in_progress for a concurrent sync of the same org and folder.
  2. Resolve the KB folder by id, or by name (creating it if absent).
  3. Delete every document in that folder.
  4. Load getFullKnowledgeBank for the scope (all_workflows, workflow = default plus that workflow, or default when unset) and upload each non-empty formatted chunk as an ElevenLabs text document, named from an "Information retrieved from <name>:" prefix or Knowledge_Source_<n>.

Not found in code: attaching the folder to a specific ElevenLabs agent, or any automatic re-sync when a document changes. The demo-org skill lists "Sync to ElevenLabs" as do-not-click.

getFullKnowledgeBank also feeds three non-researcher consumers: the WhatsApp template-send knowledge hop, Stay Club WhatsApp body overrides and email-cadence prompts with a knowledge placeholder, and the fast-reply preload.

Evidence
  • apps/api/src/trpc/knowledge-base/index.ts:811-841 — true-admin procedure
  • packages/services/src/knowledge/elevenLabsSync.ts:2-16,67-189,214-234 — scheduling, guard, wipe, upload
  • apps/web/src/features/knowledge/KnowledgeElevenLabsSyncDialog.tsx:51-69; apps/web/src/ui/new/knowledge/KnowledgeSyncPanel.tsx:33,81 — UI
  • .claude/skills/zube-demo-org/references/production-safety.md:52 — do-not-click
  • packages/services/src/knowledge/search.ts:143-216; packages/workflows/src/support/defaultMachineActorAdapters.ts:658-667; whatsappTemplateSendActor.ts:513-520; packages/services/src/runtime/cadenceProviderSendDeps.ts:195-205,330-338 — other consumers

Retrieval at reply time

Scope rule

resolveKnowledgeWorkflowScope decides which workflow_ids a template can read. Filtering is deterministic SQL workflow_id IN (...) on both the corpus read and vector search. The Foundry toggle is labelled "Restrict Nexus to this workflow" (restrict_knowledge_to_workflow_only).

Template workflowRestrict flagKnowledge it can read
Default(any)['__default__']
Namedon[named] only
Namedoff['__default__', named]

Text agent: step by step

Entry point packages/workflows/src/defaults/agenticReplyAdapter.ts.

  1. Scope and engine. Resolve the scope; useNexusKnowledge = channel !== 'web_chat'. Web chat opted out in commit 7a3aae18e (2026-09-15).
  2. Fast-reply preload. If the template has fastReply for the channel and the graph has knowledge tools, the whole scoped corpus goes into the prompt when it is ≤16,000 estimated tokens, and knowledge tools are disabled for that turn.
  3. Hidden tools. Knowledge tools are hidden when the graph sets disableKnowledgeTools, on web chat, or after preload; marked unavailable when the active corpus is empty.
  4. Planner decides. "Nexus is deliberately invisible to the planner". Persisted graph keys are unchanged: knowledge_search_rag, the typo alias knowledge_serach_rag, and the full-context tool; each key binds to the Nexus or legacy executor. Nexus descriptors drop the 12 s tool timeout (executionTimeoutMs: null).
  5. Research question. The executor wraps the planner's query (or the inbound text for full-context) with up to 12,000 characters of conversation context; the prompt says the question "is a planner-produced summary, not a scope limit". Up to 3 sequential attempts, retried only on unavailable or invalid_output; the terminal is cached per request.
  6. Canonical corpus. buildNexusCorpus does one joined read of active, ready documents, chunks and file name; sorted by documentKey, id, version; snapshot id = sha256 of canonical JSON. Ineligible above 50 documents or ~27,000 estimated tokens (enforced again in the generation layer). Empty scope returns disabled_empty_corpus. No ranking, no top-k.
  7. Researcher LLM. createLlmNexusResearcher(llm, strategy = 'source_memo'); all production callers use the default. Each document splits into heading sections mapped to exact chunk spans; one structured call on gpt.ultra (reasoning high, fallback claude.smart) returns, per customer request, selected section ids and a missingDetail. It does not write the answer. The host renders the memo from the original source text and returns research_completed with evidence spans and unresolved aspects. No deadline or attempt timeout on this path: "Caller cancellation owns elapsed time". Other Nexus generations default to a 12 s attempt timeout.
  8. Server validation checks claims and evidence against the corpus. Invalid output → invalid_output; provider failure/timeout → unavailable; corpus_ineligible → unavailable.
  9. Finalizer. The result returns through the normal tool-result channel; once Nexus has run, the planner is forced to exit the tool loop. For research_completed the finalizer uses NEXUS_MEMO_REPLY_SYSTEM and NEXUS_MEMO_REPLY_REVIEW_SYSTEM. Host guards: nexusActionGuard (a "completed" or "promised" action needs a successful tool result; channel mentions must be declared) and nexusValueTokens (no new material numbers or prices; money-like values from the supported text must be kept).
  10. Effects and provenance. A nexusEffect with an idempotency key from target, conversation, template, corpus snapshot and status. An urgent needs_assistance audit only for conflicting_evidence, invalid_output and unavailable; failures also emit a system issue. The citation snapshot goes into agentic_response metadata, and a knowledge-query observation draft is staged in the runner's tx_final domain-write buffer.
Status (enforceNexusMessagingOutcome)Customer replyEscalation
invalid_output, unavailableSuppressedSilent escalation
answeredSentNone from Nexus
partially_answered, insufficient_evidence, conflicting_evidence, disabled_empty_corpusSent (respond-and-escalate)Yes

The typed statuses answered / partially_answered / insufficient_evidence / conflicting_evidence come from alternative strategies still in code (direct_single_generation, a direct strategy with an abstention audit, decompose_then_research) with claim-level evidence. The default source-memo strategy returns research_completed.

Legacy RAG and web chat. The Nexus 1.0 executor is still bound for web_chat, but knowledge tools are disabled there. It embeds the query and runs searchSimilar (halfvec cosine, active only, workflow-filtered, default limit 10, ceiling 25). The machine's eager KB load is a stub returning []. So web chat appears to get knowledge only through the ≤16k fast-reply preload. Unverified: whether web-chat templates without fast-reply get any knowledge at all. A getAgenticTextKnowledgeSnippets helper with a 1,000-word full-text threshold exists but is called only from its own file.

Voice

No Zube-side researcher or retrieval step for voice was found (rg -i knowledge apps/telephony-infra/src matched only shutdown comments). Voice knowledge is whatever ElevenLabs retrieves from the synced folder. Workflow-scoped Nexus stays out of voice in V1. Voice does feed diagnostics through ElevenLabs post-call capture.

Evidence
  • packages/services/src/knowledge/workflowScope.ts:12-26; packages/repositories/src/surfaces/knowledge.ts:85-88,124,148-160,912 — scope rule and SQL filters
  • packages/db/src/schema/agenticMessagingTemplates.ts:144,285-286; apps/web/src/features/foundry/graph/FoundryGraphEditor.tsx:171 — restrict flag and toggle
  • agenticReplyAdapter.ts:176-179,209-247,326-329,365-530,819-822 — channel rule, preload, hidden tools, attempts, executor binding
  • packages/workflows/src/defaults/agenticReplyKnowledgePreload.ts:13-62; packages/services/src/knowledge/preloadCorpus.ts:11 — 16k preload
  • packages/llm/src/agentic/plannerNode.ts:305-306,328-334,408-412 — invisible to planner, forced exit
  • agenticReplyKnowledge.ts:39-51,356-478,564-567 — attempts, descriptors, effect, snapshot, question prompt, ineligible mapping
  • packages/repositories/src/surfaces/knowledge.ts:76-135; packages/services/src/knowledge/nexusCorpus.ts:17-19,80-246; packages/llm/src/nexusGeneration.ts:22-24,153-176 — corpus build and caps
  • packages/llm/src/nexusResearcher.ts:575-755; nexusResearchMemoGeneration.ts:16-125; prompts/nexusResearchMemo.ts:1-13 — strategies and memo
  • packages/workflow-composition/src/defaultMachines.ts:59; apps/api/src/app.ts:144; apps/worker/src/agentPreviewConsumer.ts:45 — production callers
  • packages/services/src/knowledge/nexusResearcher.ts:100-320 — server validation
  • packages/llm/src/agentic/finalizerNode.ts:15-16,340-425; finalizerNexusRuntime.ts:39-61; prompts/agentic/nexusMemoReply.ts:1-21; nexusActionGuard.ts:1-49; nexusValueTokens.ts:1-28 — finalizer and guards
  • packages/workflows/src/machines/textMessageEscalationAudit.ts:132-215 — audits
  • packages/services/src/knowledge/search.ts:7-8,70-98,240-266; surfaces/knowledge.ts:895-947; buildDefaultMachineDeps.ts:429-433 — legacy RAG
  • planning_docs/workflow-scoped-knowledge/epic.md:27,74,321-331 — voice out of V1

Sub-features

Sub-featureStatusRuns whereWho uses it
Query diagnostics / observed knowledge gaps (ZUBEA-268)GA rollout verification pending per docRunner (text capture), webhooks (voice capture), scheduler hourlyAutomatic; operators read Review
Diagnostics automation (weekly taxonomy)flag: nexus_taxonomyScheduler: weekly + 15-min pollerZube admin toggles; runs automatic
Diagnostics recoveryS1 GA · S2–S4 plannedRunner; future operator scriptEngineers
Researcher (ZUBEA-261)GAWorkflow runner, worker previewEvery text channel except web chat
Test NexusGAAPInexus.update operators
Conflict finderGA as ingest check; Conflicts tab not builtAPI (curated ingest prepare)Implicit in Add
Knowledge curation (ZUBEA-263)GAAPI, synchronousnexus.update operators
Semantic remediation groupsplanned experiment stopped, no code——
Generic parity contractGA design in code; org-flag part supersededRunnerAll text clients
Workflow-scoped knowledgeGA (doc says draft — stale)Everywhere the corpus is readFoundry template authors
ElevenLabs KB syncadmin-onlyAPI, detached microtaskZube true admin
Nexus Review in demo orgsops toolzube-demo-org skillDemo builders

Query diagnostics: observed knowledge gaps

Replaces the old opt-in query diagnostic and the corpus-mutation Review with one product: capture real knowledge attempts, then hourly classify unresolved needs, atomise them and group them into findings. No emails, no partial/insufficient audits.

  1. Text capture. Before the transcript is sanitised for the LLM, textMessageReplyActor resolves the latest user message's referenceId, timestamp and text. After the reply, buildTextKnowledgeQueryObservationDraft creates a deterministic-id observation when Nexus ended partially_answered / insufficient_evidence / conflicting_evidence (kept as authoritative directDisposition), or ended research_completed, or an eligible custom tool succeeded (no direct disposition). The draft commits atomically with the workflow transition in tx_final. If an eligible terminal cannot produce a draft, the actor reports knowledge_query_observation_draft_not_staged to error tracking.
  2. Eligible custom tools opt in with diagnosticEligibility: 'knowledge_query': MiCampus (get_properties) and Road Scholar (get_trip_list).
  3. Voice capture. A valid ElevenLabs post_call_transcription persists a capture event before the webhook acknowledges.
  4. Hourly job knowledgeQueryDiagnostics (cron 0 0 * * * *, UTC, singleton). Window starts at checkpoint minus 5 minutes (first run: 1 hour back). Capture events are claimed and materialised; the checkpoint advances only when all are done. Observations drain in batches of 20 within a 50-minute wall budget, 3 attempts each; terminal failure goes to logger.error.
  5. Per observation. Direct disposition answered → no finding; otherwise each unresolved aspect is seeded directly. No direct disposition → one LLM custom classification returning disposition and atomic aspects. Grouping per aspect: exact fingerprint in the partition → else embed and fetch up to 8 semantic candidates → one LLM match decision; dismissed candidates without a host-valid distinction absorb the occurrence ("do not re-flag"). All attachments in one transaction.

Models: gpt.fast with structuredOutputFallbacks: [], KNOWLEDGE_GAP_MODEL_ID = 'gpt-6-luna'; Vertex Gemini embeddings. (Epic specifies Gemini 3.6 — stale.) API: listNexusGapFindings, getNexusGapFindingDetail, updateNexusGapFindingLifecycle (needs nexus.update).

Doc drift. The diagnostics epic required reusing the typed Nexus status with no second classifier. Source-memo turns return research_completed with no direct disposition, so they do go through the LLM classifier.
Evidence
  • planning_docs/nexus-query-diagnostics/epic.md:7-25,48-102 — purpose, status
  • packages/workflows/src/machines/textMessageReplyActor.ts:92-98,139-154; textMessageGenerationDiagnostics.ts:44-60,154-210 — capture, tx_final staging
  • agenticReplyKnowledge.ts:178-264; agenticReplyAdapter.ts:921-939 — draft builder, reason codes
  • packages/client-tools/src/tools/clientVoiceToolDefinition.ts:18,67,106; clients/micampus/customTools.ts:244; clients/roadScholar/customTools.ts:51 — opt-ins
  • apps/webhooks/src/inbound/elevenlabs/dispatch.ts:303-369 — persist before ack
  • packages/services/src/scheduler/jobs/knowledgeQueryDiagnostics.ts:6-212; elevenLabsKnowledgeGapMaterializer.ts:587 — hourly job
  • packages/services/src/knowledge/knowledgeGapProcessor.ts:23,421-676 — processing and grouping
  • packages/services/src/knowledge/knowledgeGapGeneration.ts:14,197-276; apps/scheduler/src/composition.ts:351-354 — models
  • apps/api/src/trpc/knowledge-base/index.ts:422-580 — API

Diagnostics automation: weekly taxonomy

Shrinks the Review queue by assigning each finding to a per-organisation category catalog; Review then shows category groups, for validated results only. Code landed in e5b2b28ca (2026-09-30); the weekly matcher moved to Microsoft-Decision-1 in 17de4369d (2026-10-13). (HTML doc says "Design only" — stale.)

  1. runWeekly (nexusTaxonomyWeekly, 0 4 * * 0 Europe/London) checks the row matcher is available, then pages over orgs with the flag on and diagnostics_enabled.
  2. No catalog: initial_backfill. One structured bootstrap call over all of the org's finding text; counts tokens first and blocks with corpus_too_large above maxInputTokens: 900_000. Then one batch item per finding, to OpenAI if configured, else Vertex.
  3. Catalog exists: weekly_matching. JEV (OpenRouter microsoft/microsoft-decision-1) decides per unprocessed finding, thresholds 0.9 for an existing category and 0.95 for new. A high-confidence "create new" triggers an LLM category-definition step published through a catalog CAS (per design). Without OPENROUTER_API_KEY the matcher is an "unavailable" stub.
  4. nexusTaxonomyPoller (every 15 min) collects finished batches and publishes only validated rows.
  5. Review shows groups via listNexusProcessedTaxonomyGroups / getNexusProcessedTaxonomyGroupDetail.

Approved catalogs (MiCampus, Stay Club, Lingua) are seeded by bun run nexus:prepare-approved-backfill: reads production via prod-db-read, rehearses in disposable Postgres, writes private per-tenant SQL; applying needs separate authorisation through prod-db-write -- --sql-file. The 535 legacy row-wise results are kept as evidence only. Open gates in the doc: independent review of the JEV and new-category path, schema and processed-only UI validated before production visibility, catalog import verified. Unverified: whether production has the flag enabled for any org.

Evidence
  • planning_docs/nexus-diagnostics-automation/index.html:51-103,164-175 — purpose, design, gates
  • packages/webapp-contracts/src/admin/index.ts:224-258; packages/repositories/src/knowledgeGapTaxonomyRuns.ts:55; NexusDiagnosticsWorkspace.tsx:252-258; useKnowledgeReview.ts:26 — flag
  • packages/services/src/scheduler/jobs/nexusTaxonomyWeekly.ts:3-29; nexusTaxonomyPoller.ts:3-22 — jobs
  • packages/services/src/knowledge/nexusTaxonomyAutomation.ts:127-175; nexusTaxonomyBootstrap.ts:206-280 — run logic
  • apps/scheduler/src/composition.ts:264-268,300-350; packages/llm/src/nexusTaxonomy.ts:18-25 — providers, JEV thresholds
  • apps/api/src/trpc/knowledge-base/index.ts:456-527; NexusProcessedTaxonomyPanel.tsx — group API and UI
  • package.json:30; scripts/nexus/README.md:1-58 — backfill script

Diagnostics recovery

Commit 4ce18ac2d (2026-08-19) sanitised the LLM transcript and dropped referenceId, which the observation builder needed, so every eligible Nexus turn from 2026-08-20 lost its observation. The doc's evidence: 147 custom-source findings versus 0 Nexus findings; 48 potentially reconstructable turns (22 Lingua, 26 Stay Club).

  • S1 forward fix: built. resolveLatestTextKnowledgeQueryDiagnosticOrigin reads the unsanitised mergedTranscript and passes the origin beside the prompt; failures surface as reason codes. Commit 1c1a33e31 (2026-09-08).
  • S2–S4 backfill: planned. Read-only manifest → local rehearsal → sealed production apply. S4 is blocked on an owner decision about backfill appetite. No recovery script exists in scripts/. Policy: reconstruct only the 48 committed-run cases with exact tx_final proof, never re-research against today's corpus, leave the 71 historical failed rows unless trustworthy evidence exists.

Researcher, Test Nexus and conflict finder

  • Researcher. R1–R6 implemented and reviewed; R7 cutover replays passed for MiCampus, Stay Club and Lingua. Port answerQuestion / scanConflicts / optional classifyKnowledgeUpdateFacts in packages/ports, adapter in packages/llm, constructed once per composition root. The rollout steps in the doc assume the org toggle, since removed.
  • Test Nexus ("Ask Nexus" in docs): listNexusDiagnosticTemplates, getNexusDiagnosticScope, testNexusQuery. Scope resolved server-side from the template with the same resolveKnowledgeWorkflowScope; template must be active, text, with knowledge tools on. Calls the same answerNexusQuestion as production. Rate limits 2 concurrent / 10 starts per minute per org. Telemetry is metadata only; tRPC input hashing is suppressed for private Nexus paths. Runs are deliberately ephemeral.
  • Foundry test chat and conversation "Generate reply" use the worker preview path with the researcher and show a Nexus diagnostic (status, research question, reason, unresolved aspects), tagged "Nexus 2.0".
  • Conflict finder. scanConflicts (30 s attempt timeout) validated by validateNexusConflictGeneration. R5 labelled evaluation: 100% direct precision and recall (50/50), 0/60 benign mislabels, 0/100 prompt injections. No scanNexusConflicts procedure and no Conflicts tab exist; the only caller is the pre-publication ingest check. The query-diagnostics epic removed proactive whole-corpus scanning, so the tab is superseded.
Evidence
  • planning_docs/nexus-diagnostics-recovery/index.html; textMessageReplyActor.ts:92-154 — recovery
  • planning_docs/nexus-researcher/handoff.md:5-8,106-140; r7-client-cutover.md:3-18,300-355,437-450 — researcher status
  • packages/ports/src/nexusResearcher.ts:448-458; packages/llm/src/nexusResearcher.ts:739-823 — port and adapter
  • apps/api/src/trpc/knowledge-base/index.ts:226-420; nexusQueryRateLimiter.ts:86-97; apps/api/src/app.ts:292-296 — Test Nexus
  • apps/worker/src/agentPreview/templateTestReply.ts:113-118; apps/web/src/ui/new/agents/foundry/TextTestDiagnostic.tsx:13-21 — preview diagnostic
  • nexusConflictScanner.ts; planning_docs/nexus-researcher/conflict-evaluation.md:3-20; nexus-query-diagnostics/epic.md:421-423 — conflict finder
  • planning_docs/nexus-researcher/adr-citation-snapshots-and-hard-deletion.md — R3 ADR

Knowledge curation

The curated ingest path above. Proposals are source-backed and server-validated, then published atomically and idempotently. The automatic corpus-review half of the epic is superseded by ZUBEA-268 and its tables are dropped. Operators use /nexus/ingest (old UI) or Add (new UI).

Semantic remediation groups

Intended to group variants of an unmet need when one operator fix resolves all of them (observed atom → semantic variant → remediation group). Stopped: the fixed 21-case local calibration produced zero independently agreed multi-finding memberships. Corpus at the time: MiCampus 383 findings / 603 occurrences, Stay Club 56/67, Lingua 66/82, all open. The proposed scripts/nexusReviewGroupingReplay.ts does not exist. Open decisions in the doc: evidence retention (30 days recommended), presentation versus remediation grouping, weekly budget (≤200 observations / ≤500 generations), utility thresholds. The taxonomy is the shipped alternative.

Generic parity

The Nexus 2.0 rollout contract: one knowledge product for all clients, no runtime fallback, missing information means respond honestly and escalate, plus a loss rubric (grading-rubric.md). The code reflects it: Nexus invisible to the planner, executors bound by key, result through the tool-result channel to the finalizer, respond-and-escalate enforced. The "request-start org flag" part is superseded; there is no flag. (Doc says "in progress" — stale.)

Workflow-scoped knowledge

V1 is implemented: knowledge_documents.workflow_id, the template restrict flag, the Foundry toggle and the scope rule table above. The doc's "1,000-word full-text vs vector" loading rule is not in production paths. Voice is out of scope in V1, and ElevenLabs sync has its own explicit scope. (Doc says "draft … Do not implement" — stale.)

Nexus Review in demo orgs

The zube-demo-org skill seeds about 10 Nexus docs with one deliberate gap and Review findings with real evidence. Rules: the chain is observations → findings → occurrences; quotes must equal real user messages; observations must be complete; resolvers must be org users; a completed_at must exist for "Last successful analysis". Chunks may have NULL embeddings (Test Nexus and text test chat use the full corpus; web-chat vector search and ElevenLabs need embeddings). Each scope must stay ≤27k tokens. Demo story: Review gaps → add knowledge → test → resolve, matching the new UI's Repair and Test actions.

Evidence
  • planning_docs/nexus-knowledge-curation/epic.md:9-39,73-87; adr.md:22-37 — curation
  • planning_docs/nexus-semantic-remediation-groups/index.html — stopped experiment
  • planning_docs/nexus-generic-parity/epic.md:7,19-48,59-66; grading-rubric.md — parity contract
  • planning_docs/workflow-scoped-knowledge/epic.md:8,13,31,349 — draft label, 1,000-word rule
  • .claude/skills/zube-demo-org/SKILL.md:29,48-49; references/pipeline.md:22-23,66-71; references/requirements.md:12-13 — demo rules
  • apps/web/src/ui/new/knowledge/KnowledgeWorkspace.tsx:96-111; KnowledgeReview.tsx:365-391 — Repair and Test

Operator UI, permissions, jobs and scripts

NexusPage picks one of two implementations by UI mode.

AreaOld UI (NexusDiagnosticsWorkspace)New UI 2.0 (NewKnowledgeWorkspace)
TabsDocuments, Ingest, Review (/nexus/documents|ingest|review)Documents, Review; buttons Test and Add
DocumentsKnowledgeBankTransportPage: list, detail, upload, URL, text, bulk, edit, move workflow, delete, delete-all, ElevenLabs syncDocuments tab (sync panel KnowledgeSyncPanel)
Curated ingestNexusIngestPanelAdd opens KnowledgeIngest
ReviewNexusReviewPanel, or NexusProcessedTaxonomyPanel when nexus_taxonomy is onFindings with Repair (Add with the requirement) and Test (pre-filled); Resolve / Dismiss / Reopen
Test NexusCard under Review with template picker (NexusQueryPanel)Test button (KnowledgeTest)
Without nexus.update—Read-only

Elsewhere: the Foundry "Restrict Nexus to this workflow" toggle, the Nexus diagnostic in test chat, and a knowledge-sources pill in conversation generation panels.

PermissionAllows
nexus.viewAll reads: documents, findings, scope; knowledge-base file downloads
nexus.updateEvery mutation, including paid Test Nexus and ingest
True adminElevenLabs sync
Feature flag nexus_taxonomySet by an admin on /admin/feature-flags
Scheduler jobCronPurposeStatus
knowledgeDeletionTick*/15 * * * * * (15 s)Hard-delete GCS and rows; clean ingest stagingGA
knowledgeQueryDiagnostics0 0 * * * * (hourly)Observed-gap capture and groupingGA
nexusTaxonomyWeekly0 4 * * 0 Europe/LondonCatalog bootstrap / weekly matchingflag: nexus_taxonomy
nexusTaxonomyPoller*/15 * * * *Collect batch results, publish validated rowsflag: nexus_taxonomy
Script / assetPurposeStatus
scripts/nexus/prepareApprovedBackfill.ts, approvedBackfill.ts, README.mdTaxonomy catalog seed rehearsal (bun run nexus:prepare-approved-backfill)ops tool
planning_docs/nexus-researcher/client-knowledge-sources.mdMiCampus cutover: nine sources to ingest into __default__ (doc, not a script)ops tool
client-base-prompt-patch.mdBase-prompt routing rules that "must not be ingested as a factual source"ops tool
Evidence
  • apps/web/src/pages/NexusPage.tsx:1-11 — UI-mode switch
  • apps/web/src/features/knowledge/NexusDiagnosticsWorkspace.tsx:261-349; router.ts:507-526; useNexusSearchState.ts:17 — old UI
  • apps/web/src/ui/new/knowledge/KnowledgeWorkspace.tsx:16-154; useKnowledgeReview.ts:99-120 — new UI
  • apps/web/src/ui/new/contacts/conversations/GenerationPanel.tsx:98 — sources pill
  • apps/api/src/trpc/files/index.ts:34-35; apps/web/src/features/account/messages/permissionMatrix.ts:61-66; packages/webapp-contracts/src/userAcl/index.ts:254-255 — permissions
  • packages/services/src/scheduler/registry.ts:20-23,69-72 — job registration

Known limitations and open problems

#ProblemDetail
1Corpus size capOnly complete corpora of ≤50 docs / ~27k tokens. Above that production maps to unavailable: reply suppressed, silent escalation. The epic is explicit: no partial subset, no legacy fallback. Raising toward 30k needs live evidence; 70–80k-token corpora blew the 12 s deadline in experiments.
2Synchronous ingestPrepare and apply are long-held HTTP requests behind nginx lanes; durable-jobs TODO open. Limits 5 MB per file and combined, 75k estimated tokens extracted.
3Shadow-pilot privacy decisionEvaluation-store versus synchronous-review choice marked "BLOCKS PILOT APPROVAL". The 500-invocation pilot and 200-case launch set appear as prerequisites; no evidence they were completed (unverified).
4Test Nexus historyRuns are ephemeral by design; persisted history is a two-way follow-up.
5VoiceWorkflow scope does not reach the voice runtime. Sync is manual, wipes and re-uploads, single-process guard. The doc warns sync scope can leak named-workflow knowledge.
6Recovery backfillUnbuilt and blocked on a decision. The 71 historical failed observations lost their payloads during failure cleanup.
7Semantic grouping qualityRemediation-groups experiment failed to produce reproducible boundaries. The diagnostics epic accepts that "semantic identity cannot be mathematically guaranteed" and biases toward suppression near dismissed findings.
8Taxonomy gatesIndependent review of the JEV and LLM new-category path "BLOCKS MERGE" per the doc, but the code is merged; confirm with the owner. A too-large first-run corpus fails visibly; no sharding.
9Query preservationOne MiCampus multi-part conversation dropped an aspect from the internal Nexus question; recorded as a diagnostic, not a regression.
10Embedding pathDirect @google/genai SDK marked temporary; ingest embeds chunks sequentially, one call each.
11Web chatOpted out of Nexus; knowledge depends on the ≤16k fast-reply preload.
Evidence
  • nexusCorpus.ts:17-19; agenticReplyKnowledge.ts:564-567; finalizerNode.ts:363-373; planning_docs/nexus-researcher/epic.md:66-68,117-127,244-246 — cap
  • nginxTimeoutContract.test.ts:85-91; nexusIngestProcedures.ts:47-48 — synchronous ingest
  • planning_docs/nexus-researcher/epic.md:166-171; transcript-evaluation.md:107-126; r6-evaluation.md:102-117 — pilot, Test history
  • elevenLabsSync.ts:9-16,220-226; workflow-scoped-knowledge/epic.md:124,321-331 — voice
  • planning_docs/nexus-diagnostics-recovery/index.html — backfill
  • nexus-query-diagnostics/epic.md:333-337 — grouping limits
  • nexus-diagnostics-automation/index.html:168,171 — taxonomy gates
  • r7-client-cutover.md:341-347 — dropped aspect
  • embeddings.ts:152-153; library.ts:465-475 — embedding path
  • agenticReplyAdapter.ts:176-179; preloadCorpus.ts:11 — web chat

Insights and intelligence features — a deep dive

The analytics and LLM-judgement features that sit behind the visible reply path: daily aggregates, per-conversation Call Insights, deferred sentiment, guardrail escalation, decision models, drop-off and loss explanation, reports, routing and RevOps. The one takeaway: deterministic code owns membership, counting, thresholds and audit; the LLM only classifies, explains or picks among candidates the code has already made eligible.

Scope of "built". Everything below describes code in this checkout. Built does not mean deployed or switched on for any customer: deployment state, production data and production env vars were not inspected. The LLM layer itself (tiers, client, agentic graph) is in Agentic replies & LLMs; the aggregation tables' place in the schema is in Data model; Nexus taxonomy is in Nexus.

Cross-cutting facts first

Where intelligence runs

ProcessWhat intelligence runs there
apps/scheduler (Croner)Every cron in scheduledJobsRegistry: insights rollups, curation, deferred analyses, drop-off reconcile/process, loss generation, reports, reminders, CRM sync and projections. Single-instance by design.
apps/workerOnly the dispatcher ticks (handoff, target-event, pending-text, plus the webhook spool drain when configured), behind a tick lock. No intelligence crons.
Workflow runner (in the worker, XState)Per-conversation intelligence: Call Insights, lead score, summary, not-interested, reminder reconciliation, guardrails, audit and escalation routing.
apps/api (tRPC)Read surfaces and settings mutations only.

How LLM tiers resolve today

Code names an authored tier (gemini.fast, gpt.smart, …); the resolver picks the model. Three consequences matter for every feature in this chapter:

  • Gemini tiers start on GPT. On initial generation gemini.fast→gpt.fast, gemini.smart→gpt.smart, gemini.nano→gpt.nano. generateObject applies this unless the input has a video attachment. gpt.smart/gpt.fast/gpt.nano map to gpt-6-luna; gpt.ultra to gpt-6.1-sol; both Gemini constants to gemini-3.8-flash; Claude tiers to us.anthropic.claude-sonnet-5.
  • Structured-output fallback is cross-provider by default, e.g. gpt.fast → gemini.fast → claude.fast. A call opts out with crossProviderFallback: false or structuredOutputFallbacks: [] — several jobs below do.
  • Scheduler batch work is OpenAI-first. OpenAIFirstBatchClient uses OpenAI batch as primary when OPENAI_API_KEY is set, with Vertex batch as fallback, using the model IDs of gpt.fast and gemini.fast.
Stale docs. Insights V2, hourly-flex and loss docs describe "Gemini 3.6/3.7/3.8 on Vertex" as the primary route. In code an authored gemini.* online call starts on GPT-6 Luna, and scheduler batches start on OpenAI when a key is configured (planning docs say Gemini primary — stale).
Evidence
  • packages/services/src/scheduler/registry.ts:53-95, createScheduler.ts:63, apps/worker/src/workerProcess.ts:151-165 — where jobs run
  • packages/workflows/src/machines/onConversationComplete.machine.ts:1-33, packages/workflows/src/runner/workflowRunnerAudit.ts:172-219 — runner-side intelligence
  • guidance/engineering-constraints.md:103 — single-instance scheduler
  • packages/llm/src/models.ts:89-97, :104-191, :196-210 — model IDs and Gemini→GPT rewrite
  • packages/llm/src/clientGeneration.ts:145-151 — rewrite skipped for video
  • packages/llm/src/structuredOutputFallbacks.ts:4-17, clientGenerationRoutes.ts:97-127 — fallback chains
  • apps/scheduler/src/composition.ts:240-277 — OpenAI-first batch client
  • planning_docs/insights-v2/README.md:21-24, planning_docs/hourly-flex-insights/epic.md:27 — stale Gemini claims

Access vocabulary

aclProcedure
aclProcedure('<perm>')
Normal per-user permission check, e.g. insights.view.
trueAdminProcedure
Zube internal admins only
@getzube.com, including while impersonating a customer user.
organizationFeatureProcedure
permission + org flag
True admins pass unconditionally; everyone else needs the permission (or owner/admin) and the flag on in organization_feature_flags.

Org feature flags in code: insights_conversion, nexus_taxonomy, lead_lifecycle_stage, revops_deals. All four are defaultEnabled: false. There is no other flag key (relevant to the drop-off drift below).

Evidence
  • apps/api/src/trpc/insights/index.ts:349 — aclProcedure('insights.view')
  • guidance/engineering-constraints.md:111 — true-admin definition
  • apps/api/src/trpc/trpc.ts:326-372, packages/db/src/schema/organizationFeatureFlags.ts:8-27 — feature procedure and table
  • packages/webapp-contracts/src/admin/index.ts:225-271 — the four flags, all default-off

Feature summary

FeatureStatusTrigger / scheduleModel / tierTablesUI surface
Daily metrics + content insightsGAaggregateInsights daily 12:05 UTCgemini.fast authored (starts gpt.fast); batch OpenAI-firstdaily_metrics, daily_content_insights, content_insight_facts/insights/* (insights.view)
Monthly rollupsGAaggregateMonthlyInsights 13:00 UTC, day 1none (SQL)monthly content insights, monthly drop-off metricsranges > 60 days
Content-insight curationGAanchored fortnightly + startupgpt.ultra high, no fallbackcontent_insight_configurations, content_insight_curation_statesnone (catalog maintenance); category CRUD admin-only
Call Insights + lead scoreGAon_conversation_completegpt.smart (GPT-6 Luna, high effort)targets insight columnstarget Insights tab
waitingOnTargetadmin-onlyinside Call Insightsgpt.smarttargetstarget Insights tab
Conversion workspace + CRM projectionflag: insights_conversionprojection rebuild every 10 min + startup— (not stated in research)crm_conversion_*, crm_stage_* measurementsConversion workspace
Deferred Sentiment Analysisadmin-only5,35 * * * * UTCgpt-6-luna batch, else gemini-3.8-flashsentiment_analysis_observationstarget Insights tab (admin)
Custom analyzersGAsame half-hour jobsame as above; online helper gpt.fastorganizations.custom_analyzers → content insights custom/account/analyzers
Guardrail countingGAeach inbound text turnplanner matches; code countstranscript item metadata on conversationsagentic template config
Escalation routing (Tier 1/2/3)GAbefore an urgent audit row persistsTier 2: Microsoft Decision-1audit_trail/account/escalations, /reminders/audit-trail
Guardrail email forwardingGA (unverified rollout)post-commit, inbound email / awaiting-actionnone—guardrail emailForwarding opt-in
Lead lifecycle stage (shadow)flag: lead_lifecycle_stageparallel to Call InsightsDecision-1lifecycle observationnone ("Nothing is displayed")
RemindersGAprocessDueReminders hourly :00:20gpt.fastaudit_trail/reminders/audit-trail
Acknowledgement metricsGAread-timenoneaudit_trail/insights/audit-metrics
Drop-off observation (current)admin-only02:15 UTC reconcile + per-minute processorgpt.fast, high, no fallbackdropoff_observations/contacts/revival
Legacy drop-off tableslegacymonthly rollup onlynonethread_dropoff_events, daily_/monthly_dropoff_metricstrue-admin read procedures
Daily loss-reason generationflag: insights_conversion admin-only reviewbranch of the 12:05 UTC tickgemini-3.8-flash via OpenAI or Vertex loss batchloss_insight_*Conversion loss reasons; /insights/loss-records
Historical drop-off regenerationops toolCLI, per org + cohort datesame explanation callhistorical_regeneration_*none
Client report generationcustom: MiCampus custom: Stay Club custom: Addison LeeprocessDueReports every minute :30none (deterministic)report_definitions, report_runs/integrations/reports
Client semantic routingcustom: Lingua custom: MiCampus custom: Stay Clubclient hooksgpt.fast (Lingua also Decision-1)—none
Lead auto-assignmentGAnew unassigned target creationllm strategy: gpt.fasttarget_assignment_eventsorg accessControlSettings (route not in research)
Voice transfer outcome bucketsGAinside daily metricsnonedaily_metricsInsights Performance
RevOps dealsflag: revops_dealsops load scriptpipeline not in tracked reporevops_*/deals

1. Insights aggregation pipeline

Turns per-target, per-conversation data into privacy-conscious aggregates for the Insights workspace: overview KPIs, channel performance, content categories, time patterns and lead-score distributions. Reads are aclProcedure('insights.view').

Trigger

  • aggregateInsights runs daily at 12:05 UTC (described in code as "nightly"), singleton.
  • Two branches via Promise.allSettled: the "legacy" metrics + content rollup, and daily loss generation (§9). A loss failure is logged and does not fail the legacy branch.
  • It first deletes expired voice-privacy rows once, then iterates active orgs in each org's IANA timezone (UTC fallback).

Daily metrics (daily_metrics)

  • Re-computes an 8-day trailing window (today−7 to yesterday) in profile-local days, so a missed run self-heals. Inputs: rolling conversations, voice-consent events, targets. Writes via metrics.upsertDailyMetricsBatch.
  • Grain: org × date × channel × workflow. Holds channelMetrics JSONB, avgLeadScore, leadScoreDistribution, hourlyBreakdown, dayOfWeek and six HLL columns. Voice metrics include transfer and consent distributions; messaging includes Zube/human/received counts.
  • HLL: raw target IDs go to the repository, which builds sketches in SQL with hll_add_agg(hll_hash_text(id)) over an unnested array. The hll column is a custom Drizzle type over the Postgres hll extension; hll_* functions are on the raw-SQL allowlist.
Two different identities. daily_metrics sketches hash the raw target ID. HMAC pseudonymisation applies only to content-insight facts.

Daily content insights and pseudonymised facts

  1. Source: targets whose content-insight snapshot was analysed inside yesterday's profile-local window. Snapshots come from Call Insights fields on targets (§3) and custom-analyzer output (§4).
  2. Types: built-in concerns, competitors, unanswered_questions, interests, decision_factors, caller_profiles; custom types come from each analyzer's aggregationSpec. The enum also holds dropoff_reason, outcome, sentiment_dissatisfaction, loss_reason.
  3. Category normalisation: each raw term maps to an existing category code or a proposed new one (code, displayName, keywords). Single-call path: generateObject, authored gemini.fast (starts on gpt.fast), shared insightsCategorizeSystemPrompt. Batch path when a group has more than one unresolved term and the batch client is wired: batchGenerateKeyedObjects, sheet id insights::<type>. Failed batch rows get up to ten single-call recoveries.
  4. Fail, don't invent: any decision still missing throws BatchCategoryNormalizationIncompleteError; the job fails rather than making a category from the raw term.
  5. Pseudonymise: targetPseudoId = HMAC-SHA256(secret, targetId), secret aggregatedInsightsHmac from AGGREGATED_INSIGHTS_SECRET_HMAC. A missing secret throws inside the org loop and the outer handler aborts the remaining legacy tenants for that run.
  6. Write (appendDailyContentInsightContributions, one transaction per scope): resolve aliases to canonical codes; insert only new (canonical category, pseudoId) memberships into content_insight_facts — "first observed target/day/canonical-category membership owns its counted snapshot"; upsert the daily_content_insights bucket with unique_targets_hll = hll_union_agg(existing, hll_add_agg(hll_hash_text(target_pseudo_id))).

content_insight_facts is unique per (org, type, workflow, category, pseudoId, date, customLabel). daily_content_insights holds occurrence count, unique target count, HLL, raw-term samples and score-bucket columns.

Monthly rollups and the query side

  • aggregateMonthlyInsights: 13:00 UTC on day 1, previous profile-local month. Per org: all-workflows and per-workflow monthly content insights from daily rows (SUM + hll_union_agg), and monthly drop-off metrics from daily rows. Failures isolated per org.
  • Ranges longer than 60 days read monthly tables; any multi-day range uses HLL cardinality for unique counts.
  • Read services: packages/services/src/insights/ (overview, performance, content, timePatterns, replyTiming). Web routes: /insights/overview|performance|content|time-patterns|categories|audit-metrics.
  • Category listing is insights.view; createCategory/updateCategory/deleteCategory are true-admin.

Content-insight curation

Keeps each workflow's category catalog clean by renaming and merging categories against recent evidence.

  • Job: curateContentInsights, anchored fortnightly interval (anchor 2026-01-04T04:00Z) plus startup; singleton, interruptible.
  • Cadence: due on first initialisation or a config-version change; every fortnight for the first two months after org creation, then every second fortnight.
  • Company brief first. If setup is pending and the brief source is not the operator, a brief is generated with gpt.ultra (high, no fallback). Still missing → non-urgent setup_pending audit row. Internal error → logger.error plus urgent setup_failed audit row.
  • Algorithm: load state + catalog snapshot → skip if not due, empty, > 500 canonical categories or > 2,000 alias codes → skip if the 90-day evidence-window hash equals the last-reviewed hash → claim with a 25-minute lease → call provider → apply with optimistic staleness detection.
  • Provider: gpt.ultra, high reasoning, crossProviderFallback: false, at most 2 generations, 600 s timeout, prompt content-insight-curation v2. Allowed actions are only retain | rename | merge, each with rationale, evidence IDs and uncertainty.
  • A tracked production bootstrap tool exists: scripts/operations/prodDbContentInsightBootstrap*.ts (contents not read).

Known limits: existing daily-metric uniqueness grains are frozen — new dimensions need a separate versioned grain; the post-contract GDPR-safe aggregate release policy is still "hold".

Evidence
  • packages/services/src/scheduler/jobs/aggregateInsights.ts:54-56, :907-921 — schedule; :879-905 — two branches; :756-767, :779-785 — privacy cleanup, timezone
  • aggregateInsights.ts:276-279, :303-345, :426 — 8-day window, inputs, write
  • packages/db/src/schema/dailyMetrics.ts:35-140, :169-200 — row shape
  • packages/repositories/src/surfaces/metrics.ts:56-69, :87-112; packages/db/src/schema/hll.ts:3-23; guidance/engineering-constraints.md:82 — HLL
  • aggregateInsights.ts:58-65, :87-116, :126-129, :474-483, :640-689; contentInsightFacts.ts:16-28 — types and source
  • aggregateInsightsCategoryNormalization.ts:53-68, :106-136, :142-182, :193-204 — normalisation
  • aggregatedInsightsSecret.ts:1-12; aggregateInsights.ts:443-447, :724-728, :773-777, :840-850 — HMAC
  • packages/repositories/src/contentInsightContributions.ts:123-163, :183-295 — write path
  • contentInsightFacts.ts:30-59, dailyContentInsights.ts:21-61 — tables
  • aggregateMonthlyInsights.ts:53-57, :94-135, :151-162; packages/repositories/src/surfaces/insights.ts:520-545, :602-625 — monthly
  • packages/services/src/insights/shared.ts:252-258, :935-936; apps/web/src/routes/router.ts:426-496; apps/api/src/trpc/insights/index.ts:331-813 — query side
  • curateContentInsights.ts:85-162, :309-323; contentInsightCurationCadence.ts:1-2, :31-58; packages/services/src/insights/curateContentInsights.ts:43-191; packages/llm/src/contentInsightCuration.ts:24-93; packages/ports/src/contentInsightCuration.ts:8-43; contentInsightConfigurations.ts:132-200 — curation
  • planning_docs/insights-v2/epic.md:101-102, :1339-1348, :1593-1594 — limits

2. Insights V2: built, retired, held

Epic ZUBEA-259 ("In Progress") aims to make journeys, drop-off, revival, conversion and conversation quality replayable and to release only validated aggregates.

PieceStatusNotes
Target detail /target/$id, one Insights tab; /contacts/$id redirectsGABase insights (summary, concerns, competitors, next step, actionable insights…) for all authorised users.
waitingOnTarget (max five things the lead owes)admin-onlyProduced by the normal Call Insights call, persisted, cleared on completion. Missed its precision gate: 77.3% vs 80% target; MiCampus 33.3% vs a 70% client floor.
Categorical Sentiment Analysisadmin-onlySee §4. No accuracy claim: of 6 Gemini duplicates only 2 were fully exact; human gold labels still required.
Conversion workspace (outcomes, funnel, time-to-convert, time-in-stage, loss reasons)flag: insights_conversionBacked by a versioned, rebuildable CRM conversion projection (attribution v4), rebuilt every 10 min and on startup, plus CRM stage-run measurements (J0).
Standalone Additive-action and semantic Drop-off streamsretiredNo fallback. /insights/additive-v2, /insights/dropoffs, /insights/sentiment-v3, /insights/revival retired; advanced_insight_observations dropped.
Automated revival (R0–R2), quality→outcome metric (Q0), privacy-safe long-term aggregates (P1)plannedHeld.

The approved conversion contract: controller-turn attribution bands, first terminal outcome, poll-observed stage timing with an explicit "not exact" disclaimer, and a ≥30-leads / ≥50%-coverage rule before showing observed age.

Drift. The epic says the advanced section merges the "current voice snapshot" sentiment; the live admin API returns only sentiment.textConversations. Numeric (V1) sentiment, which supplied the voice snapshot, was deleted and conversations.ts has no sentiment column. The README's "bounded, idempotent historical voice repair" could not be located — unverified.
Evidence
  • planning_docs/insights-v2/epic.md:5-8, :32-37, :60-102, :104-216, :256-263, :372, :1363-1372, :1580-1592
  • apps/web/src/features/contacts/useContactDetailSearchState.ts:6, apps/web/src/routes/router.ts:364-380, :858-872
  • apps/web/src/ui/new/contacts/detail/ContactInsights.tsx:130-150, :172
  • onConversationComplete.persistence.ts:596, :608-647; packages/db/src/schema/targets.ts:328; packages/llm/src/prompts/insights/callInsights.ts:343, :656-659 — waitingOnTarget
  • apps/api/src/trpc/insights/salesMotionProcedures.ts:428-474 — admin sentiment read
  • apps/api/src/trpc/insights/crmOutcome.ts:560-697; rebuildCrmConversionProjections.ts:51-60; crmConversionProjectionBuildService.ts:73; crmConversionProjections.ts:46, :99, :247; crmStageMeasurements.ts:52, :139, :211
  • packages/db/drizzle/0053_lyrical_garia.sql:6; planning_docs/insights-v2/README.md:15-28; planning_docs/hourly-flex-insights/epic.md:33

3. Call Insights and the lead-score rubric

After each conversation, structured lead intelligence is extracted onto the target. This is the main source for content insights, escalations, reminders and lead score. Machine: on_conversation_complete (see Machines).

  1. Short-circuit low-token transcripts (shortCircuitLowTokens).
  2. Not-interested classification with gpt.fast. On that branch the machine writes score 0 plus a summary. Voice's on_call_complete runs no insight generation; its only insight side effect is a fixed score=0, "Caller indicated they are not interested." write. Voice Call Insights come from on_conversation_complete.
  3. Generate (generatingInsights): the adapter resolves the workflow's content-insight configuration and calls generateCallInsights at gpt.smart (GPT-6 Luna, high effort). Fields include reminder extraction, caller profile, lead_score {score 0-100, justification}, summaries, unanswered questions, interest, decision factors, competitors, concerns, timeline, funding, waiting_on_target, call_booked. A shadow lead-lifecycle classification starts in parallel (§6).
  4. Persist in lane 1, committed in the runner's tx_final: targets.updateTargetInsights, skipped when target status is completed | override | help_needed | paused. A conversation-summary fallback write also runs.
  5. Reconcile reminders with gpt.fast (reconcilingReminders).
0–10
relevance gate
Misrouted enquiries.
70+
flagged
"Flagged to the human team".
91–100
milestones
Milestone semantics.
100
paying customer
Active paying customer.

Score buckets 0–30, 31–70, 71–80, 81–95 and 96–100 drive the daily_metrics HLL columns and the content score-bucket counts.

Evidence
  • onConversationComplete.machine.ts:238-856 (states), :324, :386, :524
  • packages/services/src/conversations/classifyNotInterested.ts:12, :35; onConversationComplete.persistence.ts:175-216, :560-605, :650-682
  • packages/workflows/src/machines/onCallComplete.machine.ts:1-11
  • defaultMachineActorAdapters.ts:454-490; packages/services/src/insights/callInsights.ts:19, :210-247; packages/llm/src/models.ts:167-174
  • packages/llm/src/prompts/insights/callInsights.ts:103-106, :250-330, :613-640 — schema and rubric
  • packages/services/src/reminders/validator.ts:33, :109-164
  • README.md:141, dailyMetrics.ts:188-193 — buckets

4. Half-hour deferred analysis: sentiment and custom analyzers

The hourly-flex epic (ZUBEA-317, approved) moved latency-tolerant analytics off the conversation-complete path. Call Insights stays immediate because it owns escalation, callback and reminder decisions.

  • Job: processDeferredConversationAnalyses, cron 5,35 * * * * UTC, non-singleton, needs the llmBatch resource.
  • Window: the previous closed half hour. A conversation qualifies only with a transcript message inside the window; the prefix up to window end is captured.
  • Sentiment eligibility: non-voice channel with at least one user text message; an existing completed snapshot for the same transcript hash is skipped. Written with sentimentAnalysisObservations.insertCompleted.
  • Custom analysis: one row per target, using the target's analyzer or the org's only analyzer; skipped for completed targets unless shouldAnalyzeIfNotInterested. Input is the company brief plus only the custom definitions referenced by the analyzer's aggregationSpec.
  • Model: with a batch client, BATCH_MODEL_ID = 'gpt-6-luna' through OpenAI-first batch (Vertex fallback); otherwise gemini-3.8-flash.
  • Store: sentiment_analysis_observations, one row per (org, conversation, transcript hash) with messageStartIndex, messageCount, observedAt and JSONB result. Four modules with fixed enums: affect_frustration, friction, defect_attribution, resolution_next.
  • Analyzer definitions are org settings stored in organizations.custom_analyzers: id, name, description, typeDefJSONSchema (validated JSON Schema), prompt, shouldAnalyzeIfNotInterested, aggregationSpec. UI /account/analyzers. An online generateCustomAnalysis helper uses gpt.fast; in services/workflows the scheduled path is the batch job.
Accepted gaps. The half-hour cadence is for submission only — no completion guarantee, no online fallback, retry or backfill; permanent gaps are accepted; voice sentiment is excluded. Model drift: code uses gpt-6-luna via OpenAI-first batch (planning doc says Vertex gemini-3.7-flash — stale).
Evidence
  • packages/services/src/scheduler/jobs/processDeferredConversationAnalyses.ts:42-44, :130-172, :200-309, :350-354, :576
  • apps/scheduler/src/composition.ts:255-263
  • packages/db/src/schema/sentimentAnalysisObservations.ts:18-61, :118-134
  • packages/webapp-contracts/src/settings/index.ts:188-218; packages/db/src/schema/organizations.ts:465-467; apps/web/src/routes/router.ts:783; packages/services/src/insights/customAnalyzer.ts:21, :120-144
  • planning_docs/hourly-flex-insights/epic.md:5-9, :13-35, :42, :50-57

5. Guardrails and escalation routing

Epic status: slices 0–5 and 7 implemented for the WhatsApp internal-test milestone; slice 6 was called a post-June fast-follow (code for it exists — see below).

Guardrail config

  • Guardrails live in the agentic messaging template JSON, at template level and per graph node. Three types: redirect (description, redirectMethod, escalateAfterX 1–10, default 1), escalate, respondAndEscalate. Each can opt into emailForwarding.
  • Hidden identity: guardrailId is stable across edits; guardrailRevisionId bumps only on behavioural change; the server reconciles dropped IDs. Backfill: bun run migration:backfill-guardrail-ids.

"LLM matches, code counts"

  1. The planner copies the matching guardrail's guardrailId into guardrail_directive.matchedGuardrailId (or null); planner and finalizer propagate it. The production prompt no longer does prior_hits/total_hits arithmetic (those strings appear only in a test file).
  2. Code writes a GuardrailEvaluationMetadata record on the triggering inbound transcript item: action, lookbackWindowSeconds, priorHitCountInLookback, totalHitCountInLookback = prior + 1.
  3. countPriorGuardrailHitsInLookback counts earlier evaluations in the same conversation transcript with the same templateId and guardrailId, default lookback 3 days, deduplicated by guardrailViolationId.
  4. Threshold: escalate always; respondAndEscalate when totalHit ≥ escalateAfterX; redirect when priorHit ≥ escalateAfterX — so escalateAfterX is the number of redirects allowed before handoff.
  5. The audit ID is deterministic per violation, so retries do not duplicate rows.

Escalation routing: synthesizeUrgentActions

Escalation rules are org settings (escalationRules), edited at /account/escalations. The synthesiser runs before an urgent audit row is persisted.

Planner + finalizer (LLM) copies matching guardrailId into guardrail_directive or null Code counts same transcript, template, guardrailId 3-day lookback deduped by violation id Threshold (code) escalate: always respondAndEscalate: total ≥ X redirect: prior ≥ X Urgent audit entry deterministic id per violation non-system_issue only → synthesise before persist synthesizeUrgentActions Tier 1 · structured rules enabled rules, priority desc severity + event type + context fallback rules only if nothing else matched deduped push/email actions Tier 2 · decision model candidates: exact conditions pass Decision-1 via OpenRouter one choice: a rule or none use if conf ≥ 0.95, p ≥ 0.95 no port → failed/not_configured Tier 3 · default push to defaultPushUserId else email to opsEmail else nothing reminders job supplies both; workflow runner supplies neither audit_trail row actions (push/email) + _escalation metadata: matched rules, tier, decision, evaluated context miss miss SES escalation email enriched metadata; links to /reminders/audit-trail /target/<id> Push actions kept for legacy byte-parity dispatcher drops them at send-time Runner, no rule matched opsEmail null, no push user → nothing sent visible in the app only In-app activity log /reminders/audit-trail acknowledge → acknowledgement metrics
Escalation path. The LLM only names which guardrail matched and, in Tier 2, picks at most one already-eligible rule; counting, thresholds, defaults and dedupe are code. Email actions go out by SES; push actions are dropped at send-time.
  • Tier 1: enabled rules sorted by priority descending; a rule matches when severity, event type and context conditions all pass. Fallback rules (onlyWhenNoOtherRuleMatches) run only if nothing else matched.
  • Tier 2: only over rules whose exact conditions all pass (category, owner, channel, workflow, lead-score range); the decision port chooses at most one. Missing port → failed/not_configured and routing falls through.
  • Tier 3: push to defaultPushUserId if supplied, else email to opsEmail, else nothing.
  • Runner wiring (slice 4a): the workflow runner calls the synthesiser for urgent, non-system_issue entries with opsEmail: null and no default push user, so a workflow escalation with no matching rule sends nothing and is visible in the app only. processDueReminders supplies a defaultPushUserId and the decision port.
  • Forwarding (slice 6): Google and Microsoft wrappers have forwardMessage; a post-commit guardrail forwarder runs from inbound email and awaiting-action paths. Built, although the epic still calls it fast-follow.
Limits. Counting is per conversation, not per target or across channels. Guardrail definitions stay in JSONB with no violation-event table; cross-conversation analytics would need a future projection table.
Evidence
  • planning_docs/guardrail-escalation-intelligence/epic.md:5-16, :48-58, :297-320, :353-358; checklist.md slice 1
  • packages/webapp-contracts/src/agentConfig/index.ts:119-157; apps/api/src/trpc/templates/guardrailIdentity.ts; package.json:132
  • packages/llm/src/prompts/fragments/guardrails.ts:7-10; plannerNode.ts:196-215, :474-480; finalizerNode.ts:90-181
  • packages/workflows/src/machines/textMessageGuardrails.ts:23, :39-74, :474-569; packages/db/src/schema/conversations.ts:66-72
  • packages/services/src/auditTrail/escalationSynthesis.ts:115-192, :274-454
  • packages/workflows/src/runner/workflowRunnerAudit.ts:172-219; processDueReminders.ts:391-400
  • packages/notifications/src/ses/escalationEmail.ts:19-39; apps/web/src/routes/router.ts:791
  • packages/external-connectors/email/src/google.ts:515, microsoft.ts:526; packages/services/src/email/guardrailForwarding.ts:52, inboundDispatch.ts:665; checkAwaitingAction.ts:259

6. Decision models: "Jev" → Microsoft Decision-1

The research docs describe TypeSafe AI's early-access "System One" model ("Jev") for typed probabilistic decisions: noul, choice and score questions with probabilities and confidence. The harness principle: deterministic eligibility and safety guards first, then small named questions to the model; code owns threshold, fallback and audit. Explicitly never Jev: CRM identity, consent, final sends, calendar integrity and similar controls.

In code, every decision client calls OpenRouter's systemone endpoint, requests microsoft/microsoft-decision-1 and requires the resolved model to be microsoft/microsoft-decision-1-20261009. Clients are wired only when OPENROUTER_API_KEY is set. File names still say "Jev" (jevTransport.ts, jevLeadLifecycle.ts).

UseBehaviourGate
Escalation rule Tier 2One choice over candidate rules plus none. Emails and phones masked; owners get opaque labels. Response must carry the exact resolved model; probabilities must sum to about 1. Used only when confidence ≥ 0.95 and chosen probability ≥ 0.95 (threshold chosen on 180 tuning and 93 held-out events).gated on key presence
Lead lifecycle stage (shadow)Classifies the customer-side transcript as prospect / customer / not a customer and stores an observation. Input-hash dedupe; classifier version lead-lifecycle-microsoft-v1. "Nothing is displayed and nothing is sent to a CRM."flag: lead_lifecycle_stage + org inference region global
Lingua campus syncbackNon-exact campus text only. Accepted when confidence ≥ 0.75 and support ≥ 0.75; otherwise the existing gpt.fast classifier. Missing key writes a system_issue audit.custom: Lingua (no flag check found)
Nexus taxonomy matchingUses decisionClient.decide, wired in the scheduler to Decision-1 via OpenRouter (an "unavailable" stub without the key; apps/scheduler/src/composition.ts:300-306).flag: nexus_taxonomy

Experiment status (docs): Lingua campus study 58/60 valid outputs, 52/58 agreeing with an internal LLM review, a second run matching 51/54 — "exploratory success", not human gold. Experiment queue 01–17, most not run; 17 (custom-analyzer enum) withdrawn.

Evidence
  • planning_docs/jev-decision-research.md:13-29, :44-64; planning_docs/jev-tests/experiments/README.md:3-38
  • packages/llm/src/jevTransport.ts — OpenRouter systemone URL
  • packages/llm/src/escalationRuleDecision.ts:17-44, :59-89, :215-267; jevLeadLifecycle.ts:19-20; jevCampusSelection.ts:16-17
  • packages/app-composition/src/runtimeInputs.ts:160-187; packages/config/src/env.ts:251
  • packages/services/src/insights/leadLifecycle/conversationClassifier.ts:19-24, :112-206; packages/webapp-contracts/src/admin/index.ts:256-262
  • packages/services/src/runtime/clientHookEffects.ts:171-231; packages/workflows/src/clients/lingua/hooks/crmSyncback.ts:225-245
  • packages/services/src/knowledge/nexusTaxonomyMatchers.ts:305

7. Audit trail, take-over rows, reminders, acknowledgement metrics

  • audit_trail: 16-value type enum; source system|user|zube|external; severity info|warning|error|urgent; category positive_intent|human_requested|needs_assistance|guardrail|system_issue|informational; metadata, actions (push/email), acknowledged, acknowledgedBy, acknowledgedAt.
  • Policy: the audit trail is the client's activity log. Urgent rows are only take-overs, human follow-ups, guardrail escalations and configured reminders. System faults are Zube-only: the repository diverts system_issue inputs to error tracking instead of persisting them.
  • Take-over row: buildCannotRespondTakeOverAudit produces the standard "AI Requested Human Help" row with a deterministic ID.
  • Notification cooldown: 24 h default, bypassed for human-owned status transitions.
  • Reminders: processDueReminders hourly at :00:20 validates and disposes due reminders with gpt.fast. UI /reminders/audit-trail.
  • Acknowledgement metrics (aclProcedure('insights.view'), route /insights/audit-metrics): scope is urgent rows whose category is not system_issue or informational, acknowledged with a non-null acknowledger, in the org-local date range (org timezone, UTC fallback); pending is the same scope with acknowledged=false. Non-goal: no acknowledgement event ledger, so only the latest acknowledger counts.
Evidence
  • packages/db/src/schema/auditTrail.ts:20-60, :79-120
  • guidance/engineering-constraints.md:136-141; packages/repositories/src/surfaces/auditTrail.ts:50-54, :145-153, :586-595, :660, :729
  • packages/services/src/auditTrail/cannotRespond.ts:17-30; notificationCooldown.ts:11-89
  • processDueReminders.ts:715-725; apps/web/src/routes/router.ts:396, :489-496
  • planning_docs/audit-trail-acknowledgement-metrics/implementation_plan.md:3-107; packages/services/src/insights/auditAcknowledgementMetrics.ts:30-55, :133-146; apps/api/src/trpc/insights/index.ts:729

8. Drop-off observation (the "SalesMotion" jobs)

Three generations exist. Only the third is live.

GenerationStatusWhat it is
1. Legacy tableslegacythread_dropoff_events (conversation-unique, is_revivable, revival_dispatched_at), daily_dropoff_metrics, monthly_dropoff_metrics. No production writer: dropoffEvents.createOnce and metrics.upsertDailyDropoffMetric are called only from integration tests. The monthly job still rolls up daily rows; true-admin hasDropoffData, getDropoffOverviewKPIs, getDropoffByReason remain. revival_metrics was dropped.
2. Four-state "Sales Motion" designplanned (superseded)ZUBEA-319 doc: states lost, won, active, dropped_off, plausible_active_customer, a Gemini 3.7 Flash adjudication, a sales_motion_observation flag and 20-row retention. None of this is in code; the successor doc removed "model state/action fields".
3. Deterministic cohort + LLM explanationadmin-onlyBelow.

Current pipeline

  1. reconcileSalesMotionObservations, daily 02:15 UTC: "enqueues the prior 48–72 hour drop-off cohort". Pages dropoffObservations.listDailyCandidates, rebuilds a deterministic candidate, enqueues keyed by snapshot date and prompt hash.
  2. Deterministic cohort (no LLM) requires all of: eligible org CRM scope (active org, healthy two-sided won/lost mapping); a CRM-linked target whose latest production CRM outcome bucket is open; 0 < leadScore < 100; at least 5 transcript messages across the journey; a latest accepted company outbound (accepted/sent/delivered/read) inside [evaluatedAt − 72h, evaluatedAt − 48h) with no later lead reply.
  3. processSalesMotionObservations, every minute, claims batches of 10; rows processing > 30 min are requeued. Each claim re-prepares the candidate and verifies source/trigger fingerprints and prompt hash (else source_changed and invalidate), rejects journeys over 700k rendered characters, calls the LLM, and publishes in a source-fenced transaction.
  4. LLM: gpt.fast (GPT-6 Luna), reasoningEffort: 'high', no structured fallbacks, at most 2 generations, JSON-prefix recovery off. Input: trigger timestamp, the org's canonical loss-reason catalog and reserved aliases, the complete rendered journey.
  5. Output: nullable causalReason (basis: explicit_evidence|contextual_inference, existing category ID or new proposal, 1–4 evidence refs) and nullable topic (code, label, 1–4 refs); strict, no prose. The prompt forbids stopped_responding, unknown, other as causes and forbids inferring cause from topic alone; the host rejects unknown evidence refs, silence categories and colliding new codes.
  6. Store: dropoff_observations — snapshot date, fingerprints, prompt hash, causal category, evidence refs, topic, model tier/ID/provider, claim/complete/invalidate timestamps, attempt count, regeneration manifest links.
  7. Surface (true-admin): /contacts/revival (/insights/revival redirects); getSalesMotionOverview, getSalesMotionTarget, listSalesMotionTargets, getTargetAdminInsights.

Alongside: bootstrapSalesMotionCrmOutcomes runs every minute at second 15, backfilling canonical CRM outcome observations for existing targets through the HubSpot/Salesforce/Dynamics wrappers, reading candidates via the older salesMotionObservations repository.

Not built. No revival eligibility, campaign mapping, CRM syncback or messaging; no historical sweep beyond the daily window except the regeneration tool (§10). Customer rollout needs a new untouched acceptance cohort (≥90% state accuracy, ≥80% per-state recall, and more).
Evidence
  • packages/db/src/schema/threadDropoffEvents.ts:17-76, dailyDropoffMetrics.ts:17, monthlyDropoffMetrics.ts:18; packages/services/src/repositoryTests/*.integration.test.ts; aggregateMonthlyInsights.ts:118-128; apps/api/src/trpc/insights/index.ts:416-443; packages/db/drizzle/0065_daffy_strong_guy.sql:48
  • planning_docs/dropoff-observation/epic.md:3-37, :91-156, :361-366, :385-392; planning_docs/revival-shared-categories/epic.md:42; packages/webapp-contracts/src/admin/index.ts:225-230
  • reconcileSalesMotionObservations.ts:23-31, :42-90
  • packages/repositories/src/dropoffObservations.ts:130-228; dropoffCandidateDomain.ts:21-31, :340-370
  • processSalesMotionObservations.ts:7-8, :28-56; packages/services/src/insights/dropoffObservation.ts:25-26, :91-193, :221-267
  • packages/llm/src/prompts/insights/dropoffExplanation.ts:7-53; packages/db/src/schema/dropoffObservations.ts:79-114
  • apps/web/src/routes/router.ts:873-885; salesMotionProcedures.ts:428-542; bootstrapSalesMotionCrmOutcomes.ts:363, :608-623

9. Loss-reason intelligence

Explains supported reasons for CRM-lost leads when CRM reasons are blank or generic, with an honest "uncertain" remainder. Silence or the last topic is not a cause.

  • Imported MVP (ZUBEA-357): immutable loss_insight_runs and loss_insight_records, plus a loss_insight_reason_collations artifact that populates the shared loss_reason catalog in insight_categories. Initial import: MiCampus 1,758/1,755/3 and Lingua 31/31/0 (attempted/valid/failed); Stay Club excluded.
  • Daily generation, an isolated branch of the 12:05 UTC aggregateInsights tick: claims a UTC day window per org (duplicate ticks make no provider calls); candidates are targets with a resolved CRM lost outcome or a current lead score of exactly 0; freezes prepared inputs, then extraction and collation in at most two batch attempts (the second only for failed keys). Model gemini-3.8-flash, maxBatchAttempts: 1 per adapter call, thinking MEDIUM; composition wires OpenAILossInsightBatch when OPENAI_API_KEY is present, else VertexLossInsightBatch. Tables loss_insight_daily_runs, loss_insight_daily_items. Terminal reasons such as submission_uncertain and loss_snapshot_base_changed are recorded and the run closed.
  • Surfaces: Conversion page loss reasons (flag-gated: lossRecords.getConversionSummary/getConversionEvidence, scoped by the page's date, audience and segment filters; the unscoped getLossReasons path was removed); internal review lossRecords.getOverview/list/getDetail (true-admin) at /insights/loss-records; true-admin category tools resolveOrCreateLossReasonCategory, consolidateLossReasonCategory.
  • Limits: missed days are not replayed; no online fallback or retry queue; catalog capped at 100 categories ("visible terminal capacity failure"); customer-wide rollout outside the MVP.
Evidence
  • planning_docs/loss-reason-intelligence/epic.md:3-30; production-mvp.md:5-35; daily-generation.html
  • packages/db/src/schema/lossInsights.ts:29, :72; lossInsightReasonCollations.ts:72; lossInsightDaily.ts:54, :103
  • packages/services/src/insights/dailyLossGeneration.ts:68-95, :121-170, :312, :611-688
  • packages/llm/src/insights/lossInsightBatch.ts:36, :169-176; apps/scheduler/src/composition.ts:642-645
  • apps/api/src/trpc/insights/crmOutcome.ts:697; lossRecords.ts:218-327; apps/api/src/trpc/insights/index.ts:633-679; apps/web/src/routes/router.ts:842-848

10. Revival shared categories and historical regeneration

ZUBEA-319, implementation authorised and internal-only; the branch was accepted as merge-ready on 2026-09-08. Production regeneration was authorised on 2026-09-07 but still gated on deployment, local rehearsal, read-only preview and fresh review. Whether apply ever ran in production is unverified.

  • Design: one org-scoped causal vocabulary (insight_categories, insightType=loss_reason) shared by loss and drop-off; loss records and drop-off observations stay separate; a deterministic selector owns membership, the LLM returns only nullable cause, topic, evidence and basis; aliases resolve to canonical categories at read time.
  • Built: drop-off explanation loads the shared loss catalog (loadLossReasonCategoryCatalog); new proposals go through normalizeLossReasonCategory.
  • Historical regeneration ops tool: recomputes drop-off explanations for past cohort dates with the same prepareDeterministicDropoffCandidate and generateDropoffExplanation. Runner API preview, run, runReviewed, rehearse, apply, verify. Manifests are hashed and validated; state in historical_regeneration_* tables (manifests, sources, outputs, checkpoints, archived observations/categories, active scopes).
  • CLI: scripts/operations/historicalDropoffRegeneration.ts with apply|generate|preview|rehearse|verify; requires explicit --env-file, --organization, --cohort-date ("no all-tenant default"); apply needs --apply and --manifest-hash.
  • Doc intent: preview is read-only (repeatable-read, no provider calls); apply archives before an atomic scope switch and aborts on any source drift; automated rollback deliberately not shipped.
Evidence
  • planning_docs/revival-shared-categories/epic.md:3-14, :36-44, :153-230
  • dropoffObservation.ts:181-207, :249-252; packages/repositories/src/dropoffObservations.ts:124-128
  • packages/services/src/historicalRegeneration.ts:1-25; historicalRegenerationContracts.ts:251-276; historicalRegenerationManifest.ts:146-436; packages/db/src/schema/historicalRegeneration.ts:141-378
  • scripts/operations/historicalDropoffRegeneration.ts:25, :83-95, :150-154

11. Client report generation

Recurring per-client operational spreadsheet reports. Report types are client-specific code; report definitions are DB rows editable in the UI. Every file is stored durably, then emailed. No LLM: deterministic queries plus XLSX/CSV/TSV writers.

  • Tables: report_definitions, report_runs.
  • Job: processDueReports, every minute at :30, singleton, five isolated phases: janitor (reclaims runs stuck running past a 30-minute TTL) → due-scan (one pending run per missed window, CAS on next_run_at) → execution (generate, store in GCS + file_storage, mark complete) → delivery (attachment, or signed link when oversize) → failure (urgent operator-facing audit row).
  • Generators (4): MiCampus Salesforce lead cohort (seven-sheet XLSX), MiCampus Salesforce conversion performance, Stay Club Meta Ads efficacy, Addison Lee media production weekly. Workflow-free metadata in packages/client-tools; the scheduler wires the registry.
  • API: listReportTypes filters to generator.organizationId === actor.organizationId; view/list need organizationSettings.view; upsert, delete, generateReport need organizationSettings.manage. UI /integrations/reports. A report type exists only for orgs that have a generator.
Evidence
  • planning_docs/client-report-generation/epic.md:1-6; fast-follow-first-generator.md
  • packages/db/src/schema/reportDefinitions.ts:30, reportRuns.ts:40
  • packages/services/src/scheduler/jobs/processDueReports.ts:1-18, :694-704
  • packages/workflows/src/clients/reporting.ts:16-26; packages/client-tools/src/clients/reporting.ts:24-34; apps/scheduler/src/composition.ts:115, :225
  • apps/api/src/trpc/reports/index.ts:218-471; apps/web/src/routes/router.ts:850-856; packages/services/src/reporting/{xlsx,csv,tsv}.ts

12. Client semantic routing with gpt.fast

ZUBEA-310 ("implemented; in review" per doc) replaced regex and keyword classifiers that decided customer-facing sends, CRM values or cadences for Lingua, MiCampus and Stay Club with constrained gpt.fast structured outputs that fail closed. Addison Lee is out of scope. See Custom client code for where hooks live.

  • Client hook effects use tier: 'gpt.fast'; Stay Club selector and email-cadence models are gpt.fast.
  • Lingua: exact canonical lookup first, then Decision-1, then the gpt.fast fallback.
  • Stay Club classifier failures route to help_needed.
  • Validation (doc): a 2,180-row Lingua and 128-row Stay Club read-only replay with zero model failures.
Evidence
  • planning_docs/client-semantic-routing-gpt-fast/epic.md:3-22, :40-48, :63-67
  • packages/services/src/runtime/clientHookEffects.ts:261, :292, :339, :361, :400
  • packages/workflows/src/clients/stayClub/llmSelectionPrompts.ts:3; cadences/outboundCadences.ts:24; postWorkflowHandoffs.ts:728
  • packages/workflows/src/clients/lingua/hooks/crmSyncback.ts:215-255

13. Lead assignment strategies

  • autoAssignCreatedLead runs only for newly created, unassigned targets; settings in org accessControlSettings JSONB.
  • Callers: inbound resolution, email inbound dispatch, email and Meta history sync, manual import.
  • Strategies: inbound_channel_owner; round_robin (cursor in settings advanced by CAS); random (weighted); llm (gpt.fast picks a userId from eligible users with a short reason).
  • Results: assigned, disabled, ineligible, llm_failed, missing_llm_client, not_found, settings_conflict, skipped_existing_owner.
  • Automation issues are written as system_issue audits, which the repository diverts to error tracking. History goes to target_assignment_events.
Evidence
  • packages/services/src/leadAssignment/autoAssignment.ts:21-55, :76-95, :282-287, :395-690; contracts.ts:139-150
  • packages/services/src/targets/inboundResolution.ts:565; email/inboundDispatch.ts:447; email/historySyncBody.ts:398; metaMessaging/historySyncBody.ts:797; manualImport/createTarget.ts:377
  • packages/db/src/schema/targetAssignmentEvents.ts:16

14. Voice transfer outcome buckets

Daily metrics classify each voice transfer into five buckets, intentionally diverging from the legacy classifier, which lumped no-answer, abandonment and technical faults together. Surfaced in Insights Performance and the web contract.

BucketRule
completedTransfer completed.
reachedNoPickupLast attempt status no_answer or amd_machine. "NOT a Zube fault".
callerHangupLast status dialing or dial_call_ended, or a dial/bridge error while the caller hung up.
failedGenuine dial or bridge error, or no usable signal.
notAttemptedNo attempt records.
History. Only the 8-day trailing window is re-computed, so older rows keep whatever buckets they had. No tracked transfer-outcome backfill script was found; whether one was ever run is unverified.
Evidence
  • packages/services/src/insights/dailyMetricsReducer.ts:133-204; packages/db/src/schema/dailyMetrics.ts:44-56
  • packages/services/src/insights/performance.ts:197-198, :466; packages/webapp-contracts/src/insights/index.ts:763
  • aggregateInsights.ts:276-279 — 8-day window

15. RevOps deal intelligence

Storage, API and UI are built behind revops_deals. The deal-reconstruction pipeline is not in the tracked repo; where it lives is unverified.

  • Tables (migration 0094_shocking_marrow.sql): revops_deals (CRM provider, deal ID, name); revops_deal_targets (people on the deal: organisation, title, department, decisionRole, canBlock[], first/last-seen and left dates); revops_conversations (provider thread, subject, timestamps); revops_deal_days (as-of day snapshot with isCheckpoint, pipelineVersion).
  • Load: scripts/operations/prodDbRevopsDealLoad*.ts loads "one as-of RevOps deal export into an existing organization": rehearse against a loopback DB, then apply via prodDbSql, which rolls back unless --commit.
  • API: revopsProcedure = organizationFeatureProcedure('conversations.view', 'revops_deals') exposing listDeals, getDealDay, getConversation, listConversations, searchConversations, getDealNotes.
  • UI: /deals (overview, pipeline, /$dealId) behind OrganizationFeatureGate; client-side deal models in apps/web/src/features/deals/model/* (dependency graph, decision, needs-attention, timeline). Flag text: "Shows deals reconstructed from their email threads, day by day, in the new workspace UI. Nothing is sent to a CRM."
Evidence
  • packages/db/src/schema/revops.ts:30-31, :53-82, :97-104, :129-143
  • scripts/operations/prodDbRevopsDealLoad.ts:19-23
  • apps/api/src/trpc/revops/index.ts:28-29, :134-282; apps/web/src/routes/dealsRoutes.ts:13-54; packages/webapp-contracts/src/admin/index.ts:264-270
  • No RevOps planning doc under planning_docs/; git ls-files shows no tracked pipeline code

Doc-vs-code drift

AreaDoc says (stale)Code says
Insight LLM routeGemini 3.6 primaryGemini tiers rewritten to GPT-6 Luna on initial generation; Call Insights authored as gpt.smart
Deferred sentiment / customVertex gemini-3.7-flashgpt-6-luna via OpenAI-first batch
Drop-off modelGemini 3.7 Flash adjudicates active / dropped_off / plausible customerDeterministic selection; gpt.fast explains cause/topic only
sales_motion_observation flagGates customer readsNot in the feature-key enum; reads are true-admin
Voice sentiment in admin timelineIncludedText conversations only
Report registryV1 ships empty4 generators registered
Guardrail email forwardingSlice 6 post-June fast-followforwardMessage and a post-commit forwarder exist
JevTypeSafe Jevmicrosoft/microsoft-decision-1 via OpenRouter
Lingua Jev trialBehind a per-org default-off flagNo flag check; gated only by the Lingua hook and key presence
README revival metricsLists revival metric fieldsrevival_metrics dropped
aggregateInsights header comment"daily dropoff metric build"No daily drop-off write in the job body; upsertDailyDropoffMetric has only test callers
Evidence
  • planning_docs/insights-v2/README.md:21-24 vs packages/llm/src/models.ts:196-210, packages/services/src/insights/callInsights.ts:19
  • planning_docs/hourly-flex-insights/epic.md:27 vs processDeferredConversationAnalyses.ts:44, apps/scheduler/src/composition.ts:255-263
  • planning_docs/dropoff-observation/epic.md:13-15, :134-139, :151-153 vs dropoffObservation.ts:25, dropoffExplanation.ts:7-53, packages/webapp-contracts/src/admin/index.ts:225-230
  • planning_docs/insights-v2/epic.md:256-259 vs salesMotionProcedures.ts:463-471
  • planning_docs/client-report-generation/epic.md:6 vs packages/workflows/src/clients/reporting.ts:16-21
  • planning_docs/guardrail-escalation-intelligence/epic.md:5-16 vs google.ts:515, guardrailForwarding.ts:52
  • planning_docs/jev-decision-research.md:19-21 vs escalationRuleDecision.ts:17-18
  • planning_docs/jev-tests/experiments/README.md:3 vs clientHookEffects.ts:171-231, crmSyncback.ts:225-245
  • README.md:281-300 vs packages/db/drizzle/0065_daffy_strong_guy.sql:48
  • aggregateInsights.ts:5-6 vs job body

Open uncertainties

  1. Production deployment and enablement of every feature: which orgs have insights_conversion, lead_lifecycle_stage, revops_deals or nexus_taxonomy on, and whether OPENROUTER_API_KEY and OPENAI_API_KEY are set in production. Not inspected.
  2. Where the historical voice summary/sentiment repair named in the Insights V2 README lives.
  3. Whether the revival historical regeneration apply ever ran in production (gated as of 2026-09-08).
  4. Whether a transfer-outcome historical backfill was ever applied.
  5. Where the RevOps deal-reconstruction pipeline code lives.
  6. Nexus taxonomy decision-client provider wiring.

Channels, outbound and booking features — a deep dive

What each lead-facing feature is, whether it is live, which client it was built for and which process runs it. The most important takeaway: outbound cadences are defined in code per client. There is no cadence builder, and the only operator control is an account-level kill switch.

Cadence definitions
Code only
Zod-validated OutboundCadenceConfig registered per client; no builder UI
Operator lever
outboundCadenceEnabled
Account toggle in contact-preference settings; default true
Cadence stage types
WhatsApp template, email
SMS stages are not supported
Outbound AI phone calls
Removed
Multi-app split Phase 2 removed them for legal reasons (commit 2b5147e32)
Feature flags are not the gate here. None of these features uses the per-org feature-flag catalog. That catalog holds only insights_conversion, nexus_taxonomy, lead_lifecycle_stage and revops_deals. Gating is done through client hooks in code, integration-row config, the outboundCadenceEnabled switch, or trueAdminProcedure. When someone asks "is X on for org Y?", check those places, not the flag table.
Evidence
  • packages/webapp-contracts/src/admin/index.ts:225-230: the full feature-flag catalog
  • platform research §7/§20: multi-app split Phase 2 removed all AI outbound calling (legal), outbound customer webhooks and /api/v1; commit 2b5147e32 removed AI outbound calling

Status summary

Process names are the deployables described in the ingress chapter: apps/webhooks (public ingress), apps/worker (receipt and turn processing), apps/scheduler (crons), apps/telephony-infra (Telnyx and ElevenLabs tool calls) and apps/api (tRPC).

FeatureStatusClientWhere it runsKey evidence
Generic outbound cadence engineGA custom: per-client cadencesStay Club, Lingua, miCampusscheduler wake sweep → workflow runneroutboundMessagingCadence.machine.ts:723-928; registerClients.ts:531-542
Cadence quiet hours (message window)UNCLEAR (unverified)——fields exist; no enforcement found
miCampus Google Ads WhatsApp cadencecustom: miCampus livemiCampusCRM sync → runner → cadencemicampus/postWorkflowHandoffs.ts:104-136
Addison Lee UC1 prospecting draftscustom: Addison LeeAddison Leeemail poller → client pre-hookaddisonLee/registerClient.ts:291-330; draftPersistence.ts:1-20
Addison Lee UC2 cold outboundcustom: Addison Lee removal scheduledAddison Leescheduler, 30 s tickclientOutboundTick.ts:5-22; outboundCampaignPolicy.ts:5-17
Send-safety holdGAallworkflow runner, around WhatsApp template sendstargets.ts:166-205; workflowRunnerAudit.ts:357-410
Outbound AI phone callsremoved——commit 2b5147e32
Outbound voice hold detectionplanned (unverified)——owner notes only
Embedded webchatgated per-org setup2 unnamed clientswebhooks (HTTP + WS), worker (turns), scheduler (idle finalise)apps/webhooks/src/webchat/*; apps/webchat-widget
Webchat → WhatsApp/email continuationgated off by default—webhooks, WhatsApp ingress, email pollerservices/webchat/continuation.ts; epic :8
WhatsApp coexistence (SMB echo, app-state, history)GA—webhooks (receipt, connect), workerwhatsappBusinessApp/router.ts:356-427; smbEcho.ts:1-12
WhatsApp BSUID / usernameGA (cadences phone-only)—workerwhatsappIdentity.ts:22-30; userIdUpdate.ts
WhatsApp edit safetyGA—workereditReplyPolicy.ts:1-60
Multilingual WhatsApp templatesGA deploy + sync stepLinguacadence stage sendcommit 9a2f9372f
Messenger / InstagramGA—worker; scheduler (history resumer)services/metaMessaging/index.ts
Calendar tools (Calendly, Microsoft)GA—agentic runtime; telephony-infra (voice)builtInToolCatalog.ts:153-166
Magic booking linkGAgenericagent tool; api (public tRPC); web pagecalendarToolExecutors.ts:381-470; trpc/magicLinks/index.ts:522-600
Calendar booking truth (appointments ledger)planned (approved)——no tables in schema
Link domain redirectsdormant partialStay Club exampleweb host + apiservices/magicLinks/index.ts:218-242
Configurable public voice demos + notes generatoradmin-onlyZube salesapi (public + true-admin), webadmin/publicVoiceDemos.ts:219-415
Vodafone call importGA backfill onlymiCampusapi + web uploadimportCall.ts:1-22
NICE CXonepartial connect onlyAddison Lee (owner notes)api, webniceCxone.ts:1-32
Telephony human transferGA—telephony-infratransferToHuman.ts; transferSequence.ts
Lusha prospecting connectorcustom: Addison Lee (only consumer)Addison LeeUC1 pipelineprospecting/src/lusha.ts
21 Degreesplanned21 Degrees—21-degrees/positioning.md:3
Dynamics 365gated release gates pendingpilot TBDscheduler CRM jobs; webhooks (OAuth callback)crm/src/dynamics*.ts; epic :166-179
FreshsalesGA read-only; deals not builtAddison Leescheduler CRM syncfreshsales/syncArm.ts; epic :173-198
CRM identity convergenceGAMiCampus evidencerepositories (CRM sync path)crmIdentity.ts:383, 615
Syncback reliability recoveryGAMiCampus, Linguascheduler syncbackepic :59-75
MiCampus Salesforce syncback hardeningGA (quiet period now 2 h)MiCampusscheduler CRM jobscrmCandidates.ts:28-33
Microsoft email auth recoveryGAAddison Lee incidentemail connector; schedulermicrosoftEmailAuthProtocol.ts:123-140
Account / OAuth provider linkingplanned——firebase.ts:9, 116
en-GB UI localeGAUK/EU orgsweblocale/index.ts:5
Spanish / org language settingsplanned——language-settings-localization/epic.md:8
Native audio (realtime voice)planned——native_audio/mvp_testing_plan.md:8

All provider HTTP calls go through packages/external-connectors/** and similar wrapper packages, so every feature below names its connector.

Two meanings of "handoff". In the workflow runner, a handoff is workflow-event dispatch (workflow_handoff_pending); cadences start through a post-workflow handoff. In webchat, moving a conversation to WhatsApp or email is called continuation in code, even though its planning doc is titled "webchat channel handoff". When an agent or a ticket says "handoff", ask which one.

Outbound cadence engine

Time-based, multi-step outbound sequences per target, made of WhatsApp template and email stages. A cadence stops on a reply, a target status change, or a safeguard.

There is no cadence builder. People often assume one exists. A cadence is a TypeScript config registered by a client module. Changing the copy, timing or stage list of a cadence is a code change and a deploy. The only operator lever in the UI is the account-level "outbound cadence" toggle.

Definition and registration

  • Config. OutboundCadenceConfig is a Zod schema. Stages are a discriminated union of whatsappTemplate and email.
    • WhatsApp stages carry templateName, an optional pinned wabaId and senderPhoneNumber, requireApprovedTemplate, languageCode, a languageCodeByPhoneCountry map and leadSourceAfterSuccess.
    • Email stages carry a subject, a body, an optional prompt and an llmModelName tier.
    • The config also holds call/message windows, weekend flags, blackout dates and month-days, spread/rate knobs, stopOnAnyReply (default true), completeOnSuccessfulCall and completeOnCallBooked.
    • SMS stages are dropped: they were not in the legacy OutboundStage union.
  • Registry. Each client registers cadences in a runtime-scoped registry that rejects duplicate IDs. Registered today: Stay Club, miCampus, Lingua outbound and Lingua revival. An optional client pre-send guard can be attached per registration.
  • Entry. A client hook calls buildOutboundCadencePostWorkflowHandoff after CRM sync or conversation completion (Stay Club cadence selection, Lingua and miCampus post-workflow hooks). For CRM-sync-triggered cadences the first stage is delayed by at least 900 s (CRM_SYNC_CADENCE_FIRST_STAGE_MIN_DELAY_SECONDS).

Lifecycle

One target, one cadence. Machine is a pure transducer; the runner and hooks do the I/O. 1 · Client post-workflow hook after CRM sync or conversation complete per-client selector (code) 2 · Cadence handoff buildOutboundCadence…Handoff refused if switch is off CRM-sync entry: stage 1 ≥ 900 s 3 · START outbound_messaging_cadence input CADENCE_STARTED (or HANDOFF_DELIVERY) 4 · CALLING (parked) target status awaiting_action_from_target with due next_action_at immediate send on CADENCE_STARTED 5 · checkAwaitingAction scheduler job, every 30 s re-enters due targets skips orgs with switch off 6 · WAKE branches stopped · booked · reply successful call · exhausted else: run the due stage 7 · Pre-send checks 6-rule safeguard matrix + client pre-send guard violation → STEP_FAILED + audit 8 · Provider send cadenceProviderSendHook WhatsApp template or email WhatsApp: send-safety hold due WAKE 9 · Feed back to the machine PROVIDER_RESULT or PROVIDER_FAILED next_action_at = now + delayAfterPrevious (failure advance: now) COMPLETED reply (stopOnAnyReply) · call booked · stages exhausted status completed / override / help_needed / paused stop branch next stage: park in CALLING again
Outbound cadence lifecycle. The kill switch acts in two places: at handoff (refused) and in the wake sweep (org skipped). Whether message-window quiet hours shape next_action_at is unverified; see below.
  1. Machine. outbound_messaging_cadence has states START → CALLING → COMPLETED and does no I/O. Inputs are CADENCE_STARTED and HANDOFF_DELIVERY. Target statuses completed, override, help_needed and paused stop it. Machine internals are in the machines chapter; the runner that hosts it is in XState runner.
  2. Wake. checkAwaitingAction runs every 30 s and re-enters targets in awaiting_action_from_target whose next_action_at is due. It reads outboundCadenceEnabled per org and skips cadence work where it is off.
  3. WAKE branches, in order: target stopped, call booked, stop-on-reply, successful call, stages exhausted. Otherwise the machine falls through and the runner executes the due stage.
  4. Safeguards. A pure 6-rule matrix runs before each send: stage-0 no-history gate, live WhatsApp conversation, template resend cap, multiple WhatsApp conversations, expected-before-stage, attempt counters. A violation becomes STEP_FAILED with a WARNING audit. Client pre-send guards run before the immediate CADENCE_STARTED send and before every WAKE.
  5. Provider send. cadenceProviderSendHook runs the due stage after the machine parks in CALLING, then feeds back PROVIDER_RESULT or PROVIDER_FAILED.
    • WhatsApp: cadenceWhatsappStageSend resolves the org's WhatsApp credential, renders template components against the target and calls sendTemplateMessage. If the stage requires an approved template, a missing or non-APPROVED template fails closed. Credentials come from a 4-step selection chain unless the stage pins a WABA and sender. Consecutive WhatsApp stages are skipped when the target lists WhatsApp in blockedChannels. Targets without a phone are skipped.
    • Email: executeCadenceEmailStage renders in TEMPLATE, PARTIAL_TEMPLATE or FREE_FORM mode. Links and opens are tracked through https://link.zube.ai/e.
  6. Next stage = now + delayAfterPrevious, or now on the provider-failure advance.
  7. Kill switch. defaultContactPreferences.outboundCadenceEnabled, default true, exposed as a toggle in the contact-preferences settings editor. When false, cadence handoffs are refused.
Quiet hours: UNCLEAR, unverified. Configs carry messageWindowStartHour/EndHour, allowMessageSaturday/Sunday and blackout dates, and these are frozen into the machine context. An inCallWindow guard exists. But the only next-stage scheduler found computes plain now + delay, and no other consumer of the message-window fields was found. Do not tell a client that cadence messages respect a send window until this is confirmed in code. Addison Lee UC2 enforces its own 09:00–17:00 London window, separately.

Cadences by client

ClientCadenceShape
Lingualingua_outbound_cadenceWhatsApp default_outbound_initial at 0 s, default_followup at +24 h. Template language by phone country: es for Spanish-speaking LATAM, pt_BR for Brazil, otherwise English.
Linguarevival cadenceMixed email and WhatsApp stages
Stay Clublegacy-ported cadencesIncludes a Meta-ads parent variant
miCampusmicampus_new_lead_{1,2,3}_<locale>Google Ads WhatsApp cadence, next section
Evidence
  • packages/workflows/src/registry/outboundCadenceRegistry.ts:49-85 — stage union; :90-127 config; :94-126 windows and stop flags; :1-11, 232-273 registry; :134-165 pre-send guard
  • packages/workflows/src/runner/cadenceProviderSendHook.ts:34-35 — SMS stages dropped; :1-30 send hook; :37-49 email modes; :716-737 failure advance; :739-746 blockedChannels skip
  • packages/workflows/src/clients/registerClients.ts:531-542 — registered cadences
  • packages/workflows/src/clients/postWorkflowHandoffs.ts:10, 31 — handoff builder, 900 s minimum (commit c260a5ada)
  • packages/workflows/src/clients/stayClub/cadenceSelection.ts:266; packages/workflows/src/clients/lingua/postWorkflowHandoffs.ts:7 — client entry points
  • packages/workflows/src/machines/outboundMessagingCadence.machine.ts:1-38 pure transducer; :87-92 stop statuses; :723-928 states; :797-836 WAKE branches; :964 inputs
  • packages/services/src/scheduler/jobs/checkAwaitingAction.ts:1-9, 152-188, 384-385 — wake sweep, per-org switch, 30 s
  • packages/workflows/src/safeguards/outboundMessagingCadenceSafeguards.ts:1-29 — 6-rule matrix
  • packages/workflows/src/runner/workflowRunnerCadence.ts:37, cadencePreSendGuardHook.ts — guard placement; :535-557 handoff refused when switch off
  • packages/services/src/whatsappBusinessApp/cadenceWhatsappStageSend.ts:1-14, 11, 576-597; credentialResolver.ts:1-15
  • packages/services/src/email/emailTrackingInstrumentation.ts:10 — tracking origin
  • packages/workflows/src/runner/cadenceStepFailedScheduling.ts:20-34 — next-stage time
  • packages/db/src/schema/contactPreferences.ts:93-99; apps/web/src/features/settings/ContactPreferencesSettingsEditor.tsx:103-145 — kill switch
  • Quiet hours: packages/workflows/src/runner/cadenceSafeguardHook.ts:512-542; packages/workflows/src/machines/shared/guards.ts:87-119
  • packages/workflows/src/clients/lingua/cadences/outboundCadence.ts:34-68, 42, 51 (commit 9a2f9372f); revivalCadence.ts:46-97; packages/workflows/src/clients/stayClub/cadences/outboundCadences.ts:51-276

miCampus Google Ads WhatsApp cadence custom: miCampus

A three-touch WhatsApp follow-up for new Google Ads leads that have not picked a residence. miCampus uses Salesforce. It is live: the epic records "production dry run reviewed; live promotion approved" and the selector returns a live cadence handoff. The dry-run observation machine is still registered but no selector routes to it.

Eligibility (all must hold)

A Salesforce pull sync produces CRM_RECORD_RECEIVED, on_crm_sync runs, then the miCampus post-workflow selector checks:

  • Salesforce Lead CreatedDate within 10 minutes of the event;
  • targetWasCreated (only newly created targets enrol);
  • CRM profile is a Salesforce Lead;
  • LeadSource === 'Google AdWords' in both the target field and the persisted Salesforce section;
  • unknown residence: Available_Residence_SEL__c missing, null, or No lo tengo claro. An explicit empty string fails closed;
  • a valid phone;
  • no prior communication: no conversation with a transcript, including the shared WhatsApp thread with the pinned sender.

Shape

  • Locale. +34 → es, +351 → pt_PT, else en, as three registered cadence IDs.
  • Stages. micampus_new_lead_{1,2,3}_<locale> at 0 s, +24 h, and +48 h after stage 2. Every stage pins the WABA and sender number and requires an APPROVED template. stopOnAnyReply: true.
  • Pre-send guard. Before every stage it re-checks Salesforce Lead + unknown residence; before stage 0 it also checks the Google AdWords source. Failure completes the cadence with a client-guard violation.
  • Attribution. After stage-1 provider acceptance the local leadSource becomes [Zube] Outbound WhatsApp. The miCampus syncback pre-hook writes that value to Salesforce LeadSource for Lead targets.
  • Stop it with the account outboundCadenceEnabled switch, or a code change. Historical backfill is a non-goal.
Epic drift. The code has no first-name check and only enrols newly created targets (planning doc says first name required, plus a "late first-name update" path — stale). The code writes LeadSource back to Salesforce (planning doc contradicts itself on this — stale at :49).
Evidence
  • planning_docs/micampus-google-ads-whatsapp-cadence/epic.md:8 live promotion; :29-30 backfill non-goal; :49 vs :163 LeadSource contradiction; :61-67, 97-100 first-name text
  • packages/workflows/src/clients/micampus/postWorkflowHandoffs.ts:44-56, 67-102, 104-136, 123 — selector (commits eafcec666 dry run, 71183fc35 launch, 13fbd5c43 first name removed)
  • packages/workflows/src/clients/micampus/outboundEligibility.ts:3-6, 34-71 — source, residence, 10-minute window
  • packages/workflows/src/clients/micampus/cadences/outboundCadence.ts:10-27, 36-68, 43, 45, 77, 91-99 — locales, stages, attribution
  • packages/workflows/src/clients/micampus/cadences/outboundPreSendGuard.ts:17-57 — guard
  • packages/workflows/src/clients/micampus/index.ts:49-63 — Salesforce LeadSource write (commit 49891b8b7)
  • packages/workflows/src/clients/registerClients.ts:184; micampus/cadences/outboundDryRunCadence.ts:35-78 — dry-run machine still registered

Addison Lee outbound: UC1 and UC2

Both are Addison Lee client code (see per-client code). UC1 is sales-inbound lookalike prospecting. UC2 is the media-production cold outbound campaign (ADDISON_LEE_UC2_CAMPAIGN_ID).

UC1: draft-only prospecting custom: Addison Lee

  1. Trigger. An inbound email reaches Addison Lee's shared sales inbox through the email poller. The Addison pre-hook runs only for mail to that inbox, consumes non-email triggers so Zube never replies from that inbox, and guards against redelivered messages.
  2. Pipeline. Classify the enquiry → research the sender's organisation → find lookalike companies and filter for fit → find decision-makers and enrich contacts → draft outreach emails. It uses the injected LLM client on a "UK residency route".
  3. Enrichment. Lusha V3 (lookalikes, decision makers, email reveals) via packages/external-connectors/prospecting; ZoomInfo via the client-custom connector.
  4. Output. Per selected organisation, a mailbox review-digest draft plus one target and conversation per decision-maker, with the draft held at deliveryStatus: 'drafting'. The code states that nothing is ever sent; a human reviews and sends.

UC2: cold outbound campaign custom: Addison Lee removal scheduled

Temporary code. All UC2 code carries TODO(delete-addison-lee-uc2-one-off) and is due for deletion in late Nov 2026. Do not refactor it. Read it as a worked example of the platform's outbound safety patterns, not as a product feature.

The 30-second addisonLeeOutboundTickJob is registered and runs the real outbound executor (planning doc says the tick is "a disabled shell" — stale). Commits such as "activate Freshsales LinkedIn tasks" and "Fix UC2 queue jam" show production use.

Safety patternHow UC2 does it
Cohort isolationReviewed CSV imported as pending targets under the dedicated campaign workflow ID; campaign state in versioned additionalInformation; no schema change. Claim protocol in precomputedOutboundCampaignProtocol.
Hard caps1,000 emails/day; 250 new admissions/day; at most 3 emails and 25 actions claimed per tick
Send windowEurope/London, pacing floor(N × elapsed fraction of 09:00–17:00); bounded bursts; nothing starts at or after 17:00
CalendarStages on UK workdays 1, 3, 5, 9, 12, 14; hard-coded UK bank-holiday calendar
SequenceDay 1 email · Day 3 LinkedIn connect · Day 5 email · Day 9 LinkedIn message · Day 12 email · Day 14 email. Follow-ups take priority over new admissions.
Human-in-the-loop channelLinkedIn is manual: Zube creates Freshsales tasks for the rep. Day 3 picks clickers, then openers, max 40, no unengaged fill. Freshsales unavailable → urgent system_issue audit.
Exact sender or stopDedicated Microsoft mailbox via the Microsoft email wrapper; tick returns needs_attention if that exact integration is unavailable
Receipt-only stopsAny inbound prospect email, including out-of-office, terminally stops the target; so do unsubscribe, complaint and hard bounce. Per owner notes, not verifiable from the repo: opens and clicks never change which emails are sent; only a reply or a rep take-over stops emails.
PrecedenceA UC1 match pauses UC2 first
Kill switchOrg outboundCadenceEnabled read on every tick

Epic limitations: no automated LinkedIn sending or monitoring, no OOO resume, no nurture transition, not a reusable product.

Evidence
  • packages/workflows/src/clients/addisonLee/registerClient.ts:291-330 UC1 pre-hook; :502-516 UC1 precedence
  • packages/workflows/src/clients/addisonLee/pipeline.ts:1-11; draftPersistence.ts:1-20, 78, 293-294
  • packages/external-connectors/prospecting/src/lusha.ts:1-13, 51; src/index.ts:1-21; packages/external-connectors/client-custom/src/addisonLee/zoominfo.ts:18
  • packages/services/src/scheduler/jobs/clientOutboundTick.ts:5-22; packages/services/src/scheduler/registry.ts:54-55
  • apps/scheduler/src/tasks/addisonUc2CoreComposition.ts:234-249, 237-238, 239-247, 255-263, 264-275 — executor, kill switch, mailbox, Freshsales audit
  • apps/scheduler/src/tasks/addisonUc2FreshsalesRunner.ts:1-4, 21-45; packages/services/src/runtime/schedulerWiringTypes.ts:361, 377 deletion markers (commit 90faee3da); commits 520415143, 4ff95de5d
  • packages/workflows/src/clients/addisonLee/outboundCampaignPolicy.ts:5-17, 25; outboundCampaignSchedule.ts:23, 51, 800-846
  • packages/repositories/src/precomputedOutboundCampaignProtocol.ts:1-3, precomputedOutboundCampaignRepository.ts
  • planning_docs/addison-lee-media-production-outbound/epic.md:8-9, 65-69, 191-198, 248-264, 313-343, 371-429, 431-492

Send-safety hold GA

Losing a DB session cannot undo a provider send that already happened. The execution-safety hold stops a second runner from repeating a send whose outcome is unknown.

  • targets.workflow_state.executionSafety is typed JSONB: executionId, workflowRunId, escalated, and up to 64 attempt receipts, each with provider and accepted messageId.
  • The hold is persisted before the provider transport. A later owner that finds an unresolved hold pauses and escalates before any actor or provider work. Only the healthy original owner clears its own hold. There is no auto-resend; recovery operations never send, alter ownership, unpause or advance state.
  • WhatsApp template sends are wrapped by sendWhatsappWithWorkflowProtection.
  • Client-visible effect. On first escalation a deterministic take-over audit row is written ("A scheduled WhatsApp message may not have been delivered…" or the generic "An automated step… may not have completed…") and routed through the org's escalation rules. The cause is logged as a warn breadcrumb, not a system fault.
  • Limitation. Conservative false-positive holds are possible. Rollback must quiesce workers and preserve unresolved holds.
Evidence
  • planning_docs/db-connection-resilience/adr-execution-safety.md:1-4, 10-31, 35-38
  • packages/db/src/schema/targets.ts:166-205 — JSONB shape
  • packages/repositories/src/workflowExecutionSafety.ts:18-30 — PausedWorkflowHold
  • packages/services/src/whatsappBusinessApp/workflowSend.ts:1-10
  • packages/workflows/src/runner/workflowRunnerAudit.ts:357-410; guidance/engineering-constraints.md:140

Outbound voice: removed calling, planned hold detection

  • No outbound AI phone-call path exists today. The multi-app split Phase 2 deliberately removed all AI outbound calling for legal reasons, together with outbound customer webhooks and /api/v1 (commit 2b5147e32). Inbound voice is in the voice chapter.
  • Outbound voice hold detection planned: no repo planning doc and no code. Everything else here is per owner notes, not verifiable from the repo, so treat it as unverified: research only, aimed at stopping ElevenLabs billing while outbound airline calls sit on hold; a plan exists on the engineering-plans server as art_80618bed, not approved or built; it would need Telnyx-first outbound because today ElevenLabs owns the outbound SIP dialog.

Embedded webchat gated

A website chat widget that behaves like any other Zube text channel: same targets, same on_text_message_received agent machine, same escalation, insights on session end. Built for two unnamed clients, one with no webchat and one with a bespoke widget. Slices 0–6 are done. Each widget is set up in the Integrations UI, and rollout needs per-org setup: a WEBCHAT_SESSION_SECRET, escalation rules, a web_chat/all template and the real-origin allowlist. Transport internals (HTTP routes, WebSocket frames) are in ingress.

StageBehaviour
EmbedOne async <script> with a public widget ID. apps/webchat-widget: vanilla TypeScript + Vite IIFE, shadow-DOM panel, served by GET /webchat/widget.js.
Config + sessionGET /config, POST /session. Config on an integrations row of type web_chat: domain allowlist, brand name/colour, greeting, contact-confirmation copy, template ID, theme, logo, optional continuation. Session token is an HMAC scoped to widget + origin + visitor, valid 15 minutes. Origin allowlisting is mandatory.
Identity (anonymous-first)Server-minted visitor UUID → social handle web_chat::<uuid>. First message resolves or creates an anonymous target named "Web Visitor #xxxxxx".
TurnsWS frame handler parses, rate-limits, enqueues the turn (run on the worker), acks; turnDelivery pushes the persisted outcome. The real text machine runs with the batching park skipped. Keepalive 10 s. Limits: 10 messages/min per session, 30 per IP. Each turn sets idleAt = now + 15 min.
Contact captureNon-intrusive banner/form after 3 visitor messages, and prominently on escalation. A contact_submitted frame resolves the contact; if it matches another existing target the conversation is repointed, with no merge primitive.
EscalationNo longer waits for contact capture (planning doc says escalation is contact-gated — stale). Per owner notes, not verifiable from the repo: a target in help_needed no longer silences web_chat; the incident write-up is in the help-needed continuity plan.
Session endwebchatIdleFinalizeJob every minute. ≥2 substantive visitor messages, or captured contact → on_conversation_complete (insights, sentiment, reminders); otherwise cheap-closed. Explicit close sets idleAt = now + 60 s.
ReconnectGET /transcript replays history after navigation or a dropped socket

Non-goals: live-agent inbox or human override, authenticated visitors, file uploads, office-hours routing, multilingual widget copy. WebSockets need sticky sessions or a backplane before multi-VM scale-out.

Evidence
  • planning_docs/embedded-webchat/epic.md:15-27 slices; :37-39 rollout; :109-115 clients; :152-169 non-goals; :444-458, 475-516, 548, 563-580
  • apps/web/src/ui/new/integrations/channels/NewWebchatChannelPage.tsx:151-217 — widget setup
  • apps/webchat-widget/src/main.ts, ui.ts, transport.ts; apps/webhooks/src/webchat/router.ts:350, 385, 444, 530
  • packages/db/src/schema/integrations.ts:419-436, 472-490 — config and defaults
  • apps/webhooks/src/webchat/sessionToken.ts:43; rateLimit.ts:44-48; turnDelivery.ts:22; frameHandler.ts:1-24, 503, 628-633
  • packages/db/src/schema/targets.ts:88-94 — web_chat:: handle
  • apps/worker/src/webchat/turnProcessor.ts
  • planning_docs/webchat-channel-handoff/epic.md:16 — escalation change; planning_docs/embedded-webchat/help-needed-continuity-plan.md:22-30
  • packages/services/src/scheduler/jobs/webchatIdleFinalize.ts:16-25, 188-191

Webchat continuation gated

Lets a visitor carry a webchat conversation to WhatsApp or email; Zube correlates the next message automatically. Phone is display-only. All original slices are complete, but configuration is disabled by default per widget, and live-provider checks plus internal/client widget enablement remain deployment prerequisites. The toggle and channel choices are on the webchat channel page.

  1. Eligibility, server-side: after 3 visitor messages, or immediately when the run sets webchatPendingEscalation.
  2. Summary. After the agent reply is persisted and pushed, Zube generates a 1–2 sentence first-person summary of the current webchat only (generateObject, tier gpt.fast with minimal reasoning, max 600 chars; the planning doc says gemini.fast, which is stale), then pushes a continuation_options frame.
  3. Bearer code. Random 6-character [A-Z0-9] code with a uniqueness check, 24 h expiry for new claims, destination scoping, one-shot claim and idempotent replay. Stored in the webchat conversation's JSONB continuation object; no new table.
  4. Deep links. A WhatsApp prefilled message [Zube Summary]: … [Zube handoff code: CODE], or a mailto: with the same body.
  5. Claim. WhatsApp ingress or the 2-minute email poller finds the exact code line. The claim atomically merges the whole anonymous shell into the canonical sender target before dispatch. The receiving agent gets the stored summary as provenance-labelled context; a pending escalation carries over; first commit wins.
  6. After claim. The source conversation is read-only; "Start new web chat" keeps the visitor identity. Push happens only when the committing process holds the socket; email claims show on the next send or reload.
  7. Abuse control. A rolling risk indicator in the integration JSONB; crossing 0.1% latches automatic claims off and writes an urgent audit.

Deferred gaps: claims from another participant in an existing email thread (ZUBEA-352); target convergence between replay reads (ZUBEA-353).

Evidence
  • planning_docs/webchat-channel-handoff/epic.md:8, 12, 24, 30, 34, 38, 40, 46, 48-52, 61-62, 79, 84, 171-172, 192-297
  • packages/services/src/webchat/continuation.ts; packages/repositories/src/webchatContinuation.ts, webchatContinuationRisk.ts; apps/webhooks/src/webchat/continuationBridge.ts
  • apps/web/src/ui/new/integrations/channels/NewWebchatChannelPage.tsx:582-588 — toggle

WhatsApp

Ingress GA

POST /whatsapp/event durably records the raw payload, enqueues an inbound-event job and returns 200; if both the receipt and the spool fail it returns 500 so Meta redelivers. The worker routes by field: messages, smb_message_echoes, smb_app_state_sync, user_id_update, history. Route mechanics are in ingress.

Coexistence (whatsapp_business_app) GA

  • Meaning. WABA coexistence: a Meta Business App linked to a Page plus a WABA. It does not mean the dropped direct Cloud-API path.
  • Connect. Meta OAuth callback in apps/webhooks. On success: audit row, subscribeApp per new WABA, and app-state sync (contact book) plus history sync per new phone number, through POST /{phoneNumberId}/smb_app_data.
  • SMB echoes. A message a human sends from the WhatsApp Business phone app is appended as an OVERRIDE transcript entry and moves the target to override: a human took over.
  • App-state sync. Contact-book deltas create or update targets and backfill empty names.
  • Services. Template sync from Meta (category dropped on purpose); a post-voice-call template follow-up actor (voice-only); a send-failure classifier; per-target wrapper factories.

BSUID / username GA

Meta may omit phone numbers for users who adopt usernames and send a Business-Scoped User ID instead. Zube treats BSUID as a first-class WhatsApp identity: handle whatsapp::<bsuid>, scoped to the org; phone stays canonical when known. The social account holds {bsuid, username, parentBsuid, lastSeenPhone}; user_id_update has its own handler; outbound payloads distinguish to and recipient; manual replies fall back to targetBsuid; the operator UI shows @username and the BSUID.

Limitation. Initial template and cadence sends stay phone-only, and there are no authentication templates. A cadence stage skips targets without a phone.

Edit safety GA

An edited WhatsApp message may trigger a reply only when it recovers a missing, recent, unanswered student text on an ongoing target; every other edit is transcript-only. This followed an incident where an unreconstructible history edit produced 53 failed receipts. The admission policy is fail-closed with a 2-hour window and an explicit denial-reason enum. (Planning doc says implementation uncommitted — stale; commit 37362a8a9.)

Multilingual templates GA

Stored templates have an optional translations map keyed by language variant, and stage language resolution considers languageCodeByPhoneCountry. Lingua uses it. Per owner notes, not verifiable from the repo: the es/pt_BR translations were submitted to Meta on 2026-10-22; do not press "Sync templates" for Lingua until that commit is deployed; a missing translation retries once in English.

Evidence
  • apps/webhooks/src/inbound/whatsapp/dispatch.ts:2-19; apps/worker/src/inbound/whatsapp/receiptProcessor.ts:11-14, 214-243
  • packages/external-connectors/meta/src/base/types.ts:3-16 — coexistence meaning
  • apps/webhooks/src/whatsappBusinessApp/router.ts:164, 356-427; packages/external-connectors/meta/src/whatsappBusinessAppAdmin.ts:388-425
  • apps/worker/src/inbound/whatsapp/events/smbEcho.ts:1-12; appStateSync.ts:1-12
  • packages/services/src/whatsappBusinessApp/templateSync.ts:1-16, whatsappTemplateSendActor.ts:1-14, sendFailureClassifier.ts:232, cadenceWhatsappWrapperFactory.ts:1-15
  • planning_docs/whatsapp-bsuid-username-migration/epic.md:3-9, 21-28, 74-102; apps/worker/src/inbound/whatsapp/shared/whatsappIdentity.ts:22-30; packages/db/src/schema/targets.ts:80-86; apps/worker/src/inbound/whatsapp/events/userIdUpdate.ts:1-30; packages/external-connectors/meta/src/whatsappBusinessApp.ts:128-133; packages/services/src/conversations/manualReplyDispatch.ts:169-191; apps/web/src/features/contacts/detail/useConversationController.ts:122-129
  • planning_docs/whatsapp-edit-safety/epic.md:9, 13-17, 31; apps/worker/src/inbound/whatsapp/events/messages/editReplyPolicy.ts:1-60; packages/repositories/src/conversations/messageEdit.ts; threadEdits.ts; internal/editMediaPersistence.ts
  • packages/services/src/whatsappBusinessApp/contracts.ts:40-43; cadenceWhatsappStageSend.ts:92, 259-277

Messenger and Instagram GA

  • Facebook Login OAuth connect with signed state, Page and IG upserts, permission patches (packages/services/src/metaMessaging).
  • History sync through Graph /conversations pulls, driven by the historySyncResumer scheduler job.
  • Per-key async spacing plus a usage-percent backoff rate limiter.
  • Inbound processing in apps/worker/src/inbound/{messenger,instagram}; transport in packages/external-connectors/meta/src/{messenger,instagram}.ts.
Evidence
  • packages/services/src/metaMessaging/index.ts:1-38; historySyncBody.ts:1-10; rateLimiter.ts:1-4
  • packages/services/src/scheduler/registry.ts:44-49, 67

Ad-click attribution GA

  • targets.attribution (JSONB, migration 0097) is the source of truth for ad attribution: { first, last } ad clicks. There was no backfill.
  • WhatsApp click-to-chat referrals and Instagram click-to-Direct referrals (source: ADS) merge into it before dispatch. Messenger merges ADS referrals from inbound messages, Get Started postbacks and standalone messaging_referrals events; a standalone referral only updates an existing target and never dispatches a workflow.
  • A duplicate-target merge keeps the earliest first and the latest last click. The agentic planner sees the attribution in the contact profile.
  • Pages connected before this shipped lack the messaging_referrals subscription. scripts/integrations/resubscribeMessengerPageWebhooks.ts inspects them read-only by default and subscribes only with --apply.
Evidence
  • packages/db/drizzle/0097_certain_raza.sql: ALTER TABLE "targets" ADD COLUMN "attribution" jsonb
  • commits aa92fb9f2 (WhatsApp + Instagram), 7e60efb17 (Messenger + planner profile), d7a6743a8 (re-subscribe one-off), f4cd503ab (keep dispatching when the target vanishes mid-merge)

Calendars and booking

Calendar integrations and agent tools GA

  • Providers: only Calendly and Microsoft (Outlook/Graph). Google Calendar is an explicit non-goal.
  • Agentic tools: calendar_get_availabilities, calendar_create_booking, calendar_get_booking_link. Executors share CalendarToolService with the ElevenLabs voice tools (calendarListSlots, calendarCreateBooking in apps/telephony-infra).
  • Concurrency: a short cross-process lease, calendar_booking_slot_locks, serialises capacity checks.
  • Client-specific: miCampus does not use magic links. Its get_booking_link and send_booking_link_via_whatsapp tools return hard-coded per-residence URLs.

Magic booking link GA

  1. The agent calls calendar_get_booking_link, a "7-day booking link" write tool.
  2. The executor resolves the calendar context, refuses events with custom required questions, reuses an active link for the same target when the strategy hash matches, and otherwise issues a new calendar_booking row in magic_links.
  3. URL: <webPublicUrl>/magic/book-meeting?token=….
  4. The lead opens the public BookMeeting page, which calls public procedures validateBookingLink, listBookingSlots, bookMeeting.
  5. Completion goes through the same calendar provider wrappers.

Shaping decisions: hard-coded 7-day TTL; email required, phone optional unless flagged; invalid, expired and used links show generic copy; visitor-entered PII is not written to the target identity. Metadata provider is calendly | microsoftCalendar. (Planning doc says "draft discovery" with no public router or page — stale; commit 8aee7e650.)

Calendar booking truth planned

Approved plan to replace the sticky targets.callBooked / bookedCallDetails with durable appointments: calendar_appointments, provider refs and an operation ledger, plus voice_runtime_sessions correlation. Implementation is tracked in two Plane tasks. None of those tables exist; only calendar_booking_slot_locks does.

Evidence
  • packages/external-connectors/calendars/src/types.ts:3-6; planning_docs/calendar-booking-truth/epic.md:10, 15-21, 66, 312-368
  • packages/llm/src/agentic/builtInToolCatalog.ts:153-166; packages/workflows/src/defaults/calendarToolExecutors.ts:1-15, 381-470
  • apps/telephony-infra/src/inbound/elevenlabs/toolCalls/calendarListSlots.ts, calendarCreateBooking.ts
  • packages/db/src/schema/calendarBookingSlotLocks.ts:5-25
  • packages/client-tools/src/clients/micampus/customTools.ts:255-300
  • packages/llm/src/tools/calendarBookingLink.ts:28-41; packages/services/src/magicLinks/index.ts:127-134; apps/web/src/pages/magic/BookMeeting.tsx; apps/api/src/trpc/magicLinks/index.ts:522-600; packages/db/src/schema/magicLinks.ts:43-57
  • planning_docs/magic-booking-link/epic.md:8, 15-33, 109

Link domain and short links dormant

The approved plan makes https://link.zube.ai the public link domain (hard-coded, no env var), extends magic_links with redirect and setup-account types, adds one magic_links_daily_metrics table, and gives admins configurable redirect slugs with 7- and 30-day clicks.

BuiltNot found
  • redirect / setup-account enum and metadata; daily metrics table
  • issueRedirectMagicLink, resolveRedirectMagicLink
  • Public magicLinks.resolveRedirect; click counter upsert
  • Web host handling for link.zube.ai/<slug> and /magic/book-meeting; API CORS allows link.zube.ai
  • Email tracking uses link.zube.ai/e
  • No caller of issueRedirectMagicLink outside the service: no admin UI or route creates redirects
  • No setup-account flow code (schema and migration only)
  • The required TODO(link-domain-migration) marker is absent
Evidence
  • planning_docs/link-domain-short-links/epic.md:5, 7, 9-20, 24-50
  • packages/db/src/schema/magicLinks.ts:25, 87-110, 145-168; packages/services/src/magicLinks/index.ts:218-242, 362-395
  • apps/api/src/trpc/magicLinks/index.ts:500-530; packages/repositories/src/surfaces/magicLinks.ts:90-103
  • apps/web/src/routes/publicLinkHost.ts:1-40; apps/api/src/app.ts:70

Public voice demos and notes generator admin-only

A global, Zube-owned registry of sales demo pages, replacing the hard-coded miCampus and LBF Travel demo branches; old URLs stay stable. (Planning doc status "Proposed" — stale; schema, admin and public routers exist.)

  • Data model. public_voice_demos (status draft | published | archived; per-minute and per-day start limits, default 500/day), public_voice_demo_modes (key, title, position, provider elevenlabs | retell, agent ID, language override), public_voice_demo_sessions (attempt ID, lifecycle token hash, mint and browser state, reported duration), public_voice_demo_views. Deliberately no org or target relation.
  • Public flow. /demo/$demoSlug → public demo.getBySlug, recordView, startVoiceSession, reportSessionState. Session creation is provider-neutral, with reservation, rate-limit and unavailable errors. Retell transport in retellWrapper.ts.
  • Admin. /admin/demos; every procedure is trueAdminProcedure: list, get, create, update, archive, generate, Retell credential get/set/clear, getUsage.
  • Retention. Raw identity-free usage receipts kept 13 months.
  • Notes generator. An admin pastes company notes; admin.demos.generate returns draft page copy plus a transient voice-agent system prompt that is never persisted. Generation writes nothing. Model config: tier gpt.ultra, fallback: [] (planning doc pins gpt-5.6-sol high reasoning — stale; how gpt.ultra maps today is unverified).
  • Non-goals: creating provider agents, customer-owned pages, recordings, transcripts, CRM targets.
Evidence
  • packages/db/src/schema/publicVoiceDemos.ts:22-188
  • apps/web/src/routes/router.ts:184, 832; apps/api/src/trpc/demo/index.ts:99-148; apps/api/src/trpc/admin/publicVoiceDemos.ts:219-415, 331-358
  • packages/services/src/demoVoice/publicDemoVoiceSession.ts; packages/external-connectors/voice/src/retellWrapper.ts
  • packages/services/src/scheduler/jobs/publicVoiceDemoUsageRetention.ts:5-30; packages/llm/src/prompts/demo/demoDraft.ts:3-6

Telephony: imported calls, NICE CXone, transfer

Vodafone call import GA

Built for miCampus: ingests calls taken on a Vodafone OneNet-recorded seat outside Zube so they appear as voice conversations.

  1. Manual Uploads → "Import call audio": upload a zip of .wav + _metadata.json pairs to private GCS via signed URLs (manualImport.callImport.mintUploadUrl, submit, getProgress), gated by the leads.update ACL.
  2. The Vodafone adapter maps direction, external party and our line. recordingParty is the ground-truth seat; endTime is ignored.
  3. Mono STT with diarisation via ElevenLabs Scribe.
  4. A gpt.smart (low effort) pass decides which speaker is the org's rep.
  5. A completed voice conversation is upserted with callProvider: 'manual_import'.

Backfill only. It does not dispatch CALL_ENDED or CONVERSATION_COMPLETE_TRIGGERED, never overwrites existing targets, and creates placeholders only when no phone matches. Low attribution confidence writes a review audit. Vodafone is the only recorder format. (Planning pitch says run the post-call workflow and flip to override — stale.)

NICE CXone partial

  • Built: read-only connector (access-key token exchange, tenant discovery, Reporting API completed-contacts, KMS-encrypted secret, reactive re-exchange on 401), health check and recent routing options; tRPC integrations.niceCxone.{get, listRoutingOptions, connect, testConnection, updateSettings, disconnect}; settings for skill and team IDs, direction, minDurationSecs, createPlaceholderTargets: false, dispatchSideEffects: false; a UI card.
  • Not built: no scheduler or worker job syncs CXone calls or recordings.
  • Per owner notes, not verifiable from the repo: this is the connect path for Addison Lee's tenant; call sync waits on the Media Playback SKU and worker phase 2; the Reporting API phone filters are fromAddr/toAddr.

Human transfer (Telnyx + ElevenLabs) GA

  • Tools. ElevenLabs calls POST /voice-tools/telnyx/transfer_to_human and check_transfer_availability; in mode="auto" the latter transfers immediately when exactly one route is active.
  • Routing. Forwarding schedules resolve per day and timezone; destinations are matched by an LLM on tier fast, falling back to the fallback route.
  • Dialling. Leave the conference, bridge the AI leg back, dial destinations in order with retries. On exhaustion, play no-consent audio or route the caller back to the AI.
  • Outcome: completed | failed | not_attempted. Per owner notes, not verifiable from the repo: outcomes were later reclassified into 5 buckets, but that production backfill was not applied.

Call-flow context is in the voice chapter.

Evidence
  • planning_docs/vodafone-call-import/pitch.md:3-20; apps/web/src/ui/new/integrations/manualUpload/NewCallAudioImportTab.tsx:30; apps/api/src/trpc/manual-import/callImport.ts:74-211
  • packages/services/src/manualImport/callImport/vodafoneAdapter.ts:1-20; packages/llm/src/transcription/monoDiarizeClient.ts; packages/llm/src/prompts/voice/speakerAttribution.ts; packages/services/src/manualImport/callImport/importCall.ts:1-22 (commit 77a9bb336)
  • packages/external-connectors/contact-center/src/niceCxone.ts:1-32, 333-400; apps/api/src/trpc/integrations/niceCxone.ts:273-372; packages/webapp-contracts/src/integrations/niceCxone.ts:21-39; apps/web/src/ui/new/integrations/channels/NewNiceCxonePanel.tsx
  • apps/telephony-infra/src/inbound/telnyx/toolCalls/transferToHuman.ts:1-14, checkTransferAvailability.ts:1-14; internal/forwardingSchedule.ts:1-12, transferDestinations.ts:1-12, transferSequence.ts:1-14, noConsent.ts, ambientConference.ts:1-12, resolveTransferOutcomeFromState.ts:1-12

Prospecting connectors and 21 Degrees

  • packages/external-connectors/prospecting custom: Addison Lee: only the Lusha V3 wrapper (company lookalikes, decision makers, email reveals). Its only consumer is UC1. ZoomInfo is client-custom.
  • 21 Degrees planned: "internal alignment draft… No implementation started". Pilot targeted Sep 2026, full scope Jan 2027. Customer is a PE-backed trades/renewables group. Positioning: Zube as the communication and data-normalisation layer above their CRM/FSM, customer-facing only. Planned core work: a custom_client_polls scheduler action, CRM syncback pre/post hooks, sub-organisations post-pilot. No code references found.
Evidence
  • packages/external-connectors/prospecting/src/lusha.ts:1-13, 51; src/index.ts:1-21; packages/external-connectors/client-custom/src/addisonLee/zoominfo.ts:18
  • planning_docs/21-degrees/positioning.md:3-4, 9-21, 54-60

Localisation

  • Per-user en-US / en-GB UI locale GA: supportedUiLocales = ['en-US','en-GB'], a users.locale enum with a default, en-GB messages derived from en-US at module init. Per owner notes, not verifiable from the repo: deployed 2026-10-15; 9 UK/EU orgs set to en-GB; new users inherit the creator's locale; classic-UI copy stays US spelling.
  • Org/user language settings with Spanish UI planned: draft, planning-only. Org base language plus user override in en/es, and localised insights, audit and escalation emails. The only locales in code are en-US and en-GB.
  • Lead-facing language is per template and contact language: see multilingual WhatsApp templates and miCampus cadence locales above.
Evidence
  • packages/webapp-contracts/src/locale/index.ts:5; packages/db/src/schema/users.ts:125, 160; apps/web/src/i18n/resources.ts:51; apps/web/src/i18n/britishEnglish.ts
  • planning_docs/language-settings-localization/epic.md:8, 13, 15-18

CRM integrations

Providers: hubspot, monday, salesforce, freshsales, dynamics. Jobs: crmSyncer every 3 min, crmSyncbacker every 3 min offset by 2. The connector tables are in the data chapter.

AreaStatusWhat to know
Microsoft Dynamics 365 / DataversegatedServer-to-server application user auth via Zube's multi-tenant Entra app (no Dynamics seat). Admin picks one Dataverse table (Opportunity, Lead, Contact or custom); never silently defaults to Lead. OIDC + PKCE, callback /callbacks/microsoft-dynamics; WhoAmI proof, admin consent only when needed; one Dataverse org healthy-connected to at most one Zube org; MSAL client-credentials tokens never persisted; modifiedon polling, identity search, typed writes, owner listing, Task/Annotation, Merge only for account, contact, lead, incident. Live connect proof and customer-sandbox proof still listed; no evidence they were completed.
FreshsalesGA read-onlyInbound contact sync, outcome-read conversion, escalation tasks. Sync-back is structurally impossible (guard in the syncback orchestrator). Connect with API key + domain; 6 h pull backoff; rate-limit defaults 500/min and 5000/h. Addison Lee credentials moved to an org-level freshsales row with no mappings on 2026-09-30; UC2 LinkedIn tasks use it. No Deals object sync; contact reads only include attached deal summaries.
CRM identity convergence (ADR-021)GAAuto-merge targets only when they carry the same exact CRM source reference; never infer from phone or email. Loser must be quiet ≥6 h with no live or scheduled conversation, reminder, workflow, outbox or CRM lease; locks in deterministic order. Motivated by 27 duplicate pairs at MiCampus. resolveAndConvergeByCrmReference.
Syncback reliability recoveryGATrust structured links for update-only syncback; keep conflict checks for unlinked records; isolate converted Salesforce Leads; reclaim expired zero-failure claims; replay one target at a time. MiCampus (Salesforce) and Lingua (HubSpot). Production replay state unverified.
MiCampus Salesforce syncback hardeningGACountry-aware phone matching (ES, PT), sync all structured-linked leads, quiet period. Code uses a two-hour quiet period for automatic CRM creates, no age bypass (approval doc says 15 min with a 30 min cap — stale).
Microsoft email auth recoveryGATriggered by an Addison Lee incident: the runtime captured the integration row at boot, then auth-errored after a Graph 401. Fix: resolve the integration per run; only a definitive Entra refresh failure (invalid_grant, interaction_required, consent_required, login_required) terminalises to auth_error; configuration errors classified separately; keep reactive 401 → refresh → one retry. Epic says "in review".
Account / org / OAuth provider linkingplannedDraft: split org settings from a per-user account page; let email/password users link Google or Microsoft login onto the same Firebase UID. Code has only GoogleAuthProvider, no Microsoft provider, no linkWith*; /account is still org settings.
Evidence
  • packages/db/src/schema/crmSyncShared.ts:9-15; packages/services/src/scheduler/jobs/crmSyncer.ts:42; crmSyncbacker.ts:46
  • planning_docs/microsoft-dynamics-crm/adr-001-application-user-auth-and-environment-boundary.md:1-30; epic.md:33-44, 46-134, 166-179; packages/external-connectors/crm/src/dynamics*.ts; packages/services/src/crmWorkflows/dynamics/
  • planning_docs/freshsales-crm-integration/epic.md:3, 5-7, 16, 167, 173-175, 185-198; packages/services/src/crmWorkflows/syncBackOrchestrator.ts:45-46; apps/api/src/trpc/integrations/integrationCrmRouter.ts:544; packages/services/src/crmWorkflows/freshsales/syncArm.ts:98; packages/external-connectors/crm/src/freshsales.ts:310-347
  • planning_docs/crm-identity-convergence/adr-021-exact-local-crm-reference-convergence.md:20-30; epic.md:19-21; packages/repositories/src/targets/crmIdentity.ts:383, 615
  • planning_docs/crm-syncback-reliability-recovery/epic.md:10, 59-75; packages/services/src/crmWorkflows/shared/identityReconciliation.ts:543-613
  • planning_docs/micampus-salesforce-syncback-hardening/approval.md:3, 11-30; packages/repositories/src/targets/crmCandidates.ts:28-33, 93-98
  • planning_docs/integration-auth-recovery/epic.md:8, 14, 30-35; packages/external-connectors/email/src/microsoftEmailAuthProtocol.ts:123-140; apps/scheduler/src/tasks/addisonMicrosoftAuthRecovery.integration.test.ts
  • planning_docs/account-organization-oauth-linking/epic.md:8, 13-15; apps/web/src/lib/firebase.ts:9, 116; apps/web/src/routes/router.ts:761-791

Native audio (realtime voice) planned

A draft testing plan, explicitly "not an approved implementation design". It would test OpenAI gpt-realtime-2 and Gemini gemini-3.1-flash-live-preview as a "voice actor" paired with a stronger supervisor model. The Telnyx wrapper has no media streaming yet. No realtime or native-audio code exists in packages, apps or scripts.

Evidence
  • planning_docs/native_audio/mvp_testing_plan.md:3-13, 15-22, 34

Doc/code drift

These planning docs disagree with the code at HEAD. Trust the code; do not hand these docs to an agent as a spec without this table.

DocDoc saysCode at HEAD
micampus-google-ads-whatsapp-cadence/epic.md:61-67, 97-100First-name requirement; late first-name update pathNo first-name check; created targets only (commit 13fbd5c43)
same, :49Zube source not synced back to SalesforceSyncback pre-hook writes [Zube] Outbound WhatsApp (micampus/index.ts:58-63)
addison-lee-media-production-outbound/epic.md:65-69Tick is a disabled shellTick wired and running the real executor
embedded-webchat/epic.md:511-516Escalation gated on contact capture"escalation no longer waits for contact capture" (webchat-channel-handoff/epic.md:16)
whatsapp-edit-safety/epic.md:17Implementation uncommittedIn repo (commit 37362a8a9)
magic-booking-link/epic.md:8, 109Draft; no public router or pageBuilt (commit 8aee7e650)
configurable-public-voice-demos/index.htmlStatus "Proposed"Built: schema, admin router, public router
vodafone-call-import/pitch.md:17-20Run post-call workflow, flip to overrideBackfill only, no workflow dispatch (importCall.ts:16-19)
micampus-salesforce-syncback-hardening/approval.md:1115 min quiet, 30 min cap2 h quiet period, no bypass (crmCandidates.ts:28-33)
public-voice-demo-notes-generator/index.htmlPins gpt-5.6-sol highTier gpt.ultra, no fallback (demoDraft.ts:3-6)
freshsales-crm-integration/epic.md:3Pilot "not Addison Lee"A later section names Addison Lee as pilot (:187)

Platform, admin and operations features: a deep dive

This chapter covers the parts of Zube that are neither channels nor intelligence: identity and access, the Zube admin console, proposals and demos, spend telemetry, production data tooling and the resilience and compliance work around them. The thing to remember: authorisation is a ladder of tRPC procedure tiers keyed off one resolved request actor, and "admin" (whoever the effective actor is) is not the same as "true admin" (the human who logged in).

Read the pills as "merged", not "deployed". The research reads one checkout. It shows what is merged into this branch's history, not what is running in production. Where a planning doc says "awaiting deployment", the production state is unverified.

Summary

FeatureStatusAudienceWhere it runs
Firebase auth and request-actor resolutionGAcustomer, operatorapi (tRPC middleware), web client
Impersonation (x-persona-user-id)admin-onlyoperatorweb client + api
User ACL (groups, permissions, lead and channel scope)GAcustomerapi
Automated lead assignment (round robin / random / LLM)GAcustomerworker inbound paths, email history sync
Reminder acknowledgement / escalation job (ACL slice 10)plannedcustomersettings contract only
Customer user managementGAcustomer org adminsapi
Password setup invitesGAcustomerapi + SES + Firebase
Zube admin console (/admin)admin-onlyoperatorweb + api (trueAdminProcedure)
Organisation feature flagsadmin-onlyoperatorapi
Customer change requests logadmin-onlyoperatorapi + GCS signed URLs
Public voice demos manageradmin-onlyoperatorapi; nightly retention job in scheduler
Magic booking linksGAcustomer's leadsapi public tRPC; issued by agent calendar tool
Redirect short links (link.zube.ai)ops toolcustomer's leadsapi public tRPC + nginx; no in-app issuer found
Client proposals (proposals.zube.ai)gatedprospects, internal staff, engineersapi Express routes, SPA, nginx host block
Inactive-demo-account policyGAinternal staffservices runtime dispatchers, scheduler repositories
Demo data toolchainsops toolengineerslocal scripts, prod-db-write
60-day data retention / purgenot found—not in this checkout
LLM and vendor spend telemetryops toolengineers, internal staffLLM client + scheduler crons → PostHog
Hard spend cap / per-org budgetnot found——
Status page (status.zube.ai)gatedcustomers / publicseparate Compose project on the app VM
External developer API /api/v1removed 2026-09-30——
Custom connector secretsGAcustomer org admins, engineersapi (KMS-encrypted); consumed by client code
Agent preview / Foundry test chat / Generate replyGAcustomer, operatorapi enqueues; worker runs
Manual lead import (CSV/XLSX)GAcustomerbrowser parse, api review/submit, worker
Manual call-audio importinternal MVPinternal staffsynchronously inside the api request
Support manifestops toolengineerspackages/services/src/support
Files (signed downloads)GAcustomerapi + GCS
Home dashboardGAcustomerapi
Production SQL tooling (prod-db-read / prod-db-write)ops toolengineers, agentsdeveloper machine → loopback Cloud SQL proxy
Schema cleanup phase 2 (compatibility release)ops toolengineersmigration 0065; contract drop not done
DB connection resilience / execution-safety holdsgatedengineers, on-calldb pool, workflow runner
Webhook durability (receipts, spool, replay)GAengineers, on-callwebhooks, scheduler, GCS
Workflow envelope invariantstep 1 steps 2–4engineersworkflow runner
Workflow lock contention fixesS0 + mitigations Q1–Q7engineersworkflow runner, CRM sync
CI validation reuseshadow-onlyengineersscripts/checkremote
Vulnerability scanningops toolengineers, compliance ownerGitHub Actions (hosted + self-hosted runner)
Cloud SQL backup monitorgatedengineers, compliance ownerCloud Run job (unprovisioned by default)
Vanta remediationinventorycompliance ownerplanning doc
Multi-app split Phase 1 (five containers)shipped 2026-09-27engineersapp VM Compose
Multi-app split Phase 2 (worker split)mergedengineersapps/worker; deploy state unverified

Identity and access

Firebase Auth is the only authentication control. The web client sends authorization: Bearer <Firebase ID token>. When an admin is impersonating, it also sends x-persona-user-id; the persona id lives in localStorage under zube.personaUserId. The API trims the header and allows it through CORS.

Request-actor resolution (resolveRequestContext)

  1. Verify the token. Missing or invalid → anonymous.
  2. Look up users by Firebase UID. An internal-domain principal with no row is auto-provisioned into AUTH_INTERNAL_ORGANIZATION_ID, and default user groups are ensured.
  3. Still unknown → access_required_unprovisioned, with shouldDeleteFirebaseUser: !isInternalUser (an unprovisioned external Firebase user is flagged for deletion).
  4. Impersonation. A non-admin who sends the header is logged and ignored. An admin whose persona id does not resolve gets impersonation_invalid / persona_not_found. Otherwise the effective user becomes the persona. No isActive check is applied to the persona, consistent with the inactive-demo policy.
  5. Assemble the actor. The effective user's group ACL, organisation, owner flag and demo flag resolve in parallel. While impersonating, actor.isAdmin follows the persona's email domain, not the human's.
Web client Bearer Firebase ID token + x-persona-user-id (only when impersonating) Verify token Firebase Admin missing / invalid → anonymous users lookup by Firebase UID = the logged-in human (true-admin basis) Persona header? non-admin: log, ignore admin + unknown id: impersonation_invalid Actor effective user ACL, org, owner, demo, isAdmin Internal domain, no row auto-provision into internal org Unknown external access_required_unprovisioned persona set: isAdmin follows persona domain tRPC procedure tiers (apps/api/src/trpc/trpc.ts) publicProcedure no actor required (e.g. magic links) protectedProcedure any authenticated, org-scoped actor aclProcedure(permission) owner or admin bypass, else permission path organizationFeatureProcedure ACL + org flag; both skipped for true admin adminProcedure effective actor is internal (persona-faithful) trueAdminProcedure logged-in human is internal; never tenant data Shared request-deadline middleware 30 s default · 285 s named long paths · 585 s research/reply · 60 s reports · 30 min manualImport.*
Token → human (users row or internal auto-provision) → optional persona → effective actor → procedure tier. The highlighted tier is the only one that authorises on the logged-in human (the users-lookup result) rather than the effective actor.

Procedure tiers

TierAuthorises onRuleTypical use
publicProcedurenothingopenmagic-link validation, booking, redirect resolution
protectedProcedureeffective actorauthenticated and org-scopedself-service setMyCrmIdentity / setMyLocale / setMyUiMode
aclProcedure(permission)effective actorowner or admin bypass; else effective permissions must include the path. Denial carries accessReason: missing_permission | permission_setup_incompletemost customer features
organizationFeatureProcedure(permission, featureKey)effective actor + orgACL check plus per-org feature flag; both skipped for true adminsflagged features (see feature flags)
adminProcedureeffective actoreffective actor is internal (persona-faithful)persona-faithful internal checks
trueAdminProcedurelogged-in humanhuman is internal, regardless of persona; never for tenant business dataall /admin server procedures

resolveIsTrueAdmin exists separately for field-level redaction.

Request deadlineApplies to
30 sdefault
285 snamed long-running paths (e.g. admin delete organisation)
585 stemplates.testReply, conversations.generateReply, knowledgeBase.testNexusQuery
60 sreport generation
30 minthe whole manualImport.* namespace
Admin vs true admin. "Admin" and "internal" are deliberately the same set of email domains. The internal-domain default is getzube.com and zube.ai, configurable by env. The guidance text says only "@getzube.com email domain", which understates the code default. While impersonating a customer persona, adminProcedure and owner/admin ACL bypass follow the persona, so you see what the customer sees. trueAdminProcedure keeps the admin console working.
Evidence
  • apps/web/src/lib/Trpc.tsx:185-205 — bearer token and persona header
  • apps/web/src/lib/persona.ts:1-43 — zube.personaUserId storage
  • apps/api/src/middleware/auth.ts:3-8; apps/api/src/app.ts:194 — header read, CORS allow
  • packages/services/src/auth/bootstrap.ts:193-440 — resolveRequestContext (verify :206-240, auto-provision :242-333, unprovisioned :335-355, impersonation :360-400, actor :403-418)
  • apps/api/src/trpc/trpc.ts:84-159 — deadlines; :230, :232-239, :284-425 — tiers
  • packages/config/src/env.ts:10, :212-216; packages/auth/src/policy.ts:84-88; guidance/engineering-constraints.md:109-111

User ACL

Per-organisation role-based access for customer users. Permissions are a fixed tree; groups bundle them; direct per-user permissions are additive on top of the group (assertDirectPermissionsAreAdditive). Ownership is organizations.owner_user_id. The legacy users.role column was migrated into groups and dropped.

FamilyPermissions
leadsview, viewUnassigned, update, delete, own, manageUnowned, manuallyAssign
conversationsview, reply
remindersAndAuditTrailsview, update, acknowledge
nexusview, update
insightsview
foundryviewClientConfig, updateClientConfig
integrationsmanageOwn, manageAll
organizationSettingsview, manage
Default group
Admin
full permissions
Default group
Lead Manager
leads, conversations, reminders
Default group
Insights Viewer
insights only

Record-level lead access

Owner and internal admin bypass. Everyone else needs both an owner scope (assigned only / plus unassigned / all) and a channel scope. Channel ACL is leadChannelScope: {mode:'all'} or {mode:'selected', endpoints} with at most 100 endpoints, stored on user_groups and users. It is matched against the materialised targets.target_channel_refs: a user sees a target if it has at least one matching channel endpoint. The unlock is target-level; there is no per-field redaction.

Assignment

  • Manual: the lead-assignment service with strategy: 'manual'.
  • Automated: autoAssignCreatedLead runs only for newly created, unassigned targets. Strategies: round_robin (durable cursor in accessControlSettings), random, and llm with an optional fallback user and an explicit "did not auto-assign" audit text. Called from inbound WhatsApp and Instagram identity paths, email history sync and manual import.
  • Not built: ACL slice 10 (reminder acknowledgement flows, escalation job, notification preferences). The settings contract has primaryToGroupAfterHours / groupToAllUsersAfterHours, but no job reads them.

(The ACL status doc says slice 9 assignment automation is "Not started" — stale. It also carries historical "branch user-acl-work, not on main" handoff text; milestone 1 is on main history.)

Evidence
  • packages/webapp-contracts/src/userAcl/index.ts:89-145 — permission families; :149-236 — default groups; :19-48 — leadChannelScope
  • packages/services/src/userManagement/index.ts:331-340 — additive direct permissions
  • planning_docs/user_acl/implementation_status.md:20-27, :309-311, :370-376
  • apps/api/src/trpc/leadAccess.ts:14-80 — record-level access
  • packages/db/src/schema/users.ts:98,147; packages/db/src/schema/targets.ts:307
  • packages/services/src/leadAssignment/index.ts:40,144; autoAssignment.ts:282-300,397-398,566,628-776
  • apps/worker/src/inbound/whatsapp/shared/whatsappIdentity.ts:452; apps/worker/src/inbound/instagram/events/assignment.ts:39; packages/services/src/email/historySyncBody.ts:398
  • packages/webapp-contracts/src/settings/index.ts:459-472 — unused escalation-hours settings

Customer user management and password setup

The tRPC user.* router is gated by aclProcedure('organizationSettings.manage'): list users, list channel-scope options, user-group CRUD, create user, send invite, update user, deactivate user. Creating a user creates the Firebase account with emailVerified: true, then the row through users.createWithAudit. Deactivate sets isActive: false, which gates nothing (see the demo policy below), and self or owner deactivation is permitted. Setting your CRM identity writes an audit row.

Password setup invites. sendPasswordSetupInvite generates a Firebase password-reset link, extracts its oobCode, rewrites it to ${WEB_PUBLIC_URL}/auth/setup-password?oobCode=… and sends a branded SES email naming the inviter. Customer invites and admin invites both use it.

Evidence
  • apps/api/src/trpc/user/index.ts:235-355, :435-468
  • packages/services/src/userManagement/index.ts:317-367 (create), :458 (invite), :660-700 (CRM identity audit), :758-896 (groups), :946-954 (deactivate)
  • packages/services/src/userSetup/passwordSetupInvite.ts:31-93; apps/web/src/routes/router.ts:142
  • planning_docs/inactive-demo-account-policy/epic.md:49-55

The Zube admin console (/admin)

Routes: /admin, /admin/changes, /admin/feature-flags, /admin/demos, /admin/proposals. Every server procedure is trueAdminProcedure, so the console keeps working while you impersonate.

CapabilityBehaviour
Create client (createClient)Rejects internal-domain emails. Creates the Firebase user (random initial password, emailVerified: true), then in one transaction: organisation, default content-insight configuration, user (isActive: true), the three default groups, owner_user_id, audit row. On failure it deletes the Firebase user. Sends the setup email unless sendSetupEmail === false; returns setupEmailStatus: sent | failed | not_requested.
Impersonation pickerlistImpersonationTargets; the UI sets personaUserId.
Active flagupdateUserActive with an audit row.
Delete organisationRefuses the admin's own current org. Requires typed org name and owner email. Row-locks org, users and files; deletes every GCS object and every Firebase user, then the organisation row in one transaction. Remaining tenant rows presumably go via FK ON DELETE CASCADE (unverified). Deliberately synchronous and serial under the 285 s lane.
Password setup / resetsendPasswordSetupInvite, recordPasswordResetTrigger.
Feature flagsCatalogue below; enforced by organizationFeatureProcedure.
Customer change requests (/admin/changes)Internal log of client-requested configuration changes: list / create / update / complete / reopen / cancel, with signed-URL screenshot upload and preview. Table customer_change_requests.
Demos (/admin/demos)Public voice-demo manager: list/create/update/generate; published slugs are immutable; Retell credential admin; per-demo start-rate limits.
Proposals (/admin/proposals)Read-only list / detail.

Feature-flag catalogue (all default off)

KeyNote
flag: insights_conversion
flag: nexus_taxonomy
flag: lead_lifecycle_stageshadow; enabling requires OPENROUTER_API_KEY
flag: revops_deals

(The feature-flags epic says implementation is "blocked on Plane credentials" — stale; the code exists.)

Evidence
  • apps/web/src/routes/router.ts:814-838 — admin routes
  • apps/api/src/trpc/admin/index.ts:310-899 — procedures (flags :314-394, change requests :395-672, create client :673-745, impersonation :746-752, active :753-800, delete org :801-831, password :832-899)
  • packages/services/src/admin/index.ts:224-405, :515-548, :561-722
  • packages/webapp-contracts/src/admin/index.ts:243-273 — flag catalogue
  • apps/api/src/trpc/admin/publicVoiceDemos.ts:165, :219-343; apps/api/src/demoVoice.ts:1-40
  • packages/db/src/schema/customerChangeRequests.ts; planning_docs/organization-feature-flags/epic.md:8

Magic links

Table magic_links with link_type enum calendar_booking | redirect | setup-account and a status lifecycle.

  • Calendar booking links: 7-day TTL, URL /magic/book-meeting?token=…, issued by the agent's calendar tool executor. Public tRPC validateBookingLink, listBookingSlots, bookMeeting. (Booking-link epic says "draft discovery" — stale.)
  • Redirect short links on https://link.zube.ai/<slug>, with reserved slugs, resolved by public resolveRedirect; host detection in the SPA and an nginx block. No in-app caller of issueRedirectMagicLink exists outside the service, so creation is presumably a data operation (unverified).
  • Other types throw TODO(magic-link-expansion). setup-account is in the enum but the service rejects issuing it.
Evidence
  • packages/db/src/schema/magicLinks.ts:25-28,129-130
  • packages/services/src/magicLinks/index.ts:1-8, :99-134
  • packages/workflows/src/defaults/calendarToolExecutors.ts:455
  • apps/api/src/trpc/magicLinks/index.ts:500-600
  • apps/web/src/routes/publicLinkHost.ts:1; infrastructure/nginx/nginx.conf:29-32

Client proposals (proposals.zube.ai)

A confidential, data-driven proposal microsite at https://proposals.zube.ai/{company-slug}, gated by a 4-digit email code. Content is validated JSONB in Postgres and rendering is application code, so a new proposal is a data insert, not a deploy. It is explicitly not a CMS: no editor, no PostHog tracking, no revision model.

  1. Host split. selectApplicationHost returns 'proposal' for that hostname and lazily imports a proposal-only entry, so the staff router and analytics never load on the public host.
  2. nginx. A dedicated server_name block with its own Let's Encrypt cert proxies /api/proposals/ to api:3001 and everything else to the Firebase-hosted SPA.
  3. Express, not tRPC (cookies and cache headers matter): GET /:slug/session, POST /:slug/code, /verify, /logout, GET /:slug/content, POST /:slug/visits. CORS origin is the proposals host; mutations pass requireOrigin.
  4. Code challenge. randomInt(0, 10_000) zero-padded; 30-minute code lifetime; 24-hour absolute session. Code stored as scrypt$salt$digest and compared with timingSafeEqual; the browser token is stored only as a SHA-256 digest. Email via a dedicated SES template.
  5. Eligibility. Exact getzube.com addresses can open published or unpublished proposals. External addresses need published = true and an exact allowlist match. Every content read and visit write re-authorises.
  6. Data. client_proposals and client_proposal_accesses (migration 0074). Visits are a UUID-keyed JSONB map with server-clamped visibleMs.
  7. Document contract. proposalDocumentSchema is a discriminated union on schemaVersion 1 and 2. v1 blocks: prose, stepper, columns, example, table, scopeExplorer, cta. v2 adds a trusted custom section (html ≤ 131,072 chars, optional css ≤ 32,768) and presentationMode. IDs must be unique document-wide.

Authoring is an operator/engineer procedure. The only validated writer is ProposalsRepository.createProposal; there is no update or publish API. Content goes in through gitignored one-off scripts after a local rehearsal and explicit production-write authorisation. The create-proposal Claude skill runs draft/preview → local rehearsal → production apply (authorisation required) → "engine gap". Its one standing authorisation covers uploading client raster logos to gs://zube-ai-agents-prod-public-assets/client_assets/ at new content-hashed paths: never overwrite or delete, and the upload does not authorise a DB write.

Limits by design. No attempt counters, lockouts or rate limiting on the code challenge; no section-level gating; no revision history (rollback = published = false); no admin editing; no automatic deletion. Plan status: slices 1–2 approved 2026-09-09, slice 3 application/host changes approved; production hostname activation and the pilot rehearsal pending. Whether the hostname is live is unverified.
Evidence
  • planning_docs/client-proposals/implementation-plan.md:5, :11-61, :191-331
  • apps/web/src/applicationHost.ts:3-4; apps/web/src/main.tsx:7-9; apps/web/src/ProposalEntry.tsx:5-17
  • infrastructure/nginx/nginx.conf:102-130; apps/api/src/app.ts:219-221
  • apps/api/src/proposals/router.ts:188,207,242,259,275,299
  • packages/services/src/proposals/index.ts:19-20,91,95-108,146
  • packages/repositories/src/proposals.ts:138,376-379,582,660
  • packages/webapp-contracts/src/proposals/index.ts:270-340
  • apps/api/src/trpc/proposals/index.ts:12,54-64; .claude/skills/create-proposal/SKILL.md:28-98

Demo organisations

Inactive-demo-account policy

Production demo orgs keep every user isActive: false. That flag is now administrative metadata only: it must not block login, assignment, reminders or CRM owner sync. What demo orgs must not do is send real escalation emails or create CRM tasks.

  • Classification: an org is a demo iff it has ≥ 1 user and all users are inactive. Empty orgs are not demos.
  • Suppression at two post-commit boundaries: audit notification dispatch (logs demo_account_escalation_side_effect_suppressed) and escalation CRM-task dispatch. If classification itself fails, the effect is suppressed and logger.error fires. Audit rows and target / help-needed state are still persisted.
  • Bootstrap: actor.isDemoOrganization and demoInsightsReferenceAt go to the web client. Migration 0071 adds organizations.demo_insights_reference_at; Insights pages use it as the virtual "today".
  • Scheduler: organizationHasActiveUser is the single definition of "active organisation", used by reminders, dropoff observations, knowledge-gap taxonomy, the knowledge query queue and the organisation repository. Curation and daily/monthly insight jobs skip inactive orgs.
Sharp edge. Demo-ness is inferred, not a flag. Marking a real customer's only user inactive would classify that org as a demo and silently suppress its escalation emails.

Two demo-data toolchains

ToolchainWhat it isUse it for
Configurable generatorbun run demo:data:generate:configurable (presets Workspace London / Starline Tours) → .tmp/demo-data/; seed with bun run demo:data:seed --bundle …. Bundle schema, reference-date materialisation, deterministic IDs, demo magic links, credentials from env.local datasets. Unsuitable for prospect demos: hardcoded reminders/escalations, companyProfile.workflows: [].
zube-demo-org Claude skill"The real platform (UI 2.0) on a dummy organization." Research prospect → spec → org created in Admin → Create client with "Send setup email" unticked, user set inactive → parallel generator slices under .tmp/demo/<client>/ → local rehearsal → independent review → prod-db-write dry run then commit on exact rowCount (demo pushes are pre-authorised) → verify → hand off with a do-not-click list. Proven generators are gitignored in the primary checkout.prospect-tailored production demo orgs. Apply order: seed → restore owner → daily_metrics → content insights → conversion → Foundry → Nexus → Nexus Review → enrichment.

Production safety rules (learned from incidents)

  • Never seed provider IDs. A fake ElevenLabs id stalled the global elevenLabsCostRollup checkpoint for three days.
  • No ongoing voice calls; no healthy or auth_error integrations (use disabled).
  • No escalation rules with email or crmTask targets; all users inactive; outboundCadenceEnabled: false.
  • The seeder's --use-bundle-organization overwrites settings and owner; never re-seed after extras.
Evidence
  • planning_docs/inactive-demo-account-policy/epic.md:5,11-45,85-88
  • packages/services/src/demoAccountPolicy.ts:9-21; packages/services/src/runtime.ts:647-677; packages/services/src/runtime/runtimeDispatchers.ts:213-241
  • packages/services/src/auth/bootstrap.ts:127-143,403-430; packages/db/drizzle/0071_demo_insights_clock.sql:1-56
  • packages/repositories/src/organizationActiveUser.ts:7-21; guidance/data-operations.md:92
  • package.json:130-131; guidance/demo-account-provisioning.md:1-18; packages/db/src/seedDemoData.ts:13-17
  • .claude/skills/zube-demo-org/SKILL.md:8-39; references/pipeline.md:3-11; references/production-safety.md

60-day data retention: not found

No 60-day retention or purge exists in this checkout. Code, scripts, infrastructure, guidance, planning docs and git history across local branches were searched. There is no policy, purge job, organisation setting or planning doc. Vanta lists "Data auto-deleted when retention period expires" only as an open evidence candidate. If this feature exists it lives on a branch or checkout not visible here: confirm with the owner where any 60-day purge lives before relying on it.

What does exist and looks like retention:

MechanismWhat it deletesCadence
webhookReceiptMonitorwebhook_receipts (raw inbound WhatsApp bodies, contain PII) past a fixed 14-day expires_athourly
publicVoiceDemoUsageRetentionidentity-free public voice-demo session/view receipts older than 13 calendar months, 10k batchesnightly 00:00 UTC, singleton
knowledgeDeletionTickNexus document hard-deletion and expired ingest-session sources, with backoffevery 15 s
Admin delete organisationwhole tenant; manualon demand
HubSpot ADR-019 (CRM Sync V2)governs what is written to HubSpot, not Zube deletion—

Proposals explicitly have no retention policy.

Evidence
  • planning_docs/vanta-remediation/remediation-matrix.md:148
  • packages/services/src/scheduler/jobs/publicVoiceDemoUsageRetention.ts:1-65; registry.ts:28,78
  • packages/services/src/scheduler/jobs/knowledgeDeletionTick.ts:13-16; packages/services/src/knowledge/deletionLifecycle.ts:1-25
  • packages/db/src/schema/webhookReceipts.ts:38-43; webhookReceiptMonitor.ts:201
  • planning_docs/crm-sync-v2/adr-019-hubspot-communication-privacy-retention.md:1-15

LLM and vendor spend tracking

Telemetry only. There is no hard spend cap, per-org budget or automatic throttling on LLM cost; the only "budget" in packages/llm bounds retry attempts, not dollars.

  1. Semantic tiers → physical models. Callers ask for gpt.nano|fast|smart|ultra (and Gemini/Claude tiers). gpt.ultra → gpt-6.1-sol effort high; gpt.smart → gpt-6-luna high; gpt.fast → Luna low; gpt.nano → Luna none. Rates versioned openai-rates@2026-09-29.
  2. Per-call LLM cost events. PostHog $ai_generation with model, provider, tokens, $ai_total_cost_usd, latency, trace id, costRateVersion, optional prompt key/version. Only emitted when the caller supplies telemetry; direct batch paths bypass it. Modelled cost, not invoice truth.
  3. Voice/telephony spend crons (scheduler, singleton, gated on POSTHOG_ENABLED): telnyxCostRollup every 3 h at :15 (one vendor_usage_recorded per billable voice leg, attributed through the phone-line directory); elevenLabsCostRollup every 3 h at :25; elevenLabsRateRefresher weekly Monday 04:00. The ElevenLabs rate is hard-coded at $0.00015/credit because the comped tier has no invoice: "directional, not billing-grade". The DID → org map is in memory, fed by Postgres LISTEN/NOTIFY.
  4. Per-request generation budget (ProviderGenerationBudget) bounds attempts across provider fallback and retries.
  5. Public voice-demo rate limits: startsPerMinuteLimit / startsPerDayLimit.

Planned only: a mandatory telemetry envelope with physical-attempt IDs and daily reconciliation to the OpenAI usage export, a script-based response-quality gate, a controlled MiCampus downshift, and OpenAI Batch for insights.

Evidence
  • packages/llm/src/models.ts:48,94-97,159-190; planning_docs/openai-usage-control/index.html:17-50,70,84-118
  • packages/analytics/src/client.ts:347-370,381-405
  • packages/services/src/scheduler/jobs/telnyxCostRollup.ts:55-66; elevenLabsCostRollup.ts:60-70; elevenLabsRateRefresher.ts:29-34
  • apps/scheduler/src/tasks/postHogSpendWiring.ts:9-31,96-147
  • packages/llm/src/providerRetry.ts:329; packages/llm/src/client.ts:441-454

Status page (status.zube.ai)

One pinned Uptime Kuma 2.5.5 container, motivated by SOC 2, on the existing app VM. It runs as a separate Compose project zube-status (mem_limit: 768m, cpus: 1.0, named volume) so the app deploy's --remove-orphans cannot remove it. No host port, no app .env, no Cloud SQL, no Docker socket. Its own nginx vhost and cert. A daily backup timer briefly stops Kuma for a consistent SQLite/WAL snapshot and uploads to a private GCS prefix.

Monitors are operator configuration, not code: https://app.zube.ai/, https://api.zube.ai/ready, https://webhooks.zube.ai/ready, every 300 s, 90-day history. Incidents are posted by hand (Investigating → Identified → Monitoring → Resolved).

Same VM. A VM or nginx outage takes the status page down too; it is deliberately not an independent outage-communications system. Probes do not prove agent quality, scheduler execution or provider delivery. Remaining operator steps (choose bucket, first admin with MFA, map the domain) are not visible in the repo, so live state is unverified. The README's release tuple api/webhooks/scheduler predates the five-container split.
Evidence
  • planning_docs/status-page-mvp/index.html — banner "IMPLEMENTED — awaiting authorized deployment/bootstrap"
  • infrastructure/scripts/status-page-compose.yml:11-45; infrastructure/status/README.md:5-16,31-111
  • infrastructure/nginx/nginx.conf:82-85; infrastructure/scripts/{bootstrap,backup,restore}-status-page.sh

External developer API (removed) and custom connector secrets

The public /api/v1 surface was removed on 2026-09-30 (commit 88c4096b6): the nine target/conversation routes, /api/docs and OpenAPI generation, API-key auth and credentials, the external-api DTOs (except additionalInformation), integrations.api.getSettings/rotateKey and the Developers API-key card. Every /api/* path now 404s. Rationale: multi-app split Phase 2 removed it first, and the only api integration (Road Scholar) had never created targets through it.

What still carries the "external-api" name:

  • sanitizeAdditionalInformationForExport strips the reserved _internalMetadata key from targets.additional_information before it leaves the system (workflow actor payloads, deferred custom-analysis inputs).
  • apps/webhooks/src/external-api/kms.ts is just a re-export of resolveCredentialCipher.
  • Manual import still dispatches CRM_RECORD_RECEIVED with object_type="external_api", a legacy label, not an HTTP API.

Custom connector secrets survived the removal. An integration row of type: 'custom_secret' holds labelKey, displayName, provider, optional clientKey/callbackPath, and KMS-encrypted credentials. tRPC integrations.api.listCustomSecrets / upsertCustomSecret / deleteCustomSecret, all aclProcedure('integrations.manageOwn'), in the Developers settings UI. Consumers are client-specific code: Addison Lee's ZoomInfo and Lusha connectors look up their row by labelKey.

Evidence
  • commit 88c4096b6 message; planning_docs/multi-app-split/worker-split.md:7,27,49,158
  • packages/services/src/external-api/dto/additionalInformation.ts:1-44; packages/workflows/src/support/defaultMachineActorAdapters.ts:789; packages/services/src/insights/deferredCustomAnalysisInput.ts:95
  • packages/services/src/manualImport/createTarget.ts:6-8
  • packages/db/src/schema/integrations.ts:493-502; apps/api/src/trpc/integrations/integrationCustomSecretsRouter.ts:133,190-263; apps/api/src/trpc/integrations/index.ts:37
  • packages/workflows/src/clients/addisonLee/clientIds.ts:32-37; apps/scheduler/src/tasks/addisonClientRuntimeFactory.ts:180-201

Agent preview: Foundry test chat and "Generate reply"

Runs the production reply generator without sending anything.

  1. The API creates an agent_preview_runs row (kinds template_test_reply, conversation_generate_reply; statuses pending|completed|failed) and enqueues an agent-preview pg-boss job in the same transaction; job id = run id.
  2. Entry points: templates.testReply / getTestReplyStatus (foundry.updateClientConfig) and conversations.generateReply (conversations.reply).
  3. The worker runs buildGenerateAgenticReply in preview mode: the persisting/sending workflow machine is not invoked, client tools are draft-only, calendar_create_booking and booking links are neutered, availability lookups run live.
  4. The web app polls; status mapping never exposes a failed run's stored error.
  5. Queue expiry 300 s; jobQueueHealthMonitor reconciles expired pending runs. API ceiling for these paths is 585 s.

Limits: test chat uses the saved template; voice templates have no test chat. Agentic reply internals are in Intelligence.

Evidence
  • packages/services/src/agentPreview/submitPreview.ts:36-53; packages/db/src/schema/agentPreviewRuns.ts:21-29
  • apps/api/src/trpc/templates/index.ts ~:575-640; apps/api/src/trpc/conversations/index.ts:883-927
  • apps/worker/src/workerProcess.ts:188; apps/worker/src/agentPreview/previewReplyAdapter.ts:1-7; templateTestReply.ts:1-7
  • packages/services/src/agentPreview/previewStatus.ts:8-29; packages/db/src/jobQueue/queueConfig.ts:9-14; jobQueueHealthMonitor.ts:218-230

Manual import

Leads (CSV / XLSX)

  1. The browser parses CSV (hand-rolled RFC-4180-ish parser) or the first XLSX sheet via xlsx; max 5 MB.
  2. reviewBulkImport / reviewSingleContact validate rows and return counts and the workflow id; submitBulkImport / submitSingleContact store a batch and enqueue manual-import; getImportStatus polls. All aclProcedure('leads.update').
  3. The worker processes the batch under a per-batch session advisory lock on a dedicated connection.
  4. Each row goes through createTargetFromRequest → CRM_RECORD_RECEIVED → the OnCRMSyncWorkflow identity-resolution machine (match by CRM reference, phone, email, social handle). A failed or incomplete run must never become a successful import through a second write path. New leads go through auto-assignment. Default phone country US.
  5. Queue expiry 3600 s; a batch open longer than 1800 s is reported by the queue-health monitor.

Call audio (Vodafone / OneNet, MiCampus pitch)

Signed upload URL → manualImport.callImport.submit processes the zip synchronously inside the API request: ElevenLabs STT/diarisation, LLM speaker attribution, workflow dispatch. In-memory progress is polled by getProgress. Marked "MVP shortcut for internal use only" with a TODO to move to a durable job. nginx raises its timeout for exactly those two procedures; the namespace ceiling is 30 min. Progress is lost on an api restart and long batches can exceed 30 min.

Evidence
  • apps/web/src/features/settings/manualUpload.ts:22,134-246
  • apps/api/src/trpc/manual-import/index.ts:556-700; packages/services/src/manualImport/batch/submitBatch.ts:36-60
  • apps/worker/src/manualImportConsumer.ts:1-17; batchLock.ts:8-25; batchProcessor.ts:30-37
  • packages/services/src/manualImport/createTarget.ts:1-44; queueConfig.ts:9-18
  • apps/api/src/trpc/manual-import/callImport.ts:108-217; infrastructure/nginx/nginx.conf:300; apps/api/src/trpc/trpc.ts:127-141

Support manifest, files and Home

  • packages/services/src/support is not customer support. It is an engineering inventory: PROVIDER_MANIFEST (provider → integration type → connector package) and scheduledJobsManifest (shipped, dropped, deferredProductDecision). Dropped: detectDropoffEvents, runEmailCampaign, sendEmailReminders. Deferred: revivalGateSweep, calendarBookingMagicLinkSweep. No customer help-desk integration exists in the web app.
  • Files. file_storage rows (provider GCS | GOOGLE_DRIVE, file_category, gcs_uri). files.getById / getDownloadUrl return metadata or a GCS signed URL after a per-category check: knowledge-base → nexus.view, contact_attachment → leads.view, else conversations.view; owner/admin bypass.
  • Home. home.myDay (overdue and today's reminders, unacknowledged escalations, paginated), home.ownerCoverage, home.activity (audit feed), all remindersAndAuditTrails.view and owner-scoped via scopeFor(actor); home.communication (insights.view). Acknowledge/unacknowledge urgent audit rows. Known TODO(perf): reminders and recent conversations are filtered in memory.
Evidence
  • packages/services/src/support/manifest.ts:1-40,113-158
  • packages/db/src/schema/fileStorage.ts:16-46; apps/api/src/trpc/files/index.ts:31-139
  • apps/api/src/trpc/home/index.ts:88-164; packages/services/src/home/read.ts:84-208; packages/services/src/home/index.ts:171-203,281

Production SQL operations tooling

The only sanctioned general-purpose way for engineers and agents to read or write production Postgres: bun run prod-db-read -- --sql 'SELECT …' and bun run prod-db-write -- --sql '…' [--commit] (or --sql-file). Both are thin wrappers over scripts/operations/prodDbSql.ts.

  1. Connection pinning. Reads only the primary checkout's .env.cloudsql. Refuses unless DATABASE_URL is postgres(ql):// on 127.0.0.1/::1/localhost, port 5433, with no query string or fragment: the owner-managed loopback Cloud SQL proxy. Agents never start or stop the proxy.
  2. AST validation with libpg-query (PostgreSQL 16 parser): exactly one top-level statement; read mode = SELECT only, write mode = INSERT|UPDATE|DELETE only.
  3. Function ban. Any FuncCall/FuncExpr/SQLValueFunction is rejected. Reads may use plain count/min/max/sum/avg only (unqualified or pg_catalog; no OVER, WITHIN GROUP, ORDER BY, VARIADIC). No SELECT INTO, no locking SELECT, no data-changing CTE in reads.
  4. Provably restrictive write predicates. UPDATE/DELETE need a WHERE; UPDATE FROM / DELETE USING rejected; any OR, wildcard, tautology (1=1, true, x = x) or non-comparison fails; at least one AND arm must compare a target column with a literal or another column. INSERT … ON CONFLICT DO UPDATE needs a restrictive WHERE that does not reference excluded.
  5. Transactions. Reads: BEGIN READ ONLY, always ROLLBACK. Writes: BEGIN, SET CONSTRAINTS ALL IMMEDIATE, then ROLLBACK unless --commit. SET LOCAL statement_timeout 60 s, lock_timeout 5 s, idle_in_transaction_session_timeout 30 s by default, each overridable within bounds.
  6. Unknown commit. A connection failure during COMMIT raises CommitOutcomeUnknownError rather than guessing.
  7. Insight table fences. --lock-insight-tables, or --lock-insight-bootstrap-tables with --insight-bootstrap-organization-id, take ordered SHARE ROW EXCLUSIVE locks under READ COMMITTED before the DML snapshot.
  8. Output is one JSON line {mode, outcome, command, rowCount, rows}. There is no affected-row cap: callers gate the commit on the dry-run rowCount.
Process rule. Rehearse in a disposable local DB → dry run → explicit authorisation → --commit → reread. Full policy in the data-operations guidance.

Other tracked scripts in scripts/operations/: the RevOps deal loader (bun run revops-deal-load, dry-run default), the content-insight bootstrap runbook with hash-pinned acceptance, the lock-fence concurrency proof, the monthly email-tracking:signature-review, Phase 2 deploy and GCP log-metric runbooks, developer-machine workspace:clean, and a UC2 one-off marked for deletion late Nov 2026. Gate: bun run operations:check (typecheck + vitest for scripts/operations and scripts/nexus), included in gates:db.

Evidence
  • package.json:28,76,122-125; guidance/data-operations.md:5-31,33-143
  • scripts/operations/prodDbSql.ts:4,9-14 (parser, env, timeouts), :315-373,469-517 (predicates), :385-465 (functions, locking), :520-585 (statement mode, overrides), :687-700 (--sql-file), :740-821 (pinning, unknown commit), :855-943 (transactions, fences, output)
  • scripts/operations/workspaceClean.md; reconcileSixFreshsalesDay3Tasks.ts:2

Schema cleanup (phase 2)

Removes verified-dead schema from the Python→TS migration and earlier CRM work: crm_sync_cutovers, crm_activation_packets, revival_metrics, orphan enums and four shadow identity columns, and stops selecting organizations.nexus_enabled / crm_outcome_read_configs.activation_packet_id. Migration 0065_daffy_strong_guy.sql is a compatibility release: it locks target tables, refuses non-empty retired tables or unexpected shadow data, uses 5 s lock / 60 s statement timeouts, never CASCADE, and keeps the two physical columns for the previous release. Dry-run tooling runs via bun run schema-cleanup:test.

Status: 0065 is merged (planning doc says "not merged or deployed" — stale). The follow-up contract drop of nexus_enabled and activation_packet_id is not done. Dropoff monthly-rollup repair and sentiment v3 history discard are separate, unapplied decisions.

Evidence
  • planning_docs/schema-cleanup/phase2.md:3,6-48,69-125
  • packages/db/drizzle/0065_daffy_strong_guy.sql:1-2; rg over packages/db/drizzle/*.sql finds only 0031, 0062, 0065 mentions
  • package.json:26; scripts/audit/schemaCleanupDryRun.ts, dropoffRollupDryRun.ts

DB connection resilience

On 2026-09-02 a host network reset killed Postgres TCP sessions. The shared pg.Pool had no idle-client error handler (could crash API/webhooks/scheduler), and the workflow runner's session advisory lock is released by Postgres the instant the session dies while JS may still be doing provider work.

  • Phase 1 (monitoring): /ready uptime checks for API and webhooks, process-fatal and fatal-shutdown-hard-timeout log metrics, 8 alert policies on an email channel, via a targeted Terraform apply.
  • Phase 2 S2A–S2B (code): pool and checked-out-client error handlers report instead of crashing. Execution-safety holds: a typed top-level executionSafety field in workflow JSONB is persisted before provider transport; a later owner that finds an unresolved hold pauses or escalates instead of acting; provider-acceptance receipts can be recorded idempotently on a fresh connection; only the original owner clears the hold; automatic resend is rejected. This is the send-safety hold; internals are in XState.
  • Lease cleanup no longer sends a redundant ROLLBACK on an idle session (commit 52bfbf552).
Rollout. The epic says S2B is merge-ready with force-recreate/rollback rehearsal and rollout approval remaining, and no deployment authorised. Hold code is merged here. False-positive holds are possible and need operator resolution; rolling back to a pre-hold image over unresolved holds is unsafe.
Evidence
  • planning_docs/db-connection-resilience/epic.md:11,20-26,83-134; adr-execution-safety.md:1-38 and "Consequences"
  • packages/db/src/client.ts:176,239
  • packages/repositories/src/workflowExecutionSafety.ts; packages/workflows/src/runner/workflowRunnerTxFinal.ts:344; workflowRunnerActorProtection.ts; workflowLease.ts

Webhook durability

Deploy safety after the 2026-07-10 outage (release transaction, readiness before replacement, expand→contract migrations) is covered in Deploy. The webhook recovery pieces built here:

  • webhook_receipts: raw WhatsApp body stored as text before parsing, SHA-256, replay counters, processed/failed timestamps, spooled_at, fixed 14-day expires_at (PII).
  • GCS spool: when Postgres is unreachable at ingress, WhatsApp/Messenger/Instagram bodies go to webhook-spool/ in the private bucket. Production requires the spool; a failed capture returns 500 so Meta redelivers.
  • webhookReceiptMonitor (hourly at :15): system-issue alert emails for receipts unprocessed after 30 min, a daily 06:00 UTC digest, deletion of expired receipts.
  • Operator replay: scripts/webhooks/replayStoredWhatsappReceipt.ts requires explicit allowCustomerSideEffects and a confirmed receipt id equal to the target id; success scripts webhookSpoolSuccess.ts, receiptReplaySuccess.ts.
Evidence
  • packages/db/src/schema/webhookReceipts.ts:13-56
  • apps/webhooks/src/composition.ts:46-55; commit 5ab94d08e
  • packages/services/src/scheduler/jobs/webhookReceiptMonitor.ts:11-20,144-147,201; packages/repositories/src/webhookReceipts.ts:185-216
  • scripts/webhooks/replayStoredWhatsappReceipt.ts:13-14,65-69

Workflow envelope invariant

targets.workflow_status / next_action_at mirror only the top workflow envelope. A post-workflow stacked on a parked delayed reply could hide it from the scheduler forever (one target was stranded this way). The proposed invariant: mirrors expose the earliest due work anywhere in the stack.

StepStatusDetail
1. instant registry class, forced restore-on-failurebuilt"Must finish in the current dispatch and must never park." Set on on_conversation_complete, on_crm_sync, on_call_complete, all client successor shells and a MiCampus dry-run cadence. The runner turns any non-terminal settle into failed with instantMachineFailed.
2. Repair one-off + detectorplannednot found
3. Explicit restore | cancel successor contractplannedstill restorePrevious: boolean
4. Stack-aware mirror + WAKE unwindingplannednot found

The Meta #131000 send-stage failure fix in the same design doc was not verified.

Evidence
  • planning_docs/workflow-envelope-scheduler-invariant/design.md:1-30, §3.5, §4
  • packages/workflows/src/registry/workflowRegistry.ts:179-185; workflowRunnerEnvelope.ts:28-82
  • onConversationComplete.machine.ts:932; onCrmSync.machine.ts:59; onCallComplete.machine.ts:111; clients/clientSuccessorWorkflowEntry.ts:17,72,83,100; clients/micampus/cadences/outboundDryRunCadence.ts:67

Workflow lock contention

on_crm_sync waited up to 180 s for a target's session advisory lock held by legitimate (often LLM) work, then threw AdvisoryLockAcquireTimeoutError: PostHog noise and false customer-visible CRM failure audits.

  • S0: WorkflowTargetBusyError boundary error. The CRM sync orchestrator and email-CRM syncer treat it as a deferral: crm_sync_record_deferred_lock_contended info event, no audit, no logger.error, cursor not advanced, no attempt-budget burn.
  • Handoff coalescing: when a successor declares coalesceHandoffEventDataKey, older pending workflow_handoff_pending rows for the same target/successor/key are marked done (superseded_by_newer_handoff) in the same transaction, so a burst of reply turns queues one follow-up run.
  • Claim-first dispatch: the runner claims the durable row (pending → in_flight) before the target lock; on WorkflowTargetBusyError it requeues and un-counts the claim so contention never exhausts the dead-letter budget.
  • Earlier advisory-lock starvation fix across inbound routes, scheduler jobs and the lock watchdog (commit e9bd967d2).

Planned (Q1–Q7, unapproved): target-busy semantics for all callers, removing webchat's 10 s self-retry, resolving CRM identity before XState, a Postgres target mailbox with customer-webhook priority, durable deferred result delivery, whole-run budgets and shorter lock ownership, manual/external CRM replay.

Evidence
  • planning_docs/workflow-lock-contention/epic.md:7,16-20, §9
  • packages/ports/src/workflowRunner.ts:30; packages/services/src/crmWorkflows/syncOrchestrator.ts:121; packages/services/src/scheduler/jobs/emailCrmSyncer.ts:432
  • packages/workflows/src/runner/workflowRunnerTxFinal.ts:539-575; handoffDispatcher.ts:14-27,97-113

CI validation reuse and vibe-code cleanup (short)

CI validation reuse aims to validate identical effective inputs once across pre-push remote checks, PR CI and main promotion. Slices 1–2 and the detached execution substrate exist (scripts/checkremote/validationShadow.ts, systemdValidationWorker.ts), but nothing else under scripts/ or .github/ calls them and all output says shadow-only. Promotion cutover is planned. checkremote itself now accepts only --target aws; see Deploy.

Vibe-code cleanup landed: ratchets (knip:check, duplicates:check, file-size:check, comments and types baselines, eslint-suppressions:check) are in check:static. Never regenerate baselines; shrink them with bun run lint:prune. Task 10 (client hardcoding) is parked. Details in How we build.

Evidence
  • planning_docs/ci-validation-reuse/epic.md:9-51,67-98
  • scripts/checkremote/run.ts:28,616-623; planning_docs/aws-checkremote-parity/index.html
  • planning_docs/vibe-code-cleanup/index.md:5,83; 10-client-hardcoding.md:3; package.json:15,19,53,72,98,143

Security and compliance

ControlStatusWhat it does
Vanta remediation matrixinventory2026-09-08 snapshot from the Vanta MCP, "not proof that a control is satisfied": 72 automated tests, 91 document checks, 125 needing remediation. Decisions: keep the app VM's public IP (the failing firewall tests name the manually managed zube-checkremote-runner); app SSH is already IAP-only (35.235.240.0/20); MFA enforcement is a manual owner task; no production apply in that batch; do not touch the Cloud SQL proxy.
SAST + dependency scanbuiltSemgrep CE p/default (pinned semgrep==1.177.0, metrics off) and bun audit; locally bun run security:scan. CI on PRs (fails only on new findings vs base), on main, Mondays 10:00 Europe/London (two DST-safe UTC crons) and manual dispatch; 90-day artifacts; no GitHub code-scanning upload.
Production vulnerability evidencebuiltSelf-hosted runner, shares the production-deploy concurrency group. Reads the deployed image manifest, collects GCP VM Manager OS vulnerability reports, verifies a Cosign-signed Trivy v0.74.0 and scans each exact deployed digest. Fails on missing/stale evidence, not on findings. GitHub OIDC → Workload Identity Federation, read-only roles. Plan page banner: "IMPLEMENTED IN PR #106 — awaiting merge and production verification".
Cloud SQL backup monitorgatedIndependent Cloud Run job, daily 11:00 UTC, reads SQLAdmin metadata only for zube-agents-prod. Checks the AUTOMATED backup for the 05:00 UTC window (4 h + 2 h grace), writes gauges cloudsql_backup_health / cloudsql_backup_assessment, alerts on OPENED only. Image variable defaults to null (unprovisioned), alerts default off; deployment is a manual, isolated Terraform procedure. Read-only verification on 2026-09-30 saw 31 healthy backup runs.

(security-scanning.md says the manifest must contain exactly api, webhooks, scheduler — stale; the assessor's SERVICE_NAMES lists all five services.)

Evidence
  • planning_docs/vanta-remediation/remediation-matrix.md:3,7-11,15-40,148
  • package.json:11-13; guidance/security-scanning.md:1-80; .github/workflows/security-scan.yml:3-11,39-173,286-290
  • scripts/security/assessProductionVulnerabilityEvidence.ts:10-18
  • infrastructure/cloudsql-backup-monitor/README.md:1-12; packages/gcp/src/sqlBackupMonitor/{main,assessment,client}.ts; infrastructure/terraform/cloudsql-backup-monitor.tf

Multi-app split

Phase 1: shipped 2026-09-27

Three backend containers became five (cutover b00fef8c6):

ContainerOwnsDeploy
apiExpress + tRPC, proposalsoverlap
webhooksMeta/IG/Messenger/ElevenLabs post-call, OAuth, callbacks, webchat HTTP+WS; verify → receipt → enqueue → 200overlap
workerpg-boss consumers + the three dispatcher ticks (plus the webhook spool drain when a spool is configured) behind a singleton session advisory lockoverlap
telephony-infra/telnyx/*, /voice-tools/*, /client_tools/*, process-local call stateonly on its own path changes or --release-telephony-infra, after zero active calls (up to 30 min, else deferred); fortnightly Sunday 04:00 UK window
schedulercronsin-place restart; single instance, no leader election

Two worker instances are safe because dispatchers claim with FOR UPDATE SKIP LOCKED, per-target advisory locks serialise workflows, and ticks run under one session lock with a documented overlap window.

Phase 2: worker split (merged; production state unverified)

Goal: every event- or user-triggered machine run happens only in apps/worker. apps/api, apps/webhooks and apps/telephony-infra no longer depend on @zube-agents/workflows; worker and scheduler do. The worker holds inboundEventConsumer, voicePostCallConsumer, manualImportConsumer, agentPreviewConsumer and webchat/ (webchat moved to the worker, reversing a Phase 1 decision). Queue expiries: inbound-event 900 s, voice-post-call 3600 s, manual-import 3600 s, agent-preview 300 s.

Phase 2 removalStatusCommit
All AI outbound calling (legal)removed2b5147e32
Outbound customer webhooksremoved15f22eddd
/api/v1 developer APIremoved88c4096b6

Also landed: slice D silent-drop monitoring (fdbd91789) and the Phase 2 deploy and monitoring runbooks, where the owner runs every step. (The worker-split doc's status "final draft … implementation starts with A1" predates the merged code — stale.) Topology and deploy mechanics: Deploy.

Evidence
  • planning_docs/multi-app-split/plan.md:3,7-53,79-120, §4; :30 (Phase 1 webchat decision)
  • infrastructure/docker-compose.yml:24-155
  • planning_docs/multi-app-split/worker-split.md:3,7, §2
  • apps/{api,webhooks,telephony-infra,worker,scheduler}/package.json — workflows dependency presence
  • packages/db/src/jobQueue/queueConfig.ts:9-14
  • scripts/operations/phase2Task0Deploy.md; scripts/operations/phase2Monitoring.md:5; commits verified ancestors of HEAD
  • guidance/engineering-constraints.md:103

Doc-vs-code discrepancies

Trust the code over these docs. Whoever maintains onboarding should fix or annotate them.

DocClaimCode reality
planning_docs/user_acl/implementation_status.md:309-311Slice 9 assignment automation "Not started"autoAssignCreatedLead (round robin / random / LLM) exists and is called from inbound paths
planning_docs/schema-cleanup/phase2.md:3"not merged or deployed"Migration 0065_daffy_strong_guy.sql is in this branch
planning_docs/vibe-code-cleanup/index.md:5"No code changes yet"Many cleanup merges and ratchet gates in HEAD
planning_docs/aws-checkremote-parity/index.htmlAWS not approved; do not runrun.ts accepts only --target aws; which blockers closed is unverified
planning_docs/organization-feature-flags/epic.md:8implementation blockedFeature-flag admin and organizationFeatureProcedure exist
planning_docs/magic-booking-link/epic.md:8"draft discovery"Booking links are issued and redeemed in code
guidance/security-scanning.mdmanifest = exactly api/webhooks/schedulerAssessor expects five services
infrastructure/status/README.md:111release tuple api/webhooks/schedulerFive-container topology
guidance/engineering-constraints.md:111admin = @getzube.comDefault internal domains getzube.com,zube.ai, env-configurable (packages/config/src/env.ts:10)
Owner's request"60-day data retention / purge"Nothing in this checkout; webhook receipts expire after 14 days, voice-demo usage after 13 months

Custom client code

Per-client behaviour is TypeScript compiled into the deploy, not data. Five clients have code: Stay Club, Lingua, MiCampus, Road Scholar and Addison Lee. It lives in two client roots and plugs into the platform only through typed seams: hook slots on the runner, AI-callable tools, cadence configs, email-CRM parsers and report generators. Boot asserts every expected registration against a hand-written list.

Client roots packages/workflows/src/clients/<c>/ hooks · successor machines · cadences email-CRM parsers · reports · prompts packages/client-tools/src/clients/<c>/ AI-callable tools · report metadata calendar params (workflow-free, tier 5) external-connectors/client-custom ZoomInfo (Addison Lee) only apps/scheduler/src/tasks/addison* Addison Lee runtime composition registered at boot by registerClients.ts (never stored in a DB table) Runner hook slots, key (org, machineId, businessWorkflowId) preHook: before the actor; may consume the run postHook: after a terminal settle (never sees output) getPostWorkflow: returns the successor {machineId, eventData} preCrmSyncback: mutates CRM write properties in place Client tools (createClientVoiceTool) voice: /voice-tools/elevenlabs/custom/:client/:fn (+ legacy) shared secret only; no plannerCallable/org check text: only if org ↔ bundle, plannerCallable, and the key is in a tool_node.allowedToolKeys of the org's template Outbound cadence registry OutboundCadenceConfig per client + optional pre-send guard (MiCampus) Email-CRM parser registry crm@getzube.com notification emails → contacts (Stay Club Salesforce mails, Road Scholar enquiries) Report generators clientReportGenerators + workflow-free metadata; definitions are DB rows editable in the UI
The seams. Hooks run inside the generic runner. A preHook throw fails the run, while postHook errors are swallowed. Hooks must use clock.now(), never Date.now(). The client-boundary gate keeps client names, tool names, fetch and Date.now out of the wrong places.

Per-client inventory

Stay Club (coliving / student accommodation, London; Salesforce via CRM emails)

KindWhat
HooksOn 5 business workflows (null, university_fair, meta_ads, meta_ads_students, meta_ads_professional). getStayClubCrmSyncPostWorkflow parses the CRM record, then selects an outbound cadence through a named-workflow rule → auto-reply suppression → guardrail cadence (e.g. the Hanger Lane / North Acton redirection) → an LLM selector (gpt.fast). It can wrap the handoff in a viewing booking. A CRM-sync postHook writes a help-needed escalation when auto-reply is suppressed.
Successor machinestay_club_crm_requested_viewing_booking: books the requested viewing, then sends confirmed / unavailable / clarification emails and hands off to the cadence.
CadencesLegacy-ported coliving/student follow-ups, WhatsApp openings, long-stay promo, university fair, Meta Ads students/professional/parent.
OtherEmail-CRM parser for Salesforce notification emails; calendar booking params (invite email, attendees per event type); report "Meta Ads acquisition efficacy". No custom tools.

Lingua (language school, US campuses, EN/ES; HubSpot)

KindWhat
HookspreCrmSyncback resolves preferred campus and area of interest: exact canonical lookup first, then Decision-1, then a gpt.fast fallback. It skips Dynamics. getPostWorkflow on CRM sync hands off to lingua_outbound_cadence; on conversation-complete it hands off to lingua_conversation_complete.
Successor machinelingua_conversation_complete: a templated post-conversation email (en/es HTML templates).
CadencesWhatsApp outbound, localised by phone region (es LatAm / pt_BR / en); a revival cadence that is registered but has no producer.
Custom toolget_enrollment_link: the runtime owns the URL and folds it into the reply (finalReplyPolicy: append_output_field).

MiCampus (student residences, Spain/Portugal; Salesforce)

KindWhat
HooksSalesforce preCrmSyncback: rewrites lead source (outbound WhatsApp vs Zube inbound) and moves a lone first name into last name. getPostWorkflow on CRM sync runs the Google Ads WhatsApp cadence (live). getPostWorkflow on conversation-complete hands off to micampus_call_complete (prod + internal test org).
Machinesmicampus_call_complete; micampus_outbound_whatsapp_dry_run dormant.
Custom toolsget_properties (searches a bundled properties.json; knowledge-gap diagnostics eligible) · get_booking_link · send_booking_link_via_whatsapp (write) · send_booking_info (write, voice-only because it isn't planner-callable).
OtherReports: Salesforce lead cohort workbook, conversion performance. Vodafone call-audio import (generic platform code in services/src/manualImport, built for MiCampus). Salesforce syncback hardening (country-aware phones; the code now uses a 2 h quiet period for automatic CRM creates).

Road Scholar (educational travel, US)

KindWhat
RegistrationEmail-CRM parser only (sets road_scholar_trip_interest, with a TODO pending client mapping). No hook slots.
Custom toolget_trip_list: searches a bundled trips.json by programme number, keyword or trip type. The deploy's nginx routing smoke test calls it on both tool paths.

Addison Lee (UK cars / couriers; B2B sales pilot; Freshsales, Microsoft mail)

KindWhat
UC1 customA preHook on the sales inbox treats every inbound email as a lead-gen trigger: it consumes the run, so Zube never auto-replies. The pipeline runs enquiry classification → seed repair → lookalikes (ZoomInfo, Lusha; up to 200) → fit review → master-list match → NHS→London filter → contact search → prong decision → per-contact drafts in a Zube Drafts folder. Nothing is sent. It runs on GB-pinned Bedrock and is registered asynchronously in the scheduler only.
UC2 removal scheduledA one-off media-production cold outbound campaign: email + LinkedIn tasks in Freshsales (Day 1/3/5/9/12/14 on UK workdays), daily caps, London send window, a campaign-reply interceptor. All tagged TODO(delete-addison-lee-uc2-one-off) for late Nov 2026. Don't refactor it.
OtherZoomInfo wrapper (client-custom), Lusha (prospecting), Gemini grounded web search ports; media production weekly report; NICE CXone connect path; Microsoft email auth recovery; the RevOps pilot (see Direction).

Other organisations have no client code here: 21 Degrees (positioning only), LBF Travel (a public voice demo slug) and the demo presets.

How a custom tool reaches the agent

  1. Define it in packages/client-tools/src/clients/<client>/customTools.ts with createClientVoiceTool({clientName, functionName, description, plannerCallable, sideEffect, diagnosticEligibility?, finalReplyPolicy?, plannerInputSchema, inputSchema, outputSchema, handler}). The wrapper validates input and output with Zod. Put the name constant in customToolNames.ts.
  2. Add it to CLIENT_CUSTOM_TOOL_BUNDLES ({clientName, organizationId, tools}). An owner mismatch throws at import.
  3. Voice: configure the ElevenLabs agent (outside the repo) to call /voice-tools/elevenlabs/custom/<client>/<fn>. Context fields (target id, phones, dynamic variables) are stripped from the input and passed as execution context with clientToolEffects.
  4. Text: add the tool key to a tool_node.allowedToolKeys in the org's Foundry template graph (data, not code). The adapter filters org → bundle → plannerCallable → graph keys, then binds executors with a 12 s timeout.
Review point. The voice tool endpoints authenticate only the shared secret and the client name; they don't check that the calling org matches the bundle's org. That may be intentional, since the secret lives in the ElevenLabs configuration, but it is worth a deliberate look.

Debt: client code outside the client roots

The parked "client hardcoding" inventory counts 761 client-name hits across 41 shared production files (Addison Lee 480, Lingua 107, MiCampus 58, Jev 52, Stay Club 50, Road Scholar 14). Examples: Stay Club CRM email senders in utilities/src/email/crmDomainMap.ts; the Road Scholar voice param in services/src/voice/callParams.ts; client-named methods on the generic ClientHookEffectsPort; Addison org UUID branches in apps/scheduler/src/tasks/addison*. The boundary gate checks filenames, tool names and imports but not file contents. The plan is config-driven first, then hooks-as-data (see Direction).

Evidence
  • packages/workflows/src/registry/clientRegistry.ts:45-298; packages/ports/src/workflowRegistries.ts:37-99: hook types and key
  • packages/workflows/src/clients/registerClients.ts:21-167; registry/expectedRegistrations.ts:30-106; registerClientHooks.ts:4-49
  • packages/client-tools/src/tools/clientVoiceToolDefinition.ts:58-120; clients/customTools.ts:6-24; tools/clientVoiceTools.ts:54-130
  • apps/telephony-infra/src/inbound/elevenlabs/toolCalls/customClientTool.ts:28-187
  • packages/workflows/src/clients/stayClub/postWorkflowHandoffs.ts:271-420; lingua/hooks/crmSyncback.ts:206-323; micampus/index.ts:49-203; roadScholar/index.ts:12-17; addisonLee/registerClient.ts:1-655, pipeline.ts:1-30, draftPersistence.ts:1-20
  • scripts/grep-gates/clientBoundary.ts:6-83; planning_docs/vibe-code-cleanup/10-client-hardcoding.md:3-56

Where we're heading

Three fronts run at once: make the agent more trustworthy (Nexus 2.0, guardrails, small-model decisions behind deterministic checks), turn conversations into revenue evidence (insights, loss reasons, CRM outcomes, and now B2B deal intelligence), and mature the platform (the five-service split, fencing, compliance). The open strategic tension is that per-client custom code still ships with every deploy.

Lead lane · shipped XState machines per target state in targets.workflow_state advisory lock per target, ≤240 s settle agentic replies, cadences, CRM syncback B2C and B2B inbound/outbound conversations 9 machines + client hooks Deal-intelligence lane · partly on a branch one run = one deal at one checkpoint own claim / lease / heartbeat, revops-run queue reads Postgres only; writes deal days passive: sends nothing, writes no CRM intelligence-only orgs (no channels, no CRM link) EU Bedrock 5.5 + Decision-1, cost-capped Case lane · proposed, not approved unit of work = a case (subject), not a lead definition in TypeScript, instance in a row named setup() implementations only generic triggers; blocks promoted on 2nd use first tenant: hotel chargebacks later: converge RevOps, UC1-style jobs Shared substrate: XState for orchestration · pg-boss for transport · Postgres rows for durability (claims, leases, carry state, reply logs) · typed refusals
Long-running non-lead work is converging on the same shape. Today about six execution models coexist (lead machines, UC1 continuation, the UC2 tick, report scans, RevOps runs and pg-boss consumers), each with its own claim, retry and state handling. The case-lane proposal would generalise them.

1 · B2B deal intelligence (RevOps), the biggest new bet

Built first for Addison Lee's B2B sales team. Zube reconstructs each large deal from its email threads (calls later). For every day it records who decides, which customer-internal steps block the signature, dates and slips, and the evidence quote behind each claim. Execs care only about deals that are blocked or falling behind, so blockers come first in the UI. Forecasting is core to the long-term product, but it is not in the pilot.

PieceStatusDetail
4 tables: revops_deals, revops_deal_targets, revops_conversations, revops_deal_days (migration 0094)mergedPeople link to targets; seller-side people are ref_only with no target row.
tRPC revops router + Deals UI (overview, pipeline, per-deal: people tree/sides/table, concerns, commitments, timeline, conversations, CRM updates, gaps)flag: revops_dealsNew UI only; Classic renders not-found.
bun run revops-deal-loadops toolInserts one pre-computed as-of deal export; rehearse → dry run → --commit.
XState checkpoint-run machine (revopsCheckpointRun: claiming → loading → step loop → committing)branch: claude/revops58 commits, ~200k lines (much of it fixtures). Run state lives in DB rows; the actor runs in memory to completion. It never uses the lead runner: one real-deal run took about 5 h and 4,149 calls.
revops-run queue, revops_runs/_deal_states/_run_replies/_org_configs, run and monthly USD caps, resume from the reply logbranch"Latest run wins": a rerun replaces the state at C and deletes later days.
Decision-1 moved from OpenRouter to Azure Foundry (EU/US)branchCross-cutting: escalation Tier 2, lead lifecycle, Lingua campus and the Nexus matcher move with it. Deploy blocked until both Azure keys are in prod; adds two env vars.
Dormant by constructiondormantNo scheduler entry. crmReader: null, so every start refuses crm_reader_unavailable. Eligibility allows only intelligence-only orgs, which conflicts with orgs that have Freshsales connected (an open decision).
Forecast, past blockers and renewals pagesbranchRun on seeded synthetic demo portfolios (a clock-simulation forecast model). "Renewals schema" is a Zod schema for the demo data, not a table.
Identity substrate: multi-stakeholder email threading + CRM deal mirror (art_73a5ddf7, rev 9)proposed, unbuiltIts branch has 0 commits; none of its tables exist. The gating decision for live RevOps.
RevOps Intelligence plan (art_f7b5664c, rev 4)draftAn exec "exceptions" MVP on ≤5 deals, with slip signals and experiments X1–X5. Practice has moved past its local single-file shape.

2 · Custom-client scalability

Every custom integration is hand-written code, so onboarding a client means a push, a build and a VM deploy. That works for five clients; it doesn't scale to many onboarding at once. The direction, currently parked: config-driven first, then hooks-as-data. Per-client literals and logic move into persisted config (never new env vars), and only the residue becomes runtime-loaded hooks. The client-boundary gate already stops the sprawl from spreading to new files. The managed runtime proposal (art_e7fce6a6, 23 Oct 2026, unapproved) is the near-term step for non-lead workflows: a case lane with definitions in code and instance rows per org (the report_definitions precedent). It explicitly rejects n8n and a visual builder or DSL for now. Open decisions: O1 who authors (assume engineers), O2 a subject-keyed runs table, O3 pg-boss triggers, O4 RevOps convergence later, O5 revisit "no DB table for client hook configs", O6 chargebacks first.

3 · Other themes from the planning docs (61 folders + 2 files)

ThemeBuiltIn flight / planned
Agent quality & knowledgeNexus 2.0 researcher, curated ingest, observed gaps, workflow-scoped knowledge, guardrail escalation, gpt.fast semantic routing, Decision-1 gates, GPT-6 tieringTaxonomy rollout gates; diagnostics-recovery backfill (awaiting a decision); semantic remediation groups (stopped)
Insights & revenue evidenceConversion insights (flag), loss reasons, drop-off observations (admin), half-hour sentiment, acknowledgement metrics, 4 client reportsAutomated revival, quality→outcome metric and privacy-safe long-term aggregates are held; waitingOnTarget missed its precision gate
CRM as system of recordCRM Sync V2 Track A + safety substrate, identity convergence, syncback recovery, Freshsales (no syncback; tasks only), DynamicsCanonical single writer; Dynamics release gates; Freshsales deals; 21 Degrees "layer above any CRM" positioning (commercial only)
Channels & conversionWebchat + continuation, WhatsApp BSUID/edit safety, magic booking links, public voice demosCalendar booking truth (approved, no tables yet), link-domain admin UI, native realtime audio (draft), OAuth account linking, Spanish UI
Platform reliabilityFive-service split, execution-safety holds, lock-contention fixes, deploy release transaction, webhook spool, status pageStack-aware workflow mirrors, CI validation reuse cutover, durable Nexus ingest jobs, target mailbox
Governance & complianceUser ACL milestone 1, org feature flags, Semgrep/audit/Trivy evidence, backup monitorVanta remediation (inventory), ACL slice 10, data-retention evidence

What this means for a new engineer

  • Changes to the lead lane (runner, text machine, agentic adapter, prompts) are high blast radius. They need explicit scope, representative replays, two reviewers and the xhigh final review.
  • New long-running non-lead work should not go on the lead runner. Until the case lane is decided, read art_e7fce6a6 first (bun run plans:read).
  • New client asks: prefer config and existing seams (hooks, tools, cadence configs, report generators) over new branches in shared code. Never add per-client env vars.
  • Data residency is a design constraint: EU/UK-pinned clients disable cross-provider fallback, and RevOps customer text may reach only EU Bedrock profiles.
All planning docs, one line each (status checked against code)
DocPurposeCode reality
21-degreesPositioning for a trades/renewables group pilotcommercial only
account-organization-oauth-linkingLink Google/Microsoft login to existing accountsnot built
addison-lee-media-production-outboundAL UC2 campaignbuilt deletion late Nov
audit-trail-acknowledgement-metricsAre urgent events acknowledged?built
aws-checkremote-parityRemote checks on AWSAWS is now the only target; doc stale
calendar-booking-truthDurable appointments ledgerapproved, no tables
channel-workflow-routingPer-endpoint workflow routingpartial (endpoint workflowId exists)
ci-validation-reuseValidate once across CI/deployshadow-only substrate
client-custom-tool-ownershipMove tool names out of generic layersdone
client-proposalsproposals.zube.ai micrositebuilt; host activation pending per doc
client-report-generationRecurring client spreadsheetsbuilt (4 generators; doc stale)
client-semantic-routing-gpt-fastReplace regex classifiersbuilt
configurable-public-voice-demosRegistry for /demo pagesbuilt (doc says proposed)
crm-identity-convergenceMerge targets sharing a CRM refbuilt
crm-sync-v2Canonical CRM syncTrack A + B substrate built
crm-syncback-reliability-recoveryRecover failed syncbacksbuilt; replay state unverified
db-connection-resiliencePool handlers, execution-safety holdsbuilt
deploy-downtime-and-webhook-recoveryRelease transaction, rollbackbuilt
dropoff-observationSales-motion observationsbuilt differently (deterministic + cause only)
embedded-webchatWebsite chat channelbuilt, per-org setup
freshsales-crm-integrationFreshsales as a CRMbuilt read-only; deals not built
gemini-36-upgradeMove tiers to Gemini 3.6superseded (3.8 + GPT-first)
guardrail-escalation-intelligenceTemplate guardrails, escalation routingbuilt (incl. forwarding)
hourly-flex-insightsHalf-hour batch sentiment/custombuilt (GPT-first, doc says Gemini)
inactive-demo-account-policyDemo orgs with inactive usersbuilt
insights-v2Conversion, journeys, sentimentpartly built; several slices retired or held
integration-auth-recoveryMicrosoft email auth recoverybuilt
jev-decision-research · jev-testsProbabilistic decision model researchDecision-1 used in 4 places
language-settings-localizationOrg/user language, Spanish UIen-GB only; Spanish planned
link-domain-short-linkslink.zube.ai redirectspartial (no create UI)
loss-reason-intelligenceConversation-derived loss reasonsbuilt
magic-booking-linkSelf-serve booking linkbuilt (doc says draft)
micampus-google-ads-whatsapp-cadenceGoogle Ads → WhatsApp cadencelive
micampus-salesforce-syncback-hardeningSF syncback field rulesbuilt (2 h quiet period now)
microsoft-dynamics-crmDynamics via app userbuilt; release gates pending
multi-app-splitFive-service topologyshipped
native_audioRealtime voice instead of ElevenLabsdraft
nexus-* (7 docs)Researcher, curation, diagnostics, taxonomy, parity, remediationsee Nexus
openai-usage-controlGPT tier mapping, usage controltier mapping built; controls planned
organization-feature-flagsOrg-scoped preview featuresbuilt (doc says blocked)
periodic-vulnerability-scanningHost CVE evidencebuilt in CI (Trivy + VM Manager)
plane-cleanup-planBacklog clean-up previewops note
public-voice-demo-notes-generatorDemo setup from notesbuilt
revival-shared-categoriesShared loss/drop-off categories, regenerationbuilt; prod regeneration gated
schema-cleanupDrop dead schema0065 merged; contract step not done
status-page-mvpstatus.zube.aiinfra built; operator steps unverified
user_aclGroups, permissions, assignmentmilestone 1 + auto-assignment built
vanta-remediationSOC 2 control inventoryinventory only
vibe-code-cleanupRemove agent-written smells, ratchetsratchets landed; client hardcoding parked
vodafone-call-importImport recorded callsbuilt (backfill only)
webchat-channel-handoffWebchat → WhatsApp/email continuationbuilt, off by default
whatsapp-bsuid-username-migrationBSUID identitybuilt
whatsapp-edit-safetyEdited messages fail closedbuilt
workflow-envelope-scheduler-invariantMirror the earliest due workstep 1 built; rest planned
workflow-lock-contentionBusy-target deferral, coalescingS0 + mitigations built; Q1–Q7 planned
workflow-scoped-knowledgeScope knowledge to workflowsbuilt (doc says draft)
Evidence
  • packages/db/src/schema/revops.ts:1-157; apps/api/src/trpc/revops/index.ts:28-282; packages/webapp-contracts/src/admin/index.ts:225-271
  • claude/revops:packages/services/src/revops/machine/revopsCheckpointRun.machine.ts:88-198, run/startRun.ts:28-319, apps/api/src/trpc/admin/revopsPipeline.ts:47-156, packages/llm/src/decisionDeployments.ts:18-48, packages/config/src/env.ts:253-256
  • Artifact Server art_e7fce6a6 (managed runtime), art_f7b5664c (RevOps plan), art_73a5ddf7 (identity substrate), read with bun run plans:read; no comments on any
  • planning_docs/vibe-code-cleanup/10-client-hardcoding.md:3-56; packages/workflows/src/registerClientHooks.ts:36

Deploy, CI, observability

Deploys are GitHub Actions on a self-hosted runner. They need a green check:full marker for the exact SHA or tree, build only the services that changed, and run a journaled release transaction on the VM with automatic rollback. Logs go to Cloud Logging; every logger.error is also an error-tracking event in PostHog.

GITHUB ACTIONS · SELF-HOSTED RUNNER ON AWS EC2 (us-east-1) 1 · Test (check:full) on push to main / PR writes marker check-full-v2/<sha> 2 · resolve-deploy newest green SHA in a 10-commit window · no marker → refuse (break-glass force) 3 · Preflight + auth WIF → cicd SA · prod env from Secret Manager · read-only probes fail in ~30 s 4 · Build changed services diff vs live container SHA buildx linux/amd64 → Artifact Reg. import-only startup probes 5 · Ship to VM over IAP SSH .env.production + .env.migration invalidate image manifest first run generated rollout script VM RELEASE TRANSACTION (flock + journaled phases; zube-deploy-recovery.service re-enters on boot) snapshottag rollbackimages, env digests pull + probecandidate envnginx -t migrateapi image, migrationrole · db:migrate:runtime overlap rollapi → webhooks → workerscale=2, ready, stop old schedulerstop, thenrecreate telephony-infraonly at 0 active calls≤ 30 min, else defer nginx HUP + public smoke/ready reports deploySha→ backend_healthy 6 · Assert, Firebase, commit docker state on expected image + SHA Firebase Hosting release (SPA) last Rollback (trap on ERR/HUP/INT/TERM after mutation_started) quiesce workflow services → refuse if any target holds an executionSafety hold → restore previous images + env + config Migrations are NOT reversed, so they must stay backward-compatible. Scheduled telephony window Sunday 04:00 London, fortnightly: redeploy current SHA incl. telephony-infra
.github/workflows/deploy.yml → scripts/deploy/runProdDeploy.ts → generated bash from scripts/deploy/lib/releaseTransaction.ts. Three locks serialise production deploys: GitHub concurrency, a runner lock and a VM flock.

CI and remote checks

Workflow / commandRuns onWhat it does
test.yml (Test)self-hosted zube-checkremote (AWS EC2)PRs and pushes to main: bun run check:full (skipped if a marker already exists for the SHA or tree), UI tests when web changed, terraform validate when Terraform changed. Writes the check-full-v2/<sha> + tree markers that deploys require.
deploy.ymlsame runner, production environmentTriggers: Test succeeding on main, manual dispatch (sha, break-glass force, validate_only, release_telephony_infra), and Sunday crons for the telephony window. Resolves the newest green SHA in a 10-commit window.
security-scan.ymlubuntu + self-hostedSemgrep CE + bun audit (PRs fail only on new findings), plus a weekly production evidence job: VM Manager CVE reports + Cosign-verified Trivy over each deployed image digest
ci-recovery.ymlubuntu (outside the pool)every 5 min if enabled: wake the EC2 host, rerun jobs that lost the runner, alert on a queue stalled for 20+ min
renew-cert.ymlubuntu-latest → IAP SSHweekly certbot backstop
bun run check:remote · check:full:remotesame AWS hostShips your working tree (uncommitted changes included) as a git bundle, waits in a host-wide capacity queue (no time limit while queued), then runs under a deadline. A clean-tree check:full:remote writes the same deploy marker. Judge it by the Exit status: line.

Gates you'll hit locally: bun run check:static is required before any merge. It covers tracked inputs, the migration baseline, casing, file size, prettier, jscpd, knip, manypkg, all the grep gates, the type and comment baselines, raw SQL, ESLint suppressions, and lint + typecheck. Full checks (check, check:full, and the remote variants) run only when the owner asks. CI runs them on every PR and on main.

Images and runtime

  • Each image builds on oven/bun:1.4.4 (frozen install + turbo build), then copies in only the node binary from node:22.23.1-bookworm-slim. It runs as USER bun with CMD node --conditions=production dist/index.js (worker: dist/worker.js). Production runs Node; dev and tests run Bun/tsx, so prove runtime behaviour under Node when it matters.
  • Every image carries an import-only startupProbe that loads the app's real module graph. The deploy runs it on the runner and again on the VM before any mutation. This dates from an outage where a broken module graph reached production.
  • Images are linux/amd64, tagged by SHA, with DEPLOY_SHA baked in. /ready reports the SHA so the public smoke test can verify it.
  • Prod env is the Secret Manager secret zube-agents-prod-env, materialised on the VM as /srv/zube-agents/.env. scripts/deploy/pushProdEnv.ts updates it without a rebuild.

Observability

SignalHow
Logspino JSON to stdout → Docker gcplogs driver → Cloud Logging. Severity isn't mapped, so metrics regex-match "level"/"msg"; keep msg names stable.
Trace idsx-request-id reused or generated per HTTP request; every scheduled run gets its own requestId child logger.
ErrorscreateErrorReportingLogger mirrors logger.error to PostHog error tracking (EU), with messages and stacks scrubbed. Error tracking emails Zube per new or reopened issue, and PostHog alerts post back to /posthog/error-tracking-alerts.
Log-based metrics + alertserror_logs, process fatal, shutdown hard timeout, workflow_run_dropped_unexpected, job_queue_terminal_failure, job_queue_health_breach, addison_registration_failed, inbound.webhook_spooled (any count means an outage), spool backlog. Alert policies are gated by a Terraform variable.
UptimeGCP uptime checks on /health + /ready (api, webhooks) every 60 s; VM watchdog timers restart unhealthy containers; public Uptime Kuma at status.zube.ai.
Product analytics & costPostHog events (closed union, PII-redacted), $ai_generation per LLM call, vendor_usage_recorded for Telnyx/ElevenLabs/LLM spend (directional, not billing-grade).
Logging policy is product policy. The audit_trail is the client's activity log. Urgent rows there are only take-overs, human follow-ups, guardrail escalations and configured reminders. System faults (provider, credential, config, job or runner failures) are Zube-only: file them as category: 'system_issue' and they are diverted to one logger.error line. warn/info are benign breadcrumbs. A contact left without a reply always gets the standard take-over row ("AI Requested Human Help").

Local development

  • bun run dev starts api, web, webhooks, worker and telephony-infra (port 3003) under tsx watch with the primary checkout's .env.local. The scheduler is separate: bun run dev:scheduler. The worker runs ticks only with SCHEDULER_ENABLED=true.
  • Local Postgres (deps:up) exists only for bun run migration:check. Integration tests use testcontainers with drizzle-kit push, the only sanctioned push.
  • Production data: only through bun run prod-db-read/prod-db-write over the owner-managed Cloud SQL proxy on 127.0.0.1:5433. Never start, stop or reconfigure the proxy. See Platform for the safety model.
Evidence
  • .github/workflows/deploy.yml:3-264, test.yml:26-199, security-scan.yml, ci-recovery.yml:1-44
  • scripts/deploy/runProdDeploy.ts:1713-1992; scripts/deploy/lib/releaseTransaction.ts:103-1127; lib/changeDetection.ts:1-177; lib/greenShaResolver.ts:1-28
  • infrastructure/scripts/deploy-recovery.sh:1-68, commit-release.sh:9-76
  • scripts/checkremote/run.ts:167-195,900-1015,1550-1551,2445-2480
  • apps/api/Dockerfile:1-24; apps/api/src/startupProbe.ts:1-3; scripts/deploy/lib/productionProbe.ts:8-46
  • packages/logging/src/index.ts:14-278, requestContext.ts:27-61; infrastructure/terraform/monitoring.tf:1-567, compute.tf:55-87
  • guidance/observability.md:8-35; guidance/engineering-constraints.md:131-163

How we build (with agents)

Most code here is written by coding agents (Claude Code and Codex) and directed by engineers. Three layers make that safe: written policy the agents load (CLAUDE.md / AGENTS.md plus guidance/*.md), a routed set of subagents with fresh-context review, and a long chain of custom static gates and shrink-only ratchets that catch the typical agent failure modes mechanically.

The policy files

FileRead it before…
CLAUDE.md / AGENTS.mdanything. Same policy for Claude and Codex; change both in one diff. Covers no fabrication, context compression, model routing, review rules, prod-data boundaries and verification.
guidance/engineering-constraints.mdcode, schema, provider, infra or ops changes: tiers, types, SQL, auth, migrations, logging, deployment
guidance/code-discipline.mdany code change: try/catch only with a job, no invented fallbacks, edge cases need evidence, minimal diffs, formatting, lint ratchets
guidance/type-rules.mdtypes: any banned, unknown boundary-only, as X banned outside as const, per-site // Boundary(<category>): markers
guidance/testing-strategy.mdtests: layers, port fakes over vi.fn(), no mocking connectors, the local static gate
guidance/frontend-conventions.md · observability.md · data-operations.mdweb work · logging/audit decisions · any production data change (rehearse locally first)
guidance/claude-setup.mdsetting up a new machine: the repo-declared MCP servers in .mcp.json (zube-plane, vendored in scripts/mcp/zubePlane, and plane-tasklist), the subagent hook, and the optional context-compress plugin
guidance/epic-design-workflow.md · epic-implementator-workflow.md · task-tracking-workflow.md · local-oneoff-llm-probes.mdbig plans · approved epic execution · Plane tracking · live LLM probes

Agent roles

AgentModel · effortJob
coordinator (main session)Opus · highrequirements, decisions, routing, integration, talking to you
implementer · test-authorOpus · mediumone bounded slice in an assigned file set · failing tests first
reviewerOpus · highfresh, independent slice review, then recheck and approve
final-reviewerOpus · xhighpre-merge review for any cron, webhook or non-webapp change
check-monitor · retriever · mechanical-editorSonnet · mediumrun one bun run check:* and report · read-only sweeping search · fully specified mechanical edits

A PreToolUse hook (.claude/hooks/requireFreshSubagent.ts) denies forked or history-inheriting subagents and any spawn whose model doesn't match its role. Every subagent starts from a self-contained brief. Project skills in .claude/skills/: zube-planning, week-start, create-proposal, zube-demo-org, design-critique, data-design-critique, human-writing.

What the static gates catch

CategoryGates (all in bun run check:static)
Architectureworkspace-import:check (tier DAG), external-boundary:check (provider hosts only in wrappers), sdk:boundary-check, client-boundary:check, structured-output:check, runtime-loader:check, runner:ctx-contract, runner:lane-audit (see Runner), deploy-dependency:check, webhook route factory, UI presentation boundary, knip, manypkg
Type & SQL escapestypes:check + baseline (AST-based), raw-sql:check (query builder unless schema / allowlist / Parity: / Boundary(raw-sql):)
Test hygieneintegration-boundary:check (no mocking internals), test-source-reads:check
Shrink-only ratchetsfile-size:check, duplicates:check (jscpd), duplicate-helpers:check, eslint-suppressions:check, comments:check + baseline, format:check, casing:check, migration-baseline:check, tracked-inputs:check
Ratchets only shrink. Never regenerate a baseline or suppression file to make CI pass. Fix the code, then shrink with bun run lint:prune / types:prune. Watch for agents gaming size gates by packing lines; run prettier before trusting a size gate.

Working rules worth internalising

  • No fabrication. No stubs passed off as done, no invented APIs, env vars, flags or results. If correctness needs an unknown, stop and ask with the exact blocker.
  • Verification is proportional. Run the affected package tests plus lint and typecheck, then bun run check:static on the final candidate. Full checks run only when the owner asks; CI runs them anyway.
  • Review. A fresh reviewer at each behaviour checkpoint. Two reviewers with different lenses for webhooks, workflows, auth, concurrency, prod-data and shared agent-response changes. A fresh xhigh final review before merging any non-webapp change. A blocker needs a location, a violated invariant, a trigger and evidence; an empty blocker list is a successful review.
  • Customer replies are agentic. No canned defaults or string-assembled fallback replies, ever. The planner, finalizer, prompt, graph and reply-adapter are high-impact areas.
  • Production data. Rehearse locally (pull → transform in an isolated DB with side effects off → verify), then apply with explicit authorisation, then re-read. Raw SQL only via prod-db-read/prod-db-write.
  • Tracking and plans. Work expected to exceed about 1,000 lines of production code gets one Plane issue with a task list (the plane-tasklist MCP). Plans are published to the private engineering-plans server with bun run plans:publish, and only on request.
  • Git. Work in the checkout you were started in, and don't switch branches or worktrees unasked. Use the native GitHub integration, not gh. Commit, push, PR and merge each follow their own authorisation.
Evidence
  • CLAUDE.md (sections: No fabrication, Model routing and delegation, Code Review Rules, Operator and product boundaries, Verification and PR delivery)
  • .claude/agents/*.md; .claude/hooks/requireFreshSubagent.ts:1-5; .claude/settings.json:12-19
  • root package.json check:static script (~37 steps)
  • planning_docs/vibe-code-cleanup/index.md:3-53: the smells the ratchets target

Sharp edges & doc drift

Things this pass found that will bite you or mislead an agent. Some are real follow-ups; most are things to know before you trust a comment, a planning doc or a gate. None of them were verified against production.

Sharp edges in the code

#WhatWhy it mattersWhere
1Scan mirrors show only the top workflow envelopeA successor stacked on a parked delayed reply can hide it from the WAKE sweep. Only the first step of the fix shipped.planning_docs/workflow-envelope-scheduler-invariant/design.md
2Migrations are never reversed on rollbackEvery migration must work with the previous image (expand → contract)scripts/deploy/lib/releaseTransaction.ts:1037-1046
3The scheduler relies on in-process singleton guardsRunning two schedulers would double-run crons and email pollscreateScheduler.ts:121-180; emailPollingRunGuards.ts
4Cadence quiet hours: config fields exist but no enforcement was foundDon't promise message windows on WhatsApp/email cadences without checkingoutboundCadenceRegistry.ts:94-116; cadenceStepFailedScheduling.ts:20-34
5voice-post-call has no NOTIFY; a failed enqueue loses the post-callUp to 30 s pickup latency; the stale-call sweep is the backstop0076_pgboss_12_34_0.sql:444; apps/telephony-infra/src/app.ts:91-111
6Voice custom-tool endpoints check only the shared secret and client nameNo org-to-bundle check; worth a deliberate decisioncustomClientTool.ts:126-149
7WhatsApp POST webhooks are unsigned by design (only replays are signed)Intentional per the code comment; the reason isn't statedapps/webhooks/src/inbound/whatsapp/dispatch.ts:15-17
8The per-org llmInferenceRegion is read only by the lead-lifecycle classifierAgentic replies, insights and batches use the global client regardlessconversationClassifier.ts:125-130
9The default agent system prompt hard-codes an education "enrollment advisor" personaNon-education tenants rely on base and node prompts to override itagenticReplyPrompt.ts:17-38
10The Lusha key is decrypted in a composition root, not inside its wrapperDeviates from "wrappers own decrypt"addisonClientRuntimeFactory.ts:252-262
11PROVIDER_HOST_TOKENS misses some hosts used inside connectorsA leak of those hostnames outside the wrappers wouldn't be caughtnoDirectExternalProviderAccess.ts:36-57
12CREATE EXTENSION (vector, hll, pgcrypto) isn't in any migrationA fresh environment needs them provisioned out of bandpackages/db/drizzle/*.sql
13Demo orgs are inferred: "≥1 user and all users inactive"Marking a real customer's only user inactive silently suppresses their escalation emails and CRM taskspackages/services/src/demoAccountPolicy.ts:9-21
14The internal/admin email domains default to getzube.com and zube.aiThe guidance says only @getzube.compackages/config/src/env.ts:10,212-216
15Prod runs Node; dev and tests run Bun/tsxProve runtime-sensitive behaviour under Nodeapps/*/Dockerfile
16In-memory dedupe caches are per processDuring a two-worker overlap each instance can accept a duplicate; receipt and runner guards are the real defencereceiptProcessor.ts:5-7; elevenlabs/eventProcessor.ts:1-15
17No 60-day data-retention purge exists in this checkoutWebhook receipts expire after 14 days, voice-demo usage after 13 months, voice consent detail after 14 days. The embedded-webchat epic assumes a 60-day purge "being built on a separate track"; ask the owner where it lives.searched packages, apps, scripts, planning_docs
18ElevenLabs agents (prompts, tool URLs) are configured outside the repoVoice behaviour changes may need ElevenLabs-side edits that code review never seespackages/ports/src/elevenLabs.ts:250-258 (CRUD unused)
19The RevOps branch removes OpenRouter for Decision-1Merging it without the Azure keys in prod stops escalation Tier 2, lead lifecycle, Lingua campus and the Nexus matcherclaude/revops handoff

Planning docs and comments that lag the code

SourceSaysCode says
magic-booking-linkdraft discovery; no public pageBooking links issued and redeemed end to end
organization-feature-flagsblocked on credentialsFlag table, admin UI and organizationFeatureProcedure exist
workflow-scoped-knowledgedraft, do not implementV1 shape implemented (Foundry "Restrict Nexus to this workflow")
configurable-public-voice-demos · vodafone-call-importproposedBuilt
client-report-generationV1 ships an empty registry4 generators registered
schema-cleanup · vibe-code-cleanupnot merged · no code changes yetMigration 0065 merged · ratchets landed
user_acl slice 9not startedAuto-assignment (round robin / random / LLM) exists
aws-checkremote-paritynot approved; don't run on AWSAWS is the only accepted target
Insights V2, hourly-flex, drop-off, gemini-36 docsGemini 3.6/3.7 on Vertex is primary; drop-off adjudicates four statesGemini tiers run on GPT-6 first; batch is OpenAI-first; drop-off is a deterministic cohort plus a gpt.fast cause/topic
Nexus epicsGemini researcher, per-org nexus_enabled, a Conflicts tabgpt.ultra source memo; on for all text channels except webchat; conflict scan only at ingest
AL UC2 epicthe tick is a disabled shellWired and running (until its scheduled removal)
WhatsApp edit safetyuncommittedMerged
MiCampus SF hardening · Google Ads cadence15/30 min quiet period · first-name checks2 h quiet period · no first-name check
Jev testsLingua trial behind a per-org flagNo flag check on that path; gated only by the hook and the API key
Root README.mdrevival metric fieldsrevival_metrics table dropped (0065)
guidance/engineering-constraints.mdCloud SQL Postgres 16Terraform pins POSTGRES_18 (live value unverified)
guidance/security-scanning.md · Terraform comments · status README release tuplethree services / three containers (api, webhooks, scheduler)Five services
phoneLineDirectory.ts header · Telnyx dispatch comment · "outbound bootstrap" commentsused by api/webhooks · dispatches CALL_ENDED in-process · outbound callsScheduler-only · enqueues voice-post-call · outbound AI calling removed
multi-app-split/worker-split.md2 dispatcher ticks3 ticks + spool drain

Glossary

TermMeaning here
targetOne lead. The durable identity every channel, workflow, CRM link and metric keys off.
business workflow id (targets.workflow_id)A free-text label (default __default__) that selects Foundry templates, client hooks and cadence ownership. It is not a machine.
machineAn XState v5 machine registered in the workflow registry; nine exist.
envelopeThe JSONB in targets.workflow_state: machine id, run id, version, xstate snapshot, nextActionAt, previousState, executionSafety.
tx_finalThe single transaction at the end of a run that commits the snapshot, buffered domain writes, audits, target events and handoff rows.
lane (1–6)The classification of a machine side effect: buffered write, immediate read, immediate RMW, split provider send, bounded actor.
WAKEThe event the 30 s checkAwaitingAction sweep sends to targets whose next_action_at is due.
handoffMachine chaining through a durable workflow_handoff_pending row. Not the same as webchat "continuation".
instant machineA machine that must finish in one dispatch (conversation-complete, CRM sync, call-complete, client successors).
restorePreviousA successor's request to pop the stacked predecessor envelope back.
send-safety hold / executionSafetyA marker committed before a provider send. If an owner dies mid-send, the next owner pauses the target and writes a take-over row instead of resending.
take-over rowThe standard "AI Requested Human Help" activity-log entry (needs_assistance).
system_issueThe audit category for Zube-only faults; diverted to logger.error and never shown to clients.
preHook / postHook / getPostWorkflow / preCrmSyncbackThe typed client hook slots on the runner and the syncback service.
FoundryThe web-app area (and table agentic_messaging_templates) where orgs configure agent templates, graphs and guardrails.
tierA semantic model name (gpt.fast, claude.smart…) resolved to a concrete model in packages/llm/src/models.ts.
Nexus / Nexus 2.0The knowledge base and its full-corpus, evidence-only researcher. Nexus Review is the operator queue of observed knowledge gaps.
Jev / Decision-1The probabilistic decision model (microsoft/microsoft-decision-1). Files still say "jev".
UC1 / UC2Addison Lee's two custom use cases: draft-only inbound prospecting, and a one-off cold outbound campaign (removal scheduled).
workflow-free runtimeThe service runtime used by api, webhooks and telephony-infra: no runner, no machines.
tick lockThe advisory lock that elects which worker runs dispatcher ticks.
receipt / spoolThe raw WhatsApp body stored in webhook_receipts / the raw body written to GCS when DB capture fails.
cadence · kill switchA code-defined outbound sequence run by outbound_messaging_cadence · the per-org outboundCadenceEnabled setting.
continuationThe webchat feature that carries a conversation to WhatsApp or email via a bearer code.
BSUIDWhatsApp's business-scoped user id, used when Meta omits the phone number.
coexistence / SMB echoA WhatsApp Business App linked to the WABA; messages a human sends from the phone app arrive as echoes and flip the target to override.
true admin · personaA logged-in internal-domain human (even while impersonating) · the user an admin is impersonating via x-persona-user-id.
UI 2.0The "New" web UI (ui/new), chosen per user; Classic is the default.
marker (check-full-v2/<sha>)Proof that check:full passed for a SHA or tree; deploys require one.
intelligence-only org · checkpoint runRevOps terms: an org with no channels or CRM link, so pipeline targets never trigger messaging · one pipeline run of one deal at one checkpoint.
case laneThe proposed generic runtime for non-lead workflows (unapproved).

Built on 24 Oct 2026 from parallel read-only code passes over main at 8b358572d, plus the claude/revops branch and three published proposals. Production state (flags enabled, deploys, data) was not inspected. Where this page and the code disagree, the code wins: ask an agent to re-check the cited file:line.