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.
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.
targetstarget_id.packages/llm.The system in 60 seconds
- Ingress apps only capture.
webhooksandtelephony-infraverify 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) - The worker turns jobs into events. It resolves the provider identity to an organisation and a
target, merges the transcript, then callsworkflowRunner.handleEvent(targetId, event). (Queue) - 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) - 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)
- Time is data. Machines never use in-memory timers. They write
next_action_ator pending rows, and scheduler and worker ticks turn those back into events, so restarts and deploys lose nothing. (Timers) - Analysis follows conversation. On completion,
on_conversation_completeextracts 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.mdbefore 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.
What runs where
| Component | Runs on | Port / host | Role |
|---|---|---|---|
| nginx | VM | 80/443 · api, webhooks, link, proposals, status.zube.ai | TLS (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.ai | Express + 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 container | no HTTP · readiness file | The only pg-boss consumer; holds an XState runner; runs dispatcher ticks behind an advisory "tick lock". |
| scheduler (apps/scheduler) | VM container | no HTTP · no healthcheck | 30 Croner jobs, PostHog spend crons, phone-line LISTEN/NOTIFY directory. Holds its own runner. Single instance by design. |
| uptime-kuma | VM, separate Compose project | status.zube.ai | Public status page. Same VM, so it is not independent of a VM outage. |
| Web SPA (apps/web) | Firebase Hosting | app.zube.ai | React SPA; /trpc 307-redirects to api.zube.ai. Also serves magic-link and proposal hosts. |
| Webchat widget | bundled into the webhooks image | /webchat/widget.js | Dependency-light IIFE embed customers drop on their sites. |
| Cloud SQL | GCP managed | private IP (+ an SSL-only public IPv4 with no authorised networks by default); devs via proxy on 127.0.0.1:5433 | System of record + pg-boss schema. Zonal, PITR 30 days. Extensions: pgvector, hll, pgcrypto. |
| Cloud Storage | GCP managed | — | Private CMEK bucket (webhook-spool/, recordings, tmp/llm-batch/, uploads) + public-assets bucket for audio Telnyx fetches. |
| Cloud KMS | GCP managed | — | integration-credentials key wraps every OAuth token/secret; storage-encryption CMEK. 90-day rotation. |
| Firebase Auth / Identity Platform | GCP managed | — | Email-link and password sign-in, optional Google IdP. ID tokens verified in packages/auth. |
| CI/CD + remote checks | AWS EC2 (us-east-1) | SSM-SSH | Self-hosted GitHub Actions runner zube-checkremote; also runs bun run check:*:remote. Idle-reaped. |
Request routing (nginx)
| Host | Path | Upstream | Notes |
|---|---|---|---|
api.zube.ai | / | api:3001 | 30 s read timeout, aligned to tRPC + DB statement timeout (added after a 2026-06 insights freeze) |
testNexusQuery, generateReply, templates.testReply | api | 10 min lane | |
| admin org delete, demo generate, knowledge ingest ops | api | 5 min lane | |
reports.generateReport | api | 75 s lane | |
manualImport.callImport.* | api | 30 min lane (TODO: durable job) | |
webhooks.zube.ai | /webchat/ws | webhooks:3002 | WebSocket upgrade, 20 min read timeout |
/telnyx/ · /voice-tools/ · /client_tools/ | telephony-infra:3002 | path passed unchanged | |
/ | webhooks:3002 | all provider webhooks, OAuth callbacks, widget bundle | |
link.zube.ai | /e/ · / | webhooks · Firebase | email tracking (access log off: tokens in URL) · magic links |
proposals.zube.ai | /api/proposals/ · / | api · Firebase | proposal microsite |
app.zube.ai | all | Firebase Hosting | no nginx block; SPA rewrite |
Constraints you must not break
| Invariant | Why |
|---|---|
| Scheduler is single-instance; deploy stops it, then recreates it | Croner singleton guards one process, not replicas. Scaling out needs leader election (TODO). |
| Two workers may overlap during a deploy | Safe 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 disk | VM disk dies on redeploy; durable state lives in Postgres and GCS. |
All app containers share one ../.env | No 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 temporary | A managed load balancer must precede any multi-VM setup. |
| telephony-infra only redeploys at zero active calls | Call 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 plaintext | Wrappers own decrypt → call → refresh → re-encrypt → persist. |
| Terraform is the source of truth for GCP resources | New resources get Terraform in infrastructure/terraform/. DNS, billing, initial TLS and in-DB grants are not in Terraform. |
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, diskinfrastructure/terraform/database.tf:1-76: Cloud SQL tier, version, PITR, usersapplication/migrationinfrastructure/docker-compose.yml:23-164: the six services, shared env, health checks, stop grace periodsinfrastructure/nginx/nginx.conf:13-20,139-399: variable upstreams, per-procedure timeout lanes, host blocksapps/web/firebase.json:1-53,infrastructure/terraform/firebase.tf: SPA hosting and/trpcredirectinfrastructure/terraform/kms.tf,storage.tf:1-229,identity-platform.tf:1-63scripts/checkremote/run.ts:167-176,scripts/checkremote/ciRecovery.ts:7-9: AWS EC2 runner and remote checksguidance/engineering-constraints.md:95-107: topology and single-instance constraintspackages/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.
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
| Path | What's in it | Touch it when… |
|---|---|---|
apps/api | Express + tRPC (21 routers), procedure ladder (publicProcedure → trueAdminProcedure), proposals REST | adding a web-app endpoint |
apps/webhooks · packages/inbound-http | provider ingress via the createInboundRoute factory, OAuth callbacks, webchat WS | a new provider webhook or callback |
apps/telephony-infra | Telnyx call control, ElevenLabs server tools, transfer logic, in-memory call state | voice behaviour during a call |
apps/worker | pg-boss consumers (inbound-event, voice-post-call, manual-import, agent-preview), per-channel inbound processors, dispatcher ticks | how an inbound job becomes a workflow event |
apps/scheduler · packages/services/src/scheduler | cron registry + every job body; Addison Lee runtime composition | anything periodic |
packages/workflows | XState machines, the runner, registries, client hooks (src/clients/<client>/), cadence configs, safeguards | workflow behaviour |
packages/llm | LlmClient, model tiers, agentic graph (planner/tool/finalizer), prompts, Nexus researcher, batch, embeddings, decision models | any LLM call or prompt |
packages/services | domain 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/db | Drizzle schema (source of truth), numbered SQL migrations (0000–0097), pg-boss wrapper, demo seeding | schema changes (bun run db:generate) |
packages/external-connectors/* | provider wrappers: crm, email, calendars, meta, telnyx, voice, contact-center, prospecting, client-custom, shared | calling any third party |
packages/client-tools | per-client AI-callable tools, report metadata, calendar params (workflow-free) | a client-specific agent tool |
packages/app-composition · workflow-composition | env → runtime inputs, wrapper factories, reply senders · runner-holding runtime + default machine registration | wiring a new adapter |
packages/webapp-contracts | hand-written tRPC I/O types and DTOs; the only backend types the web app may import | changing an API shape |
apps/web | Vite + 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-offs | tooling |
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:
- Port the service sees:
HubspotWrapperPort extends CrmWrapperPort, CrmIdentityReconciliationPort. The service gets a factoryBuildHubspotWrapper = (integration) => HubspotWrapperPort, a callback "so orchestrator tests can inject scripted wrappers". - Ports the adapter needs:
IntegrationRepositoryPort(persist rotated tokens, markauth_error),AuthFailurePort,CryptoPort(KMS). - Adapter:
HubspotWrapper extends CrmWrapperowns decrypt → request → reactive 401 → singleflight refresh → re-read latest credentials → persist → retry once → flip toauth_error. - Composition:
buildCrmWrapperFactoriesinapp-compositionbuilds the closures. The worker gets them viabuildDefaultRuntimeWithCrmFactories; 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 banspackages/services/src/crmWorkflows/armDeps.ts:227-238: factory-type injectionpackages/external-connectors/crm/src/wrapper.ts:293-414: reactive refresh looppackages/app-composition/src/crmWrapperFactories.ts:45-122: composition of wrapper factoriespackages/app-composition/src/workflowFreeRuntime.ts:8-15;packages/workflow-composition/src/defaultRuntime.ts:32-78packages/workflows/src/registry/expectedRegistrations.ts:30-113: boot-time registration assertionsapps/api/src/trpc/router.ts:24-52,apps/api/src/trpc/trpc.ts:230-425: routers and procedure ladderguidance/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.
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)
- Raw body (413 above 2 MiB) and operation context.
- Verify. An invalid signature gets a silent 200, or a 401 for Telnyx. ElevenLabs alone proceeds on a bad signature (legacy parity).
beforeParsedurable work, parse, optional in-memory dedup (Telnyx).- 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. - Ack
200 {status:'ok'}. - Optional background handler after the ack (Telnyx). Errors are logged, never retried.
Inline path (WhatsApp POST, Meta GET handshakes, voice tools, PostHog alerts)
- Raw body and context. An invalid verify throws
HttpError(401). - Spooling capture budget starts;
beforeParseruns inside it (WhatsApp: insertwebhook_receiptswith raw text + sha256). - Parse. A failure returns
parseFailureStatus(WhatsApp: 503 so Meta retries). - The handler runs inside the same budget (WhatsApp: enqueue
{source:'whatsapp', receiptId}). - 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
| Path | Provider | Verification | What it does |
|---|---|---|---|
POST /whatsapp/event | Meta WhatsApp | None 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/event | Meta | HMAC-SHA256 with app secret, strict | Enqueue raw payload with deterministic job id uuidv5(source:sha256(body)) |
GET /{whatsapp,messenger,instagram}/event | Meta | verify-token handshake | Echo hub.challenge |
POST /elevenlabs/event | ElevenLabs post-call | HMAC, 30 min tolerance; proceeds on a bad signature | Persist knowledge-query capture (valid signature only), enqueue inbound-event |
POST /posthog/error-tracking-alerts | PostHog | Bearer HMAC | Urgent system-issue email via SES (ignores advisory-lock noise) |
/e/o/:token.gif · /e/c/:token · /e/u/:token | Zube email tracking | token hash lookup | Open pixel, click redirect, unsubscribe |
GET /callbacks/{hubspot, salesforce, monday, microsoft-dynamics, calendly, microsoft-calendar, microsoft-teams, microsoft-sharepoint, google-email, microsoft-email} | OAuth | signed callback state | Exchange code, KMS-encrypt tokens, upsert integrations row |
GET /callbacks/meta-messaging/ · /callbacks/whatsapp-business-app/ | Meta connect | signed state | Page/IG subscribe; WhatsApp Embedded Signup (business token, no refresh) |
ALL /callbacks/custom/addisonlee/zoominfo | custom | none | Returns 204 and does nothing (stub) |
/webchat/{widget.js, config, session, transcript} + WS /webchat/ws | Zube webchat | origin allowlist, 15 min HMAC session token | Widget bundle, config, session mint, transcript replay, turns over WebSocket |
emailPollingSyncer, every 2 min), and CRMs are pulled every 3 min (crmSyncer). The Telnyx SMS client exists but has no consumer.telephony-infra routes
| Path | Caller | Auth | What it does |
|---|---|---|---|
POST /telnyx/event | Telnyx Call Control v2 | ed25519, 300 s tolerance, 401 on failure | Ack, 3-tier in-memory dedup, switch over 13 event types (background) |
POST /voice-tools/elevenlabs/inbound_call_init | ElevenLabs | Basic auth elevenlabs:<secret>, fail-closed | First message + dynamic variables for the caller |
POST /voice-tools/elevenlabs/calendar_{list_slots,create_booking} | ElevenLabs tool | same | Calendar tool service (Calendly / Microsoft) |
POST /voice-tools/telnyx/{transfer_to_human, check_transfer_availability} | ElevenLabs tool | same | Hours/rules gates, LLM destination pick, blind transfer |
POST /voice-tools/elevenlabs/custom/:client/:fn · legacy /client_tools/:client/:fn | ElevenLabs tool | same (shared secret; no org check) | Dispatch to packages/client-tools per-client tool |
GET /ready | deploy | — | DB check + activeCalls (deploy gate) |
The handoff contract (pg-boss payloads)
| Source | Queue · payload | Job id |
|---|---|---|
inbound-event {source:'whatsapp', receiptId} | generated (dedupe happens on the receipt) | |
| Messenger / Instagram | inbound-event {source, payload} | uuidv5 of body sha; JobAlreadyExistsError swallowed |
| ElevenLabs post-call | inbound-event {source:'elevenlabs', payload} | none |
| Webchat turn | inbound-event {source:'webchat', turn}, priority live, group per visitor | uuidv5(widget, visitor, messageId), sent in the same tx as the outcome row |
| Telnyx recording | voice-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_idmaps to anintegrationsrow, giving the org, and the sender becomesresolveOrCreateWhatsAppTarget(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 byreferenceCallId, 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
workflowIdfrom the target,applyInboundEndpointWorkflowRoutingrepoints the target (unless it is paused or overridden).
Webchat transport
- 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). - On each frame, webhooks rate-limits (10/min per session, 30/min per IP), inserts a pending
webchat_turn_outcomesrow and the pg-boss job in one transaction, then acks the frame. A failure returns a protocol error, never assistant text. - The worker runs the text machine (no batching park for webchat), writes the outcome, and NOTIFYs
webchat_turn_outcome. - 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-calljob. - Capture before ack, spool as last resort, so a DB outage never turns into Meta retry storms or lost messages. The worker's
webhookSpoolDrainTickre-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 pathsscripts/grep-gates/webhooksRouteFactory.ts:44-59,125-135: route gate (narrower than its header claims; routers outsideinbound/are not gated)apps/webhooks/src/inbound/whatsapp/dispatch.ts:15-17,54-75,91-147: unsigned POST, replay auth, receipt + enqueueapps/webhooks/src/app.ts:110-202;apps/telephony-infra/src/app.ts:117-256: route mountspackages/db/src/jobQueue/payloads.ts:3-81;inboundEventJobId.ts:5-17: payload contract and job idsapps/worker/src/inbound/whatsapp/events/messages/index.ts:832-870: org + target resolutionapps/telephony-infra/src/inbound/telnyx/internal/inboundDidResolver.ts:86-121,ensureInboundConversation.ts:1-157apps/webhooks/src/webchat/enqueueTurn.ts:58-84,frameHandler.ts:308-362,continuationBridge.ts:1-11,turnDelivery.ts:1-25apps/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
| Queue | Producer | Consumer (worker) | Settings | Purpose |
|---|---|---|---|---|
inbound-event | webhooks (WhatsApp, Messenger, Instagram, ElevenLabs, webchat); worker spool drain | createInboundEventConsumer → per-source processor | two subscriptions: general (concurrency 20) + live tier (priority ≥10, concurrency 2); groupConcurrency 1; retry ≤8 with backoff ≤300 s; expire 900 s; 5 s poll backstop | all inbound messaging + webchat turns |
voice-post-call | telephony-infra after recording saved | createVoicePostCallConsumer | concurrency 4; expire 3600 s; no NOTIFY, so pickup can wait up to the 30 s poll | transcript → persist → CALL_ENDED |
manual-import | api (lead CSV/XLSX import), same tx as batch rows | batch processor under a per-batch advisory lock | concurrency 2; heartbeat 30 s; retry 3; pg-boss failures resume | ≤100 rows per batch, processed in order |
agent-preview | api (template test reply, conversation "Generate reply") | createAgentPreviewConsumer | concurrency 4; expire 300 s; retry 1 | effects-free reply previews polled by the UI |
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
- Remove the stale readiness marker, then build composition and consumers first, so a runtime without a runner fails boot before it connects.
- Create the pg-boss client and the tick lock, a session
pg_try_advisory_lockonzube:dispatcher-ticks. Only the holder runs ticks, and only whenSCHEDULER_ENABLED=true. - Register consumers last, so a startup throw can't strand fetched jobs. Then write
/tmp/zube-worker-ready. - 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)
| Tick | Every | Claims | Dispatches |
|---|---|---|---|
handoffDispatcherTick | 15 s | due workflow_handoff_pending ids (SKIP LOCKED), 600 s in-flight janitor | runner.runPendingHandoff: the crash-recovery path for machine chaining |
targetEventDispatcherTick | 15 s | target_workflow_event_pending | TARGET_EVENT_DISPATCHED (today: cadence_step_failed) |
pendingTextDispatcherTick | 15 s | due pending_text_events grouped by target | drainPendingTextEvent + send reply |
webhookSpoolDrainTick | 30 s | GCS 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.
| Job | Schedule | What it does | Gate / note |
|---|---|---|---|
checkAwaitingAction | every 30 s | The WAKE sweep: targets awaiting_action_from_target plus due active text targets → WAKE → send reply | core timer mechanism |
checkStaleConversations | every 5 min | force-complete stale voice calls → CALL_ENDED | recovery for busy post-call |
emailPollingSyncer | every 2 min | poll each Google/Microsoft mailbox → relevance gate (EU Bedrock) → MESSAGE_RECEIVED → reply | non-singleton; per-mailbox in-process guard |
emailCrmSyncer | every 5 min | poll crm@getzube.com, map sender domain → org, LLM-parse contacts → CRM-sync per contact | Stay Club / Road Scholar style CRM-by-email |
crmSyncer | every 3 min | pull HubSpot / Salesforce / Dynamics / Freshsales / monday deltas → CRM_RECORD_RECEIVED | needs KMS + wrapper factories |
crmSyncbacker | every 3 min (+2) | write Zube target fields back to HubSpot / Salesforce / Dynamics (no Freshsales syncback) | interruptible |
crmEscalationTaskReconciler | every 5 min | mark expired CRM escalation-task reservations for reconciliation | no provider calls |
rebuildCrmConversionProjections | every 10 min + startup | repair/refresh conversion read models | feeds Conversion insights |
bootstrapSalesMotionCrmOutcomes | every minute | backfill canonical CRM outcome observations | |
historySyncResumer | hourly + startup | resume stalled email / Messenger / Instagram history syncs | |
aggregateInsights | daily 12:05 | per-org daily metrics + LLM-normalised content insights + daily loss generation; voice-privacy retention first | needs LLM |
aggregateMonthlyInsights | 1st of month 13:00 | monthly rollups from daily rows (HLL unions) | |
curateContentInsights | fortnightly Sun 04:00 + startup | rename/merge category catalogs on gpt.ultra | interruptible |
processDeferredConversationAnalyses | :05 and :35 | half-hour batch: sentiment + custom analyzers | non-singleton; OpenAI-first batch |
reconcileSalesMotionObservations | daily 02:15 | enqueue the 48–72 h drop-off cohort (deterministic) | |
processSalesMotionObservations | every minute | LLM drop-off cause/topic per claimed observation | surfaced admin-only |
processDueReminders | hourly | LLM-validate and dispose due reminders; escalation routing | |
processDueReports | every minute | janitor → due scan → generate → store → email client reports | 4 client generators |
knowledgeDeletionTick | every 15 s | Nexus hard delete (GCS, then rows) + ingest staging cleanup | |
knowledgeQueryDiagnostics | hourly | observed knowledge gaps → findings for Nexus Review | |
nexusTaxonomyWeekly | Sun 04:00 London | bootstrap catalogs / weekly matching of findings | flag nexus_taxonomy |
nexusTaxonomyPoller | every 15 min | collect batch results, publish validated rows | flag nexus_taxonomy |
webchatIdleFinalize | every minute | close idle webchats; substantive ones get on_conversation_complete | |
jobQueueHealthMonitor | every minute | queue wait p95 breaches, recent failures, reconcile stuck webchat turns / dead imports / expired previews | silent-drop detection |
webhookReceiptMonitor | hourly | email overdue WhatsApp receipts (30 min grace), daily digest, delete expired receipts (14 d) | needs SES |
publicVoiceDemoUsageRetention | daily 00:00 | prune demo usage receipts older than 13 months | |
telnyxCostRollup | every 3 h | Telnyx CDRs → PostHog vendor_usage_recorded (org via phone-line directory) | POSTHOG_ENABLED |
elevenLabsCostRollup | every 3 h | per-call ElevenLabs cost → PostHog | POSTHOG_ENABLED |
elevenLabsRateRefresher | Mon 04:00 | re-stamp the hard-coded credit→USD rate | POSTHOG_ENABLED; directional, not billing-grade |
clientOutboundTick | every 30 s + startup | Addison Lee UC2 media-production outbound campaign tick | custom: 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)
| Pattern | Where | Protects |
|---|---|---|
| Per-target session advisory lock on a reserved connection | workflow runner | one 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 ticks | one tick runner during overlap deploys |
FOR UPDATE SKIP LOCKED claim + in-flight TTL janitor | handoffs, target events, reminders, observations, taxonomy runs | no double processing; stranded rows return after 600 s / 30 min |
| Claim owned by the runner, not the dispatcher | handoff dispatch | one 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 key | on_conversation_complete per conversationId | a burst of turns queues one follow-up, not N (this was the cause of lock-timeout storms) |
| Tx-scoped advisory locks on identity hashes | target merge/create, CRM identity, webchat codes | concurrent events for one phone/email converge on one target |
| Deterministic job ids + transactional enqueue | ingress, imports, previews, spool drain | redeliveries never duplicate; rows and jobs commit together |
| In-process guards | scheduler singleton, email poll guard, dedupe caches | valid only because the scheduler is single-instance |
Evidence
packages/db/src/jobQueue/pgBossJobQueue.ts:36-302: wrapper, concurrency, settlement, retry policypackages/db/drizzle/0076_pgboss_12_34_0.sql:442-444,0083_phase2_worker_split_queues.sql:8-10: queue DDLapps/worker/src/workerProcess.ts:48-216: boot and shutdown orderpackages/services/src/scheduler/registry.ts:53-95: crons and dispatcher tickspackages/services/src/scheduler/createScheduler.ts:63-349: singleton semantics,runOnStartup, anchored intervals, stoppackages/workflows/src/runner/advisoryLock.ts:1-65,247-334;handoffDispatcher.ts:5-157;workflowRunnerTxFinal.ts:539-580packages/db/src/phoneLineDirectory.ts:15-35,239-309;apps/scheduler/src/tasks/postHogSpendWiring.ts:96-157planning_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.
targets.workflow_statemachineId, workflowRunId, version, xstate persisted snapshot, nextActionAt, previousState stack, optional executionSafety. No runs table.workflow_status · next_action_atpackages/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 Xis allowed only insidesetup({ 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
nowor an injected clock: noDate.now(), nonew Date(), noafter:. actor.sendis allowed only indispatchUntilSettled.tsandmachines/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
versionandmigrations[]. Every machine is at v1 today, and a snapshot from a newer version throws.
Lanes: how side effects are classified
| Lane | Tag / primitive | Semantics |
|---|---|---|
| 1 | @runnerPlanAndBuffer / planAndBuffer | Buffered write, flushed inside tx_final. Replay-safe through a deterministic id + ON CONFLICT. The machine gets a synthesised DOMAIN_RESULT. |
| 2 | @runnerImmediate | Short reads. |
| 3 | @runnerImmediateRMW | Short read-modify-write that commits before tx_final and must be self-idempotent. Allowlisted to four methods: atomicMergeTranscript, persistAgentReplyIfStillLatest, mergeAdditionalInformation, createStub. |
| 4 | split-transaction provider send | Cadence stage sends, executed by the runner, with results fed back as PROVIDER_RESULT/PROVIDER_FAILED. |
| 6 | createBoundedPromiseActor | LLM calls and read-only lookups as invoked child actors with deadlines. |
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
| Source | Event | Path |
|---|---|---|
| Inbound WhatsApp / Messenger / IG / email / webchat | MESSAGE_RECEIVED | worker consumer or email poller → handleEvent |
| Voice outcome | CALL_ENDED | voice-post-call job · ElevenLabs post-call · stale-call sweep |
| CRM record | CRM_RECORD_RECEIVED | crmSyncer/emailCrmSyncer on a freshly minted bootstrap id (the machine swaps the lock to the real target) |
| Timer | WAKE | checkAwaitingAction every 30 s |
| Machine chaining | HANDOFF_DELIVERY → successor's first run-initiating event | eager post-commit run, else handoffDispatcherTick |
| Cross-machine signal | TARGET_EVENT_DISPATCHED → e.g. STEP_FAILED | targetEventDispatcherTick |
| Deferred text | spooled MESSAGE_RECEIVED | pendingTextDispatcherTick |
| Operator action | none | apps/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.
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.
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)
| Rule | Reason |
|---|---|
A session advisory lock, not FOR UPDATE, serialises a target | It 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 pool | A 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 effects | The durable guard must see the actor's genuine initial snapshot. |
| Handoffs are durable rows; eager delivery is only a latency optimisation | The 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 table | Reaching into another machine's envelope "breaks encapsulation". |
| The registered set is boot-asserted against a literal list | A lost registration fails boot instead of silently dropping runs. |
| Replies are sent by the caller after commit, after a staleness claim | claimLatestZubeTranscriptReplyForSend checks that the reply still answers the latest user message. |
| The runner is closed for extension | New 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:
| Model | Mechanism | XState? |
|---|---|---|
| Addison Lee UC1 continuation | preHook consume + detached continuation under the runner's lease (60 min ceiling) | no (runs under the lead runner's lease) |
| Addison Lee UC2 tick | 30 s cron, DB-backed claim of due actions | no |
| Client reports | processDueReports: CAS on next_run_at, janitor, report_runs | no |
| CRM syncback | per-org orchestrator cron with preCrmSyncback hooks | no |
| Agent preview | pg-boss job → adapter preview surface | no runner |
| RevOps checkpoint runs branch | revops-run queue, own claim/lease/heartbeat, in-memory actor run to completion | yes, 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 pointspackages/workflows/src/runner/workflowRunnerExecutor.ts:116-929: admission, hold check, resolve, hooks, dispatch, tx_final, post-commitpackages/workflows/src/runner/workflowRunnerSettledSnapshot.ts:14-39: output before stoppackages/workflows/src/runner/snapshotCodec.ts:53-150: envelope validation and migrationspackages/db/src/schema/targets.ts:122-206,296-300,397-405: envelope schema and scan indexpackages/workflows/src/machines/shared/actions.ts:1-142,actors.ts:1-132: lanesscripts/grep-gates/runnerLaneAudit.ts:2-72,285: lane rules and scan globspackages/repositories/src/workflowExecutionSafety.ts:18-275;workflowRunnerActorProtection.ts:183-258: send-safety holdpackages/workflows/src/runner/workflowRunnerEnvelope.ts:15-248: status derivation, restore-previousplanning_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.
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
| machineId | Status | Purpose | Key states | Starts on | Flags |
|---|---|---|---|---|---|
on_text_message_received | GA | Inbound 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} → finalSendChecks | MESSAGE_RECEIVED, WAKE | statusOnWake active; batching delay 180 s text / 600 s email unless configured; webchat never parks |
on_call_complete | GA | Finalise a voice call: short vs valid, classification, not-interested write. On failure, signals cadence_step_failed to a sibling cadence. | loadingConversation → classifyShortCall → invokingClassifier → short/validCallTerminalEmit | CALL_ENDED | instant |
on_conversation_complete | GA | Post-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 → translateTranscript | handoff from text / call machines | instant; coalesced per conversationId |
on_crm_sync | GA | Resolve 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 → … → applyingHookGates | CRM_RECORD_RECEIVED (also used by manual import) | instant |
outbound_messaging_cadence | GA machine reached via client hooks | A pure transducer for multi-stage outbound WhatsApp-template and email cadences. The runner does the scheduling maths, safeguards and provider sends. | START → CALLING → COMPLETED | CADENCE_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_complete | custom: Lingua | Send the templated post-conversation email (campus, language), then restore the predecessor. | idle → delivering → done | Lingua getPostWorkflow on conversation-complete | instant, restorePrevious |
stay_club_crm_requested_viewing_booking | custom: Stay Club | Book a CRM-requested viewing via calendar tools; confirmed / unavailable / clarification emails; may hand off to a cadence. | idle → delivering → done | Stay Club getPostWorkflow on CRM sync | instant; successor: cadence |
micampus_call_complete | custom: MiCampus | After a MiCampus call: LLM booking extraction (confidence floor 70), WhatsApp template follow-up, per-residence booking-info emails. | idle → delivering → done | MiCampus getPostWorkflow (prod + internal test org) | instant |
micampus_outbound_whatsapp_dry_run | custom: MiCampus dormant | Internal-only observation cadence with no provider ports: it validates the handoff and restores. It was used before the live MiCampus cadence launched. | idle → done | nothing in code hands off to it any more | instant |
"Workflows" that are not machines
| Thing | What it is | Status |
|---|---|---|
| Outbound cadence configs | Zod-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 hooks | preHook (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 UC1 | preHook 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 lease | custom: Addison Lee, scheduler only |
| Addison Lee UC2 | campaign-reply preHook + 30 s cron for a one-off cold outbound campaign | custom: Addison Lee removal scheduled late Nov 2026 |
on_crm_syncback | a hook key used by the non-XState syncback service | GA service |
workflow_outbox | table retained after outbound customer webhooks were deleted | legacy, 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_idis 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 hastemplateKindtext|voice. Text templates require a persistedgraphDefinition; voice templates forbid one and point at an ElevenLabsexternalAgentId. Templates also carrychannelScope,workflowId,guardrails[], fast-reply settings,disableHumanHandoff,restrictKnowledgeToWorkflowOnlyand status draft|active|inactive. Inside a run,resolveAgenticTemplatepicks 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}ResponseDelaySecondsor a per-target override.
Evidence
packages/workflows/src/registerDefaultMachines.ts:186-303;packages/workflow-composition/src/defaultMachines.ts:27-90packages/workflows/src/clients/registerClients.ts:62-167,176-542: expected machine ids, hook keys, client successors, cadence registrypackages/workflows/src/runner/workflowRunnerResolution.ts:153-183: event → machinepackages/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-998packages/workflows/src/clients/micampus/cadences/outboundDryRunCadence.ts:7-78: dormant dry runpackages/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-243packages/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.
The reply pipeline, step by step
- The machine reaches
invokeAgenticReplyinon_text_message_received, after the permission, transcript and batching steps. It invokesgenerateAgenticReply, a bounded actor (600 s) built bybuildGenerateAgenticReply(packages/workflows/src/defaults/agenticReplyAdapter.ts). The agentic graph is the only reply path; legacy non-agentic paths were removed. - Template gate. With no active template or graph, the result is
no_response_needed, treated as a config issue already reported upstream. - 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. - Webchat fast path. On
web_chat, a singlegenerateObject(default tiergpt.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. - 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". - 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. - 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,suppressUnusableReplysetsshouldRespond=false, escalateToHuman=true. - Adapter post-processing. The whole graph is never retried, because tools may already have acted.
shouldRespondwith an empty message becomes an escalation. The result'scompletionReasonis one ofresponded·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. - Machine post-steps. A deterministic guardrail hit count (3-day lookback per
guardrailId), thenpersistAgentReplyIfStillLatest(rejects a stale basis), thenfinalSendChecks(re-reads status; override, help_needed or paused blocks the send). The caller sends after commit.
Tools the agent can call
| Tool key | Effect | Notes |
|---|---|---|
knowledge_search_rag (+ typo alias knowledge_serach_rag) · knowledge_get_full_context | read | On 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_availabilities | read | Calendly / Microsoft calendar slots, shared with the voice tool service |
calendar_create_booking | write, non-repeatable | 240 s timeout; cross-process slot lock |
calendar_get_booking_link | write | Issues a 7-day magic booking link |
internal_escalate_to_human | write | Always allowed |
| Client custom tools | per tool | MiCampus 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
| Tier | Provider · model | Effort | Typical use |
|---|---|---|---|
gpt.ultra | OpenAI · gpt-6.1-sol | high | Nexus source-memo researcher, content-insight curation, demo draft generator |
gpt.smart | OpenAI · gpt-6-luna | high | finalizer, Call Insights, multimodal analysis, tool selection, image OCR |
gpt.fast | OpenAI · gpt-6-luna | low | classifiers, reminders, client semantic routing, drop-off explanation, lead assignment |
gpt.nano | OpenAI · gpt-6-luna | none | webchat one-call fast path, calendar param normalisation |
gemini.smart/fast/nano | Vertex · gemini-3.8-flash | medium/low thinking | Rewritten to gpt.* on the first attempt (except video); Gemini becomes the fallback |
claude.smart/fast/nano | Bedrock · us.anthropic.claude-sonnet-5 (one model, three efforts) | high/medium/low | structured-output fallback; eu. prefix when the AWS region is EU |
- Residency-pinned clients.
buildRegionalInferenceLlmClientservesgb(Bedrock eu-west-2, Sonnet 4.6 / Opus 4.6: Addison Lee pipeline) andeu(eu.anthropic.claude-sonnet-5-5: the email relevance/spam gate for every tenant), with no cross-provider fallback. The per-orgllmInferenceRegionsetting 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-1via 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 OpenAIgpt-4o-mini-transcribe) for audio; OpenAIweb_searchwith a Gemini grounding fallback; OpenAI batch first and Vertex batch as fallback for scheduler batch work.
Client mechanics worth knowing
| Concern | Behaviour |
|---|---|
| Structured output | Callers 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 & fallback | The 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. |
| Cancellation | Every 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 caching | Opt-in Bedrock cache points exist in the client, but no production caller uses them yet. |
| Evals | Only 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 in | Features (tier) |
|---|---|
on_conversation_complete | Call 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 machine | inbound media: audio, image, document (gpt.smart); video (gemini.smart, no fallback) |
| voice | inbound call dynamic variables · call result classification · transfer destination matcher (gpt.fast) · imported-call speaker attribution (gpt.smart) |
| cadences | email stage content (persisted tier, default gpt.fast) · WhatsApp stage template selection |
| client hooks | Stay Club cadence selection and booking extraction, Lingua email routing / CRM fields / campus, MiCampus call-complete extraction (gpt.fast + Decision-1) |
| api | Foundry graph generation (gpt.smart) · public voice demo draft (gpt.ultra) · Nexus ingest curation · Test Nexus |
| scheduler | content 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 notespackages/llm/src/clientGeneration.ts:146-153,494-498;structuredOutputFallbacks.ts:4-17;providerRetry.ts:18-121packages/llm/src/regionalInference.ts:18-124;packages/services/src/insights/leadLifecycle/conversationClassifier.ts:125-130packages/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-27packages/workflows/src/defaults/agenticReplyAdapter.ts:114-984: context, tool binding, outcomespackages/llm/src/agentic/builtInToolCatalog.ts:26-170;packages/client-tools/src/tools/clientVoiceTools.ts:54-130packages/workflows/src/machines/textMessageGuardrails.ts:23-569: deterministic guardrail countingscripts/grep-gates/structuredOutputBoundary.ts:1-58;packages/llm/src/openAiStrictSchemaTransform.ts:1-440packages/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.
apps/api).Components and responsibilities
| Piece | Owns |
|---|---|
| Telnyx | PSTN legs, answer/gather/playback/record, SIP dial, transfer, bridge, conferences; ed25519-signed webhooks; CDRs for cost rollups |
telephony-infra | DID → 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 agent | The 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 tools | inbound_call_init (first message + dynamic variables, partly LLM-filled), calendar list/book, transfer tools, custom client tools. Basic auth with a shared secret. |
| worker | voice-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). |
| Machines | on_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
transferCallruns 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_ENDEDitself only for calls Telnyx didn't route.
What voice does not do
| Capability | Status | Detail |
|---|---|---|
| Outbound AI calls to leads | removed | Removed 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 calls | not built | Voice knowledge is whatever ElevenLabs retrieves from the synced KB folder. Workflow-scoped knowledge doesn't reach voice. |
| Native realtime audio (OpenAI Realtime / Gemini Live) | planned | planning_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 detection | planned | Research only, off-repo (per owner notes, not verifiable from the repo). |
| Imported calls (Vodafone OneNet) | platform code built for MiCampus | Zip upload → mono diarised STT → LLM speaker attribution → completed voice conversation. Backfill only: no workflows fire. See Channels. |
| NICE CXone | partial | Connect and settings only; no call sync job. |
| Public website voice demos | admin-managed | Browser 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 switchapps/telephony-infra/src/inbound/telnyx/events/callInitiated.ts:66-226,callAnswered.ts:1-446,internal/dialElevenLabs.ts:10-210,internal/elevenLabsSipUri.ts:3-45apps/telephony-infra/src/inbound/telnyx/state/callState.ts:14-37,stateStore.ts:1-36: in-memory stateapps/telephony-infra/src/inbound/telnyx/internal/transferSequence.ts:1-333,toolCalls/transferToHuman.ts:1-91apps/telephony-infra/src/app.ts:78-115,146-161:/readyactive calls, voice-post-call enqueueapps/worker/src/inbound/telnyx/internal/processRecordingTranscript.ts:109-166,recordingCompletion.ts:110-186apps/worker/src/inbound/elevenlabs/eventProcessor.ts:1-15,775: skip when Telnyx owns the callpackages/ports/src/elevenLabs.ts:250-258: agent CRUD with no production callerplanning_docs/multi-app-split/worker-split.md:7,27; commit2b5147e32: outbound AI calling removedpackages/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.
target_id. Automated writers may fill only blank identity fields.Schema by domain
| Domain | Key tables | Notes |
|---|---|---|
| Tenancy & access | organizations, users, user_groups, organization_feature_flags, customer_change_requests | Org settings live in JSONB columns. Feature flags are per-org booleans by key. |
| Lead identity | targets, target_assignment_events, target_lifecycle_stages | WhatsApp 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. |
| Conversations | conversations, pending_text_events, webchat_turn_outcomes, email_tracking_events, sentiment_analysis_observations, file_storage | channel_type: voice, zube, sms, whatsapp, email, web_chat, messenger, instagram. Transcript messages carry source, provider ids, delivery status, edit history, generatedReplyBasis. |
| Workflows & templates | agentic_messaging_templates, workflow_handoff_pending, target_workflow_event_pending, agent_preview_runs, workflow_outbox (unused) | Workflow state itself is on targets. |
| Integrations | integrations, monday_oauth_app | 18 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 sync | crm_sync_states (lanes: target_property, conversation_artifact, outcome_read, field_provisioning, pull_retry), snapshots, ledgers, field verification, outcome configs/observations, stage measurements, conversion projections | Outcome configs are immutable epochs; observations are change-only; projections are rebuildable read models. |
| Bookings | calendar_booking_slot_locks, magic_links, magic_links_daily_metrics | No bookings/appointments table; booking truth is still targets.callBooked (calendar-booking-truth is planned). |
| Audit & reminders | audit_trail, reminders, notification_cooldown_ledger | system_issue rows are diverted to logger.error instead of being stored. |
| Insights | daily_metrics, daily/monthly content insights, content_insight_facts, insight_categories, curation state, drop-off/loss/lifecycle/sales-motion observations, 8 historical_regeneration_* tables | HLL sketches for unique counts; HMAC pseudo-ids in facts. See Intelligence. |
| Knowledge | knowledge_documents, knowledge_chunks, ingest sessions/sources/candidates, corpus revisions, query observations, gap findings/occurrences, 12 taxonomy tables | See Nexus. |
| Jobs & ingress | pgboss.* (migrations 0076/0083, not modelled by Drizzle), manual_import_batches/_rows, scheduler_checkpoints, webhook_receipts (14 d expiry, PII) | |
| Reports · proposals · demos · RevOps | report_definitions/report_runs · client_proposals/_accesses · public_voice_demo* · revops_deals, revops_deal_targets, revops_conversations, revops_deal_days | Proposals and demo tables are global (no org). |
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/*)
| Package | Providers | Capabilities | Auth |
|---|---|---|---|
| crm | HubSpot · Salesforce · Dynamics 365 · Freshsales · monday.com | upsert/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) |
Gmail · Microsoft Graph mail · Gmail service account (crm@getzube.com) | list/get, send, reply, draft, forward, delta (Microsoft) | delegated OAuth + reactive refresh; mismatch guard | |
| calendars | Calendly · Microsoft Graph calendar | slots, booking, event types, scheduling links | OAuth + KMS. No Google Calendar. |
| meta | WhatsApp Business (Cloud API, Embedded Signup, coexistence) · Messenger · Instagram | send, media, templates, webhook verification, WABA admin, history sync | Tech Provider business token, no refresh; 401/403 → auth_error, operator re-onboards |
| telnyx | Call Control · Messaging (SMS, unused) | call legs, SIP dial, transfer, conferences, CDRs | platform key from env |
| voice | ElevenLabs · Retell | conversations, transcripts, recordings, KB docs, agent CRUD (unused) · Retell web calls for demos | platform key · KMS envelope for Retell |
| contact-center | NICE CXone | read-only: token exchange, completed contacts, routing options | KMS access key |
| prospecting | Lusha | lookalikes, decision makers, email reveals | custom_secret (decrypted in the scheduler composition root; a deviation from "wrappers own decrypt") |
| client-custom | ZoomInfo (Addison Lee only) | search, enrich, lookalikes, usage | custom_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 everylogger.errorto 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 invariantspackages/db/src/schema/targets.ts:80-405,conversations.ts:22-673,integrations.ts:419-695,integrationCredentials.ts:4-216packages/db/src/schema/knowledgeEmbeddings.ts:4-18: halfvec cast for 3072 dimspackages/repositories/src/repositoryModule.ts:184-306;targets/identityWriteAuthority.ts:5-8packages/external-connectors/shared/src/authRefreshFlow.ts:1-11;meta/src/whatsappBusinessApp.ts:705-751packages/services/src/crmWorkflows/syncOrchestrator.ts,syncBackOrchestrator.ts:2-46,shared/syncAnchor.ts:1-20,shared/hooks.ts:1-25packages/notifications/src/index.ts;packages/analytics/src/errorReportingLogger.ts:128-178guidance/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.
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 gateorganizationFeatureProcedure(permission, featureKey): a true admin bypasses both ACL and flag; everyone else needs both. The webOrganizationFeatureGaterenders 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) ornew("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(defaultfalse): when false, the scheduler registers no crons and the worker registers no dispatcher ticks.POSTHOG_ENABLED(jobenabledEnvVar) gates the three vendor-cost crons.OPENROUTER_API_KEYwires the Decision-1 clients.GCP_STORAGE_BUCKETenables the webhook spool drain. - Settings toggles.
defaultContactPreferences.outboundCadenceEnabled(defaulttrue, an account kill switch),emailSettings.oneClickUnsubscribeEnabled,accessControlSettings.assignment.enabled/.escalation.enabled, voice no-consent and human-transfer routing.enabled, phone-lineambientSound, escalation-rule CRM-task directives. All default off except the cadence switch and escalation rules.revivalSettingsandinferenceSettingsare 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) andAdminOnlyOverlay(sections inside customer pages) follow the logged-in Zube human (@getzube.comdomain), so an impersonating admin keeps access.adminProcedureis defined but has no call sites. - Per-client code. Hard-wired to an organisation ID under
packages/workflows/src/clients/**orpackages/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_stageflag. The "Gated" filter below is this document's label for built-but-off-by-default features.
| Area | Feature / workflow | Status | What it does (one line) | Runs in | Trigger / surface | Notes |
|---|---|---|---|---|---|---|
| Lead workflows | on_text_message_received | GA | Agentic 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 chat | Hands off to on_conversation_complete. Default machine for every org. |
| Lead workflows | on_call_complete | GA | Finalises 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 sweep | On failure enqueues cadence_step_failed for a sibling cadence. Hands off to on_conversation_complete. |
| Lead workflows | on_conversation_complete | GA | Post-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 chat | Also starts the lead_lifecycle_stage shadow classifier when that flag is on. Client getPostWorkflow may add a successor. |
| Lead workflows | on_crm_sync | GA | Resolves 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 import | Runs for any org with a CRM integration. |
| Lead workflows | outbound_messaging_cadence | GA engine custom: start | Pure 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 checkAwaitingAction | The only producers are client hooks (Stay Club, Lingua, MiCampus). No cadence builder UI. Honours outboundCadenceEnabled. |
| Lead workflows | Channel-to-workflow routing (endpoint assignment) | GA | An inbound message on an endpoint moves the target onto that endpoint's business workflow and writes a config_change audit row. | worker / telephony-infra | Inbound Instagram, Messenger, ElevenLabs, Telnyx | Paused and override targets are protected. (planning doc says "Status: draft" — stale.) |
| Lead workflows | Send-safety hold (execution-safety hold) | GA | Persists 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 session | Writes a deterministic take-over audit row. Conservative false-positive holds are possible. |
| Lead workflows | Reply delays | GA | Text and email reply delays from contactPreferences or a target override (defaults 180 s / 600 s). | runner | Org contact preferences | Web chat never parks. |
| Client machines & hooks | lingua_conversation_complete | custom: Lingua | Picks and sends a templated post-conversation email (template key, campus, language), then restores the predecessor. | worker / scheduler (runner) | Handoff from Lingua on_conversation_complete getPostWorkflow | HTML templates en/es. |
| Client machines & hooks | stay_club_crm_requested_viewing_booking | custom: Stay Club | Books a CRM-requested viewing through calendar tools; sends confirmed / unavailable / clarification emails. | runner | Handoff from Stay Club on_crm_sync | May hand on to the outbound cadence. |
| Client machines & hooks | micampus_call_complete | custom: MiCampus | After a voice conversation: LLM booking extraction (confidence floor 70), WhatsApp template, per-residence booking emails. | runner | Handoff from MiCampus on_conversation_complete | Also bound to a MiCampus internal test org. Faults go to Zube-only audit rows. |
| Client machines & hooks | micampus_outbound_whatsapp_dry_run | custom: MiCampus dormant | "Internal-only observation cadence": no provider ports, stages, CRM writes or audits. | runner | HANDOFF_DELIVERY (no producer found) | Registered and boot-asserted. Whether data or a script enqueues it is undetermined. |
| Client machines & hooks | MiCampus CRM-sync post-workflow (Google Ads WhatsApp cadence) | custom: MiCampus live | Starts the locale-resolved WhatsApp cadence for new Salesforce leads with no prior communication. | runner | on_crm_sync getPostWorkflow | Eligibility: Google AdWords source, unknown residence or recent lead creation. (epic's first-name requirement — stale.) |
| Client machines & hooks | MiCampus preCrmSyncback | custom: MiCampus | Salesforce only: rewrites LeadSource (outbound WhatsApp vs Zube inbound) and moves a lone first name into last name. | scheduler | on_crm_syncback hook key, via crmSyncbacker | Syncback hardening: 2 h quiet period (approval doc's 15 min — stale). |
| Client machines & hooks | MiCampus cadence pre-send guard | custom: MiCampus | Client guard run before the immediate send and before every cadence WAKE. | runner | Cadence send | |
| Client machines & hooks | Tool get_properties | custom: MiCampus | Planner-callable read tool searching bundled properties.json. | worker / telephony-infra | Agent tool call | Feeds knowledge_query diagnostics. |
| Client machines & hooks | Tool get_booking_link | custom: MiCampus | Planner read tool returning the official pricing/visit URL. | worker / telephony-infra | Agent tool call | |
| Client machines & hooks | Tool send_booking_link_via_whatsapp | custom: MiCampus | Planner write tool sending a WhatsApp text via client tool effects. | worker / telephony-infra | Agent tool call | |
| Client machines & hooks | Tool send_booking_info | custom: MiCampus | Write tool sending booking-info email; not planner-callable, so voice-only. | telephony-infra | Voice tool call | |
| Client machines & hooks | Lingua CRM-sync post-workflow | custom: Lingua | Hands a new CRM record to lingua_outbound_cadence. | runner | on_crm_sync getPostWorkflow | |
| Client machines & hooks | Lingua conversation-complete post-workflow | custom: Lingua | Hands off to lingua_conversation_complete. | runner | on_conversation_complete getPostWorkflow | |
| Client machines & hooks | Lingua preCrmSyncback | custom: Lingua | Resolves preferred campus and area of interest and sets those CRM fields. | scheduler | crmSyncbacker | Skips Dynamics. Exact lookup → Decision-1 → gpt.fast fallback. |
| Client machines & hooks | Lingua campus prediction (Decision-1, files named "Jev") | custom: Lingua | Probabilistic campus choice for non-exact text; accepted at confidence and support ≥ 0.75. | scheduler | Lingua syncback hook; needs OPENROUTER_API_KEY | Targets microsoft/microsoft-decision-1 via OpenRouter. (docs say behind a default-off org flag — no flag check found in code.) |
| Client machines & hooks | Tool get_enrollment_link | custom: Lingua | Planner tool; the runtime owns the URL and appends it to the final reply with dedupe. | worker / telephony-infra | Agent tool call | |
| Client machines & hooks | Stay Club CRM-sync post-workflow | custom: Stay Club | For 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. | runner | on_crm_sync getPostWorkflow | Order: named-workflow rule → auto-reply suppression → guardrail cadence → LLM selector. |
| Client machines & hooks | Stay Club LLM cadence selector / scenario classifier | custom: Stay Club | gpt.fast structured outputs choosing the cadence; failures route to help_needed. | runner | Inside Stay Club CRM-sync post-workflow | Part of client semantic routing (ZUBEA-310, doc "implemented; in review"). |
| Client machines & hooks | stayClubCrmSyncPostHook | custom: Stay Club | Writes a help-needed escalation when auto-reply is suppressed. | runner | on_crm_sync post hook, default workflow only | |
| Client machines & hooks | Stay Club no-op conversation-complete post hook | custom: Stay Club | Registered so the hook slot exists; does nothing. | runner | on_conversation_complete | |
| Client machines & hooks | Stay Club calendar booking params | custom: Stay Club | Invite email, optional attendees by event type, LLM transcript summary for bookings. | runner / telephony-infra | Generic calendar tool service | No custom agent tools registered for Stay Club. |
| Client machines & hooks | Email-CRM parsers (Stay Club, Road Scholar) | custom: Stay Club custom: Road Scholar | Parse notification/enquiry emails in the shared CRM inbox into contacts and dispatch on_crm_sync. | scheduler | emailCrmSyncer every 5 min | Stay Club parses Salesforce notifications. Road Scholar sets road_scholar_trip_interest (TODO pending client mapping). |
| Client machines & hooks | Tool get_trip_list | custom: Road Scholar | Planner read tool searching bundled trips.json by program number, keyword or trip type. | telephony-infra / worker | Voice tool call | Deploy probe smoke-tests it on both tool paths. |
| Client machines & hooks | Call param road_scholar_trip_interest | custom: Road Scholar | Exposed as a voice call parameter inside generic services. | telephony-infra | Inbound call init | |
| Client machines & hooks | Addison Lee UC1 sales-inbound prospecting | custom: Addison Lee | Consumes every inbound email to the shared sales inbox and runs lookalikes → enrichment → per-contact drafts into an Outlook "Zube Drafts" folder. Never sends. | scheduler only | on_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 & hooks | Addison Lee prospecting providers | custom: Addison Lee | ZoomInfo (client-custom wrapper), Lusha V3 connector, Gemini grounded web search, wrapped as ports in the client folder. | scheduler | UC1 pipeline | Lusha is the only consumer of external-connectors/prospecting. |
| Client machines & hooks | Addison Lee UC2 media-production outbound | custom: Addison Lee removal scheduled | Cold email + LinkedIn campaign for one salesperson: campaign-reply interceptor, DB-backed state machine, daily caps, Day 3/Day 9 schedule, Freshsales runner. | scheduler | clientOutboundTick every 30 s + reply pre-hook | TODO(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 & hooks | ZoomInfo callback /callbacks/custom/addisonlee/zoominfo | custom: Addison Lee | Returns 204. A stub. | webhooks | HTTP callback | |
| Outbound cadences | stay_club_outbound_cadence | custom: Stay Club | Shell for 12 standard legacy-ported contact cadences (coliving/student follow-ups, WhatsApp openings). | runner | Stay Club CRM-sync selection | Also covers long-stay student promo (id not given in research). |
| Outbound cadences | stay_club_university_fair_cadence | custom: Stay Club | Cadence for university-fair leads. | runner | university_fair business workflow | |
| Outbound cadences | stay_club_meta_ads_cadence | custom: Stay Club | Meta ads cadences with parent, students and professional maps. | runner | meta_ads* business workflows | |
| Outbound cadences | stay_club_hanger_lane_north_acton_redirection_email | custom: Stay Club | Guardrail cadence redirecting short-stay enquiries. | runner | Stay Club guardrail selection | |
| Outbound cadences | stay_club_general_enquiry_{email,whatsapp} | custom: Stay Club | General-enquiry cadences by channel. | runner | Stay Club selection | |
| Outbound cadences | micampus_outbound_whatsapp_cadence | custom: MiCampus live | WhatsApp cadence in en, es and pt with a pre-send guard. | runner | MiCampus CRM-sync post-workflow | CRM-sync cadences delay the first stage by ≥ 900 s. |
| Outbound cadences | lingua_outbound_cadence | custom: Lingua | default_outbound_initial at 0 s, default_followup at +24 h; template language by phone country. | runner | Lingua CRM-sync post-workflow | Multilingual templates need a deploy plus one sync step. |
| Outbound cadences | lingua_revival_cadence | custom: Lingua dormant | Revival cadence mixing email and WhatsApp stages. | runner | none found | Registered, no in-code producer. Revival is a deferred product. |
| Outbound cadences | Cadence safeguard matrix | GA | 6 pure rules (stage-0 no-history, live WhatsApp conversation, resend cap, multiple conversations, expected-before-stage, attempt counters); violation → STEP_FAILED + WARNING audit. | runner | Before each stage send | |
| Outbound cadences | Account cadence kill switch outboundCadenceEnabled | GA | When false, cadence handoffs are refused and checkAwaitingAction skips cadence work. | runner / scheduler | Contact-preferences settings toggle | Default true. The only operator lever over cadences. |
| Outbound cadences | Cadence quiet hours (message window) | unverified | Configs carry message-window hours, weekend flags and blackout dates. | runner | Cadence config | No enforcement found on WhatsApp/email stages; next stage is plain now + delay. Confirm with the owner. |
| Channels | WhatsApp Cloud API | GA | Inbound and outbound WhatsApp. | webhooks → worker | /whatsapp webhook → inbound-event | Receipts stored in webhook_receipts (14-day expiry). |
| Channels | WhatsApp Business App coexistence | GA | History import, contact-book (app-state) sync and SMB echoes. | webhooks → worker | WhatsApp webhook events | |
| Channels | WhatsApp BSUID / username identity | GA | Treats the WhatsApp BSUID as first-class identity for inbound and replies. | worker | Inbound WhatsApp | Cadences remain phone-only. |
| Channels | WhatsApp edit safety | GA | Edit handling and transcript convergence for edited messages. | worker | Inbound edits | (doc says uncommitted — stale.) |
| Channels | Multilingual WhatsApp templates | GA | Template language chosen per contact/phone country. | runner | Cadence and follow-up sends | Used by Lingua; needs a deploy plus one sync step. |
| Channels | Messenger / Instagram | GA | Meta connections, OAuth, media persistence, profile fetch, rate limiting. | webhooks → worker | /messenger, /instagram | |
| Channels | Ad-click attribution (ENG-30) | GA | Records 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. | worker | Meta referral fields on inbound messages, postbacks and Messenger messaging_referrals events | No backfill. Pages connected before ENG-30 need scripts/integrations/resubscribeMessengerPageWebhooks.ts (dry run by default, --apply to subscribe). |
| Channels | Email (Gmail / Outlook) | GA | Mailbox polling, reply sending and inbound dispatch. | scheduler | emailPollingSyncer every 2 min | |
| Channels | History sync (email, Messenger, Instagram) | GA | Imports channel history; stalled syncs are resumed hourly. | scheduler | historySyncResumer | |
| Channels | Email open / click / unsubscribe tracking | GA | Tracked links and pixels via link.zube.ai/e. | webhooks | /o/:token.gif, /c/:token, /u/:token | Scanner opens separated by an ops review script. |
| Channels | One-click unsubscribe | gated | One-click unsubscribe on tracked email. | webhooks | emailSettings.oneClickUnsubscribeEnabled | Default false. |
| Channels | Guardrail email forwarding / bypass-forward | code present | Forwards guardrail-matched email after commit. | scheduler | Email inbound | Guardrail doc says slice 6 is post-June fast-follow; the jobs manifest marks bypass-forward deferred; code exists. Current status undetermined. |
| Channels | Hard bounces and email ignore list | GA | Bounce handling and sender ignore list inside the email service. | scheduler | Email inbound/outbound | |
| Channels | Microsoft email auth recovery | GA | Recovers Microsoft mailbox auth failures. | scheduler | Email integration errors | Built after an Addison Lee incident. |
| Channels | Web chat (embeddable widget) | GA | Website chat on the same targets and agent machine as other text channels. | webhooks → worker | /webchat HTTP + WS, apps/webchat-widget | Per-org setup: session secret, escalation rules, web_chat/all template, origin allowlist. Built for two unnamed clients. |
| Channels | Webchat continuation to WhatsApp / email | gated | Carries a webchat conversation to WhatsApp or email and correlates the next message. | webhooks / worker | Per-widget toggle | Disabled by default per widget; live-provider checks remain deployment prerequisites. |
| Channels | Calendar integrations + agent tools (Calendly, Microsoft) | GA | Slot listing and booking with locks, timezone and attendees. | runner / telephony-infra | Agent tool calls | |
| Channels | Magic booking link | GA | A lead self-books a meeting from a tokenised link. | api / web | /magic/book-meeting?token= | (doc says draft — stale.) |
| Channels | Link domain short links / redirects | resolve planned: create UI | Redirect slugs on link.zube.ai resolve publicly with daily click metrics. | api / web | /$slug on link.zube.ai | No admin create UI; no setup-account flow. Magic-link type coverage undetermined. |
| Channels | Channel read / send / help-needed permissions | GA | Per-integration flags decide whether a channel replies or escalates. | runner | Integration config | SMS and zube have no mapping and fail loud. |
| Channels | SMS (Telnyx) | dormant | A TelnyxSmsClient exists; no inbound handler and no importer. | — | none | Cadence SMS stages were dropped. |
| Channels | zube channel enum value | internal enum | Internal conversation channel value with no ingress. | — | none | |
| Channels | Microsoft SharePoint / Teams | connect-only | OAuth connect with nothing consuming the connection. | api / web | New UI integration pages | Classic redirects to /integrations?add=. |
| Channels | Lead CSV / XLSX import | GA | Batch import that dispatches CRM_RECORD_RECEIVED per row. | api → worker | /integrations/manual-upload → manual-import queue | Uses the legacy label object_type="external_api". |
| Voice | Telnyx inbound call control | GA | AMD, consent, forwarding schedule, ambient conference, inbound call init. | telephony-infra | /telnyx | |
| Voice | ElevenLabs voice agents and post-call | GA | Voice agent runtime; post-call webhook drives CALL_ENDED. | webhooks → worker | /elevenlabs → inbound-event | |
| Voice | Telnyx recording completion | GA | Transcribes the recording and emits CALL_ENDED. | telephony-infra → worker | voice-post-call queue | A failed enqueue is logged and the post-call is lost. |
| Voice | ElevenLabs calendar tools | GA | calendar_list_slots, calendar_create_booking and the custom client tool route. | telephony-infra | /voice-tools, / (legacy client tools) | |
| Voice | Human transfer | gated | check_transfer_availability, transfer_to_human. | telephony-infra | Human-transfer routing .enabled | Default false. |
| Voice | No-consent call routing | gated | Routes calls where consent is not given. | telephony-infra | callSettings no-consent .enabled | Default false. |
| Voice | Ambient sound | gated | Background sound (office / cafe / nature) on a call. | telephony-infra | Phone line ambientSound | Default null. |
| Voice | Outbound routes callSettings.outboundRoutes | dormant | Workflow-to-line mapping for outbound voice, still stored and editable. | api / web | /integrations/phone-calls | No runtime reader outside settings validation and UI since AI outbound calling was removed. |
| Voice | Transfer outcome reclassification | GA | Daily metrics classify each transfer into five buckets (e.g. reachedNoPickup, callerHangup). | scheduler | aggregateInsights | Historical backfill: whether applied is unverified. |
| Voice | Manual call-audio import (Vodafone OneNet ZIP) | custom: MiCampus MVP | Imports call recordings: STT/diarisation, LLM speaker attribution. | api | /integrations/manual-upload | Sources 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. |
| Voice | NICE CXone recording import | connect-only | Connect, test and update settings; no ingest job. | api / web | /integrations/recording-imports/nice-cxone | Connector imported only by apps/api. |
| Voice | Public voice demos | admin-only public page | Configurable public demo pages (ElevenLabs or Retell) with rate limits and usage receipts. | api / web | /admin/demos; public /demo/$demoSlug | Published slugs immutable. (doc says "Proposed" — stale.) |
| Voice | Demo notes generator | admin-only | From pasted notes, drafts demo page copy and a transient voice-agent prompt; writes nothing. | api | admin.demos.generate | Tier gpt.ultra, no fallback. |
| Agent & knowledge | Foundry text templates | GA create/delete: admin | Agentic templates bound to a workflow_id and channel_scope; lifecycle draft/active/inactive. | api / web | /foundry | Multiple active matches emit an URGENT audit. |
| Agent & knowledge | Foundry voice templates | GA | Voice agent templates; provider elevenlabs only. | api / web | /foundry | |
| Agent & knowledge | Template test reply / Generate reply (agent preview) | GA | Read-only reply preview through the adapter's preview surface. | api → worker | agent-preview queue | Contact-detail generation panel is admin-only. |
| Agent & knowledge | Template graph generation | admin-only | LLM generation of a template graph definition. | api | templates.generateGraph | |
| Agent & knowledge | Template guardrails | GA | Template- and node-level guardrails (e.g. redirect with escalateAfterX); "LLM matches, code counts". | runner | Template config | Slices 0–5 and 7 done; slice 6 was a fast-follow. |
| Agent & knowledge | Workflow-scoped knowledge | GA | restrictKnowledgeToWorkflowOnly scopes Nexus documents to named workflows. | runner | Template setting | (doc says draft — stale.) |
| Agent & knowledge | Nexus corpus, chunking, embeddings | GA | Sources and documents stored in GCS with chunked embeddings. | api | /nexus/documents | |
| Agent & knowledge | Hard delete + citation snapshots | GA | Immediate corpus exclusion, then physical deletion; replies keep citation snapshots. | scheduler / runner | knowledgeDeletionTick | |
| Agent & knowledge | Curated ingest / publication (ZUBEA-263) | GA | Source-backed proposals published atomically after human approval. | api | /nexus/ingest | |
| Agent & knowledge | Pre-publication conflict check | GA | Checks a proposal against the corpus before publishing. | api | Ingest flow | |
| Agent & knowledge | Nexus researcher in production (ZUBEA-261) | GA | Evidence-only researcher over the eligible corpus; source memo on GPT-6.1 Sol. | runner | All text channels except web chat | Planning doc says "implemented, default-off"; Nexus research reports it live. Prefer the code-cited Nexus research. |
| Agent & knowledge | Test / Ask Nexus | GA | Operator test console using the same researcher. | api | Nexus UI | Corpus details behind admin overlay. |
| Agent & knowledge | Observed knowledge gaps (ZUBEA-268) | GA | Captures knowledge attempts; hourly classification and grouping into Review findings. | runner / webhooks / scheduler | /nexus/review; knowledgeQueryDiagnostics | Rollout verification pending per doc. Covers get_properties and get_trip_list. |
| Agent & knowledge | Nexus taxonomy (diagnostics automation) | flag: nexus_taxonomy | Assigns findings to per-org category catalogs; Review shows category groups instead of raw findings. | scheduler | nexusTaxonomyWeekly + nexusTaxonomyPoller | (doc says design only — stale.) Decision-client provider wiring not traced. |
| Agent & knowledge | Nexus diagnostics recovery | S1 planned: S2–S4 | Fixes a capture regression; recovery of lost history is planned and blocked. | runner | — | |
| Agent & knowledge | Generic parity contract (Nexus 2.0) | GA | One knowledge product for all clients; missing information means respond honestly and escalate. | runner | Finalizer | The org-flag part of the contract is superseded. |
| Agent & knowledge | ElevenLabs KB sync | admin-only | Pushes Nexus to the ElevenLabs knowledge base. | api (detached microtask) | knowledgeBase.syncElevenLabs, manual | |
| Insights & intelligence | Daily / monthly insights aggregation | GA | Per-org daily metrics, LLM-normalised content insights, monthly rollups. | scheduler | aggregateInsights, aggregateMonthlyInsights | For insights.view. Docs' "Gemini primary" is stale: Gemini tiers are rewritten to GPT. |
| Insights & intelligence | Content-insight curation | GA | Renames and merges each workflow's category catalog from recent evidence. | scheduler | curateContentInsights | |
| Insights & intelligence | Call Insights, lead score, summary, not-interested | GA | Extracts structured lead intelligence onto the target after each conversation. | runner | on_conversation_complete | Authored as gpt.smart. |
| Insights & intelligence | Reminders | GA | Reminder reconciliation per conversation and LLM validation when due. | runner / scheduler | processDueReminders; Home, /reminders | Active-user orgs only. |
| Insights & intelligence | waitingOnTarget | admin-only | Max-five list of what the lead owes, produced by Call Insights. | runner | Contact Insights tab (true admin) | Missed its precision gate (77.3% vs 80%); not GA. |
| Insights & intelligence | Sentiment Analysis (deferred) | admin-only read | Categorical per-snapshot sentiment for non-voice conversations from the previous half hour. | scheduler | processDeferredConversationAnalyses | Best effort: no online fallback, retry or backfill. Model is gpt-6-luna via OpenAI-first batch (doc's Vertex Gemini — stale). |
| Insights & intelligence | Custom analyzers | GA | Org-defined JSON-Schema analyses run per target in the deferred batch. | scheduler / api | /account/analyzers | |
| Insights & intelligence | Audit trail, take-over rows, escalation rules | GA | Activity log, "cannot respond" take-over rows, 3-tier escalation synthesis, 24 h notification cooldown. | runner / api | Home, /reminders/audit-trail, /account/escalations | Raw audit details are admin-only. |
| Insights & intelligence | Escalation rule Tier 2 (Decision-1) | gated: env key | One choice question over candidate rules; used only at confidence ≥ 0.95. | runner | Escalation routing | Active wherever OPENROUTER_API_KEY is set; production setting not inspected. |
| Insights & intelligence | CRM escalation task per rule | gated | Optionally writes a CRM task when an escalation rule fires. | runner / scheduler | Escalation-rule CRM-task directive (opt-in) | Expired reservations reconciled by a cron. |
| Insights & intelligence | Audit acknowledgement metrics | GA | Whether urgent audit events get human acknowledgement. | api | /insights/audit-metrics | |
| Insights & intelligence | Conversion workspace | flag: insights_conversion | Win rates, funnel, time-to-convert, time-in-stage, loss reasons from CRM outcomes. | api / web | /insights/conversion | True admin sees it grouped as "Internal" when off. |
| Insights & intelligence | CRM conversion projection + stage-run measurements | GA | Versioned, rebuildable read model (attribution v4) and J0 stage measurements. | scheduler | rebuildCrmConversionProjections | Feeds the flagged Conversion workspace. |
| Insights & intelligence | Lead lifecycle stage (shadow) | flag: lead_lifecycle_stage | Classifies the lead as prospect / customer / not a customer and stores an observation. Displays and sends nothing. | runner | on_conversation_complete | Also needs inference region global; enabling is refused without OPENROUTER_API_KEY. |
| Insights & intelligence | Drop-off observation ("SalesMotion") | admin-only | Deterministic 48–72 h drop-off detection plus gpt.fast cause/topic explanation. | scheduler / api | /contacts/revival | Active-user orgs only. (four-state LLM adjudication design — superseded.) |
| Insights & intelligence | Drop-off analytics procedures | admin-only | hasDropoffData, getDropoffOverviewKPIs, getDropoffByReason. | api | tRPC | Read legacy drop-off tables. |
| Insights & intelligence | Legacy drop-off tables | legacy | thread_dropoff_events, daily_dropoff_metrics, monthly_dropoff_metrics. | scheduler | Monthly rollup only | No production writer; writers called only from tests. |
| Insights & intelligence | Loss-reason intelligence | admin-only | Explains CRM-lost leads; imported MVP plus daily generation in the aggregateInsights tick. | scheduler / api | /insights/loss-records | Initial import scope: MiCampus and Lingua; Stay Club excluded. |
| Insights & intelligence | Category curation and loss-reason categories | admin-only | Create, edit, delete and consolidate categories and loss reasons; suggestions. | api / web | /insights/categories overlay | |
| Insights & intelligence | Revival shared categories + historical regeneration | internal | One org-scoped causal vocabulary shared by loss and drop-off; manifest-driven regeneration of historical explanations. | script | historicalDropoffRegeneration.ts | Whether the production regeneration ran is unverified. |
| Insights & intelligence | Revival (product) | deferred admin write | revivalSettings.enabled (default false); settings writable only by admins. | api | Settings | Revival jobs are deferred. |
| Insights & intelligence | Manual lead assignment | GA | Atomic ownership change with audit and target_assignment_events history. | api | Contacts | |
| Insights & intelligence | Auto lead assignment | gated | On target creation: inbound_channel_owner, round_robin, random or llm strategy. | runner / api / scheduler | accessControlSettings.assignment.enabled | Default false. |
| Insights & intelligence | Owner → group escalation after N hours | setting only | accessControlSettings.escalation (primaryToGroupAfterHours, groupToAllUsersAfterHours). | — | Settings | The inventory lists it as an opt-in setting; the platform research found no job referencing it (ACL slice 10 "Not started"). |
| Insights & intelligence | Client reports framework | GA types per client | Report definitions and runs, CSV/TSV/XLSX writers, scheduled delivery. | scheduler / api | /integrations/reports; processDueReports | A report type exists only for orgs with a generator. (epic says V1 ships empty — stale.) |
| Insights & intelligence | Report: Salesforce lead cohort | custom: MiCampus | Lead cohort workbook from Salesforce. | scheduler | processDueReports | |
| Insights & intelligence | Report: Salesforce conversion performance | custom: MiCampus | "Manual conversion-performance report". | scheduler | processDueReports | |
| Insights & intelligence | Report: Meta ads efficacy | custom: Stay Club | Meta ads acquisition efficacy workbook (Europe/London). | scheduler | processDueReports | |
| Insights & intelligence | Report: media production weekly | custom: Addison Lee | Weekly UC2 campaign report. | scheduler | processDueReports | Tied to UC2, which is scheduled for removal. |
| CRM | HubSpot | GA | Pull sync and sync-back. | scheduler | crmSyncer, crmSyncbacker | Owner sync from CRM inside on_crm_sync. |
| CRM | Salesforce | GA | Pull sync and sync-back. | scheduler | crmSyncer, crmSyncbacker | |
| CRM | Microsoft Dynamics 365 / Dataverse | GA | Pull sync and sync-back with app-user S2S auth. | scheduler | crmSyncer, crmSyncbacker | Channels research: release gates pending, pilot TBD. |
| CRM | Freshsales (pull) | GA read-only | Pulls Freshsales records into targets. | scheduler | crmSyncer | Pilot: Addison Lee. Deals not built. |
| CRM | Monday | GA | Pull sync and sync-back. | scheduler | crmSyncer, crmSyncbacker | The 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"). |
| CRM | Shared Monday OAuth app config | admin-only | Org-shared Monday OAuth app credentials. | api | integrations.mondayApp.{get,save} | |
| CRM | CRM Sync V2 canonical writer | GA | Sync states, output snapshots, field verification and outcome tables. | scheduler | CRM sync arms | Track A + B substrate implemented; A5 continues per doc. |
| CRM | CRM identity convergence (ADR-021) | GA | Repairs duplicate targets that reference one CRM object. | runner | on_crm_sync | |
| CRM | Syncback reliability recovery | GA | Recovery replay for failed syncbacks (MiCampus Salesforce, Lingua HubSpot). | scheduler | crmSyncbacker | Recovery replay is operational. |
| CRM | Lock-contention pull deferral (S0) | GA | A busy target defers the CRM record without audit, cursor advance or attempt burn. | scheduler | crmSyncer, emailCrmSyncer | |
| CRM | CRM introspection and field verification | GA | Field discovery, verification and owner listing for setup. | api | /integrations/crm/* | |
| CRM | My CRM identity / Home CRM card | GA | A user links their CRM owner identity; Home shows the CRM identity card. | api / web | /user-settings, / | |
| Background jobs | clientOutboundTick | custom: Addison Lee removal scheduled | One UC2 campaign tick. | scheduler | Every 30 s, run on startup | Skips outside the London send window. Delete late Nov 2026. |
| Background jobs | aggregateInsights | GA | Daily metrics, content insights, daily loss generation; deletes expired voice-privacy rows first. | scheduler | 0 5 12 * * * (12:05 UTC) | Described as "nightly" but fires at noon UTC; reason not found. |
| Background jobs | curateContentInsights | GA | Curates content-insight catalogs. | scheduler | Anchored fortnightly Sundays 04:00 UTC, run on startup | Missing from the stale jobs manifest. |
| Background jobs | aggregateMonthlyInsights | GA | Monthly rollup from daily aggregates. | scheduler | 0 0 13 1 * * | |
| Background jobs | bootstrapSalesMotionCrmOutcomes | GA | Backfills canonical CRM outcome observations for sales-motion targets. | scheduler | Every minute at :15 s | HubSpot, Salesforce, Dynamics wrappers. |
| Background jobs | checkAwaitingAction | GA | WAKE sweep for delayed replies and cadence timeouts. | scheduler | Every 30 s | Honours outboundCadenceEnabled. |
| Background jobs | checkStaleConversations | GA | Closes or replays stale ongoing voice conversations (CALL_ENDED). | scheduler | 5 */5 * * * * | |
| Background jobs | crmEscalationTaskReconciler | GA | Marks expired opt-in CRM escalation-task reservations for operator reconciliation. | scheduler | 40 */5 * * * * | No provider calls. |
| Background jobs | crmSyncbacker | GA | Writes targets back to the CRM. | scheduler | 0 2-59/3 * * * * | Freshsales disabled. |
| Background jobs | crmSyncer | GA | Pulls CRM records into targets. | scheduler | 0 */3 * * * * | |
| Background jobs | emailCrmSyncer | custom parsers | Polls the shared CRM inbox, parses contacts, dispatches on_crm_sync. | scheduler | 30 */5 * * * * | Sender domain → org via a domain map. Parsers: Stay Club, Road Scholar. |
| Background jobs | emailPollingSyncer | GA | Polls each mailbox, dispatches on_text_message_received, sends the reply. | scheduler | 15 */2 * * * *, not singleton | Per-mailbox in-process guard. |
| Background jobs | historySyncResumer | GA | Resumes stalled Google, Microsoft, Messenger, Instagram history syncs. | scheduler | 45 0 * * * *, run on startup | |
| Background jobs | jobQueueHealthMonitor | ops tool | Logs queue-tier wait breaches and failures; settles stuck webchat turns, dead import batches, expired previews. | scheduler | Every minute at :20 s | |
| Background jobs | knowledgeDeletionTick | GA | Physically removes deleted Nexus objects, then their rows. | scheduler | Every 15 s | |
| Background jobs | knowledgeQueryDiagnostics | GA | Materialises knowledge attempts and groups unanswered results for Review. | scheduler | Hourly | Active-user orgs only. |
| Background jobs | nexusTaxonomyPoller | flag: nexus_taxonomy | Collects completed Vertex batches; publishes validated taxonomy results. | scheduler | */15 * * * * | Missing from the stale jobs manifest. |
| Background jobs | nexusTaxonomyWeekly | flag: nexus_taxonomy | Bootstraps missing taxonomies and submits inference per unprocessed finding. | scheduler | 0 4 * * 0 Europe/London | Missing from the stale jobs manifest. |
| Background jobs | processDueReminders | GA | Validates and disposes due reminders (LLM). | scheduler | 20 0 * * * * | |
| Background jobs | processDeferredConversationAnalyses | GA | Half-hour Sentiment Analysis and custom analysis via batch. | scheduler | 5,35 * * * *, not singleton | Needs llmBatch. |
| Background jobs | processDueReports | GA per-client generators | Generates and stores pending reports; delivers scheduled ones. | scheduler | Every minute at :30 s | Janitor reclaims runs stuck past 30 min. |
| Background jobs | reconcileSalesMotionObservations | feeds admin view | Enqueues the prior 48–72 h drop-off cohort. | scheduler | 15 2 * * * | |
| Background jobs | processSalesMotionObservations | feeds admin view | Processes a batch of daily sales-motion snapshots with the LLM. | scheduler | Every minute | Active-user orgs only. |
| Background jobs | publicVoiceDemoUsageRetention | GA | Prunes public-demo receipts older than 13 months. | scheduler | Daily 00:00 UTC | |
| Background jobs | rebuildCrmConversionProjections | GA | Repairs missing and refreshes active CRM conversion projections. | scheduler | */10 * * * *, run on startup | |
| Background jobs | telnyxCostRollup | gated: POSTHOG_ENABLED | Telnyx CDR → PostHog vendor_usage_recorded per billable leg. | scheduler | 15 */3 * * * | Internal spend telemetry; org attribution via the phone-line directory. |
| Background jobs | elevenLabsCostRollup | gated: POSTHOG_ENABLED | Per-call ElevenLabs cost → PostHog. | scheduler | 25 */3 * * * | "Directional, not billing-grade". |
| Background jobs | elevenLabsRateRefresher | gated: POSTHOG_ENABLED | Weekly re-stamp of the hard-coded credit→USD ratio. | scheduler | 0 4 * * 1 | |
| Background jobs | webchatIdleFinalize | GA | Finalises idle web chat conversations (CONVERSATION_COMPLETE_TRIGGERED). | scheduler | Every minute | |
| Background jobs | webhookReceiptMonitor | ops tool | Emails ops about unprocessed WhatsApp receipts, daily digest, prunes expired receipts. | scheduler | 15 * * * * | Needs sesConfig. |
| Background jobs | Scheduler heartbeat | ops tool | Debug log line. | scheduler | SCHEDULER_HEARTBEAT_CRON, default */5 * * * * | |
| Background jobs | handoffDispatcherTick | GA | Drains workflow_handoff_pending via runPendingHandoff. | worker | Every 15 s, behind tick lock | |
| Background jobs | targetEventDispatcherTick | GA | Drains target_workflow_event_pending to successor machines. | worker | Every 15 s, behind tick lock | Dead-letters at max attempts. |
| Background jobs | pendingTextDispatcherTick | GA | Resumes WhatsApp/Messenger conversations waiting behind another reply. | worker | Every 15 s, behind tick lock | (worker-split doc says 2 ticks — stale.) |
| Background jobs | webhookSpoolDrainTick | gated: GCP_STORAGE_BUCKET | Turns spooled WhatsApp/Messenger/Instagram bodies into inbound-event jobs; quarantines bad ones. | worker | Every 30 s, run on startup | |
| Background jobs | Phone-line directory LISTEN/NOTIFY | ops tool | In-memory DID → org map for Telnyx cost attribution. | scheduler | pg_notify('phone_lines_changed') | File header claiming api/webhooks consumers is stale. |
| Background jobs | Cloud SQL backup monitor | ops tool | Checks the daily automated backup from SQLAdmin metadata and alerts. | Cloud Run job (out of band) | Cloud Scheduler 0 11 * * * UTC | Deployment opt-in. |
| Queues | inbound-event | GA | WhatsApp, Instagram, Messenger, ElevenLabs post-call and web chat turns; two subscriptions with reserved live-tier slots. | webhooks → worker | pg-boss | |
| Queues | voice-post-call | GA | Telnyx recording completion → transcript → CALL_ENDED. | telephony-infra → worker | pg-boss | No notify, so a job may wait up to about 30 s (unverified). |
| Queues | manual-import | GA | CSV import batches (and call-audio per the inventory). | api → worker | pg-boss, concurrency 2 | |
| Queues | agent-preview | GA | Foundry test replies and manual reply generation. | api → worker | pg-boss, concurrency 4, 300 s expiry | |
| Queues | revops-run | branch | Executes RevOps checkpoint runs. | worker (branch) | Started only by true-admin tRPC | Only on claude/revops. |
| Web app surfaces | Home / (+ /home, /dashboard aliases) | GA | Urgent audit items, reminders, recent conversations, CRM identity card; in New UI also reminders and audit trail. | web / api | Logged in + workspace setup | Classic and New. |
| Web app surfaces | /contacts, /target/$id | GA | Contacts list and contact detail (conversations, activity, insights, CRM rail). | web / api | leads.view | Several detail panels are admin-only. |
| Web app surfaces | /reminders, /reminders/audit-trail | GA | Reminders list and audit trail with acknowledge. | web / api | remindersAndAuditTrails.view | Classic only; New UI redirects to Home and hides the nav item. |
| Web app surfaces | /insights/{overview,performance,content,time-patterns,categories,audit-metrics} | GA | Insights dashboards. | web / api | insights.view | Category create/edit is admin-only. |
| Web app surfaces | /insights/conversion | flag: insights_conversion | Conversion workspace. | web / api | Flag + insights.view | |
| Web app surfaces | /insights/loss-records | admin-only | Loss records explorer. | web / api | AdminOnlyGate | |
| Web app surfaces | /contacts/revival (/insights/revival redirects) | admin-only | Sales-motion / drop-off Revival workspace. | web / api | AdminOnlyGate | |
| Web app surfaces | /nexus/{documents,ingest,review} | GA | Nexus knowledge base, ingest proposals, Review. | web / api | nexus.view (writes nexus.update) | New UI merges Nexus and Foundry into "Agents". |
| Web app surfaces | /foundry, /foundry/template/$templateId | GA | Agent text and voice templates and setup. | web / api | foundry.viewClientConfig | Create and admin fields behind overlays. |
| Web app surfaces | /integrations home | GA | Provider registry across channels, CRMs, calendars, Microsoft 365, recording imports. | web / api | integrations.manageOwn | |
| Web app surfaces | /integrations/channel/{whatsapp,gmail,outlook,meta,web-chat} | GA | Per-channel setup, including the webchat widget and continuation toggle. | web / api | integrations.manageOwn | New only; Classic redirects to /integrations/communication-channels. |
| Web app surfaces | /integrations/crm/*, /integrations/calendar/* | GA | CRM and calendar provider setup. | web / api | integrations.manageOwn | Shared CRM app config is admin-only. |
| Web app surfaces | /integrations/phone-calls (+ Classic /integrations/call-management) | GA | Phone lines, routing, outbound routes. | web / api | organizationSettings.view | New redirects call-management to phone-calls. |
| Web app surfaces | /integrations/{crm,communication-channels,calendars} | GA | Classic aggregate settings pages. | web / api | integrations.manageOwn | Communication channels redirects to per-provider pages in New. |
| Web app surfaces | /integrations/developers | GA | Custom connectors and KMS-encrypted custom secrets (custom_secret). | web / api | integrations.manageOwn | Kept when /api/v1 was removed. |
| Web app surfaces | /integrations/manual-upload | GA | CSV lead import and call-audio import. | web / api | leads.update | |
| Web app surfaces | /integrations/reports | GA types per client | Report definitions, runs, downloads. | web / api | organizationSettings.view (.manage to edit) | |
| Web app surfaces | /account, /account/{contact-settings,analyzers,escalations} | GA | Company profile and business workflows, contact defaults, custom analyzers, escalation rules. | web / api | organizationSettings.view | Inference region is admin-only. |
| Web app surfaces | /account/users | GA | Users, groups, ACL (incl. channel scope), invites. | web / api | organizationSettings.manage | |
| Web app surfaces | /user-settings | GA | UI mode (Classic/New), locale (en-US / en-GB), My CRM identity. | web / api | Logged in | |
| Web app surfaces | /deals/{overview,pipeline,$dealId} | flag: revops_deals | RevOps deals reconstructed from email threads: overview, pipeline, per-deal graph. | web / api | Flag + conversations.view | New only; Classic renders not-found. Data comes only from the ops loader. |
| Web app surfaces | Deals sidebar item | flag: revops_deals | New UI nav entry. | web | Flag alone | "No admin preview": hidden for admins when the flag is off. |
| Web app surfaces | Public: /auth/* (login, forgot/setup password, access-required) | GA | Firebase login and password flows. | web | PublicAuthGate | |
| Web app surfaces | /auth/signup | internal-facing | "Internal Signup" explainer for company Google accounts; customers are provisioned manually. | web | Public | |
| Web app surfaces | proposals.zube.ai/$slug | gated: hostname pending | Client proposal viewer with code-verified session. | web / api | Separate app host; /api/proposals/* | Production hostname activation and pilot rehearsal pending per plan; live state not determinable. |
| Web app surfaces | /settings/*, /account/calls | legacy | URL aliases redirecting to /integrations/* or account pages. | web | Logged in | |
| Web app surfaces | /_dev, /_dev/{primitives,charts,forms} | ops tool | Dev workbench and UI primitive playground. | web | Vite dev server or localhost only | |
| Web app surfaces | /admin | admin-only | Clients: create client, impersonation targets, user activation, delete organisation, password invites. | web / api | AdminOnlyGate | Delete organisation is the only tenant-wide hard delete. |
| Web app surfaces | /admin/changes | admin-only | Internal customer change-request log with evidence uploads. | web / api | AdminOnlyGate | |
| Web app surfaces | /admin/feature-flags | admin-only | List and toggle the 4 org feature flags. | web / api | AdminOnlyGate | |
| Web app surfaces | /admin/demos | admin-only | Public voice demo management: create, generate, Retell credential, usage. | web / api | AdminOnlyGate | |
| Web app surfaces | /admin/proposals | admin-only | Client proposals list and detail. | web / api | AdminOnlyGate | No update/publish API; created via the create-proposal skill. |
| Admin & internal tools | Impersonation (persona) | admin-only | A true admin acts as a customer user; true-admin access follows the human, so /admin stays available. | api / web | admin.listImpersonationTargets | Admins can preview either UI mode while impersonating. |
| Admin & internal tools | Overlay: Foundry admin fields | admin-only | Template creation and admin-only template fields. | web | AdminOnlyOverlay | |
| Admin & internal tools | Overlay: contact detail internals | admin-only | Sentiment, internal target insights, outcome rail, raw audit metadata, reply-generation panel. | web | AdminOnlyOverlay | |
| Admin & internal tools | Overlay: WhatsApp template actions / sync | admin-only | Template actions and syncTemplates. | web / api | AdminOnlyOverlay, trueAdminProcedure | |
| Admin & internal tools | Overlay: Account inference settings | admin-only | LLM region global / us / european. | web / api | Classic Account page | Region also gates the lead-lifecycle classifier. |
| Admin & internal tools | Overlay: Nexus internals | admin-only | Evidence internals, toolbar admin actions, test-query corpus details. | web | AdminOnlyOverlay | |
| Admin & internal tools | Overlay: audit event raw details | admin-only | Raw audit event details. | web | True admin | |
| Admin & internal tools | Demo-organisation policy | internal | Orgs whose users are all inactive suppress external escalation side effects; demo_insights_reference_at gives demo Insights a virtual "now". | runner / api | Org data | Doc: "implemented; awaiting deploy review". |
| Admin & internal tools | zube-demo-org skill | ops tool | Builds prospect demo orgs in production from fabricated data (rehearse locally, then prod-db-write). | agent session | Skill | Seeds Nexus docs with a deliberate gap and Review findings. |
| Admin & internal tools | create-proposal skill | ops tool | Authors and validates client proposals on the proposal engine. | agent session | Skill | |
| Admin & internal tools | PostHog LLM cost events | internal | $ai_generation events with modelled cost per call. | all LLM callers | When the caller supplies telemetry | Direct batch paths bypass it. No hard spend cap exists. |
| Admin & internal tools | /posthog alert intake | internal | PostHog error-tracking alert emails. | webhooks | HTTP | |
| Admin & internal tools | Status page status.zube.ai | ops tool | Uptime Kuma in a separate Compose project behind nginx. | VM | — | Infra merged; operator steps (bucket, MFA admin, domain mapping) unverified. |
| Admin & internal tools | Security scanning | ops tool | Semgrep + bun audit in CI; production vulnerability evidence job (VM Manager, Trivy per image digest). | CI | PRs, main, weekly | The planning-doc table says host scanning is not built; the platform research cites the CI job and assessor script. Prefer the latter. |
| Admin & internal tools | check:remote (AWS) | ops tool | Remote checks on AWS EC2 via SSM-proxied SSH. | AWS | bun run check:remote | GCP target in staged retirement. |
| Admin & internal tools | CI validation reuse | ops tool shadow | Reuses validation of identical inputs across checks. | CI | validationShadow.ts | Partial: normal commands and workflows do not call it yet. |
| Ops scripts | prod-db-read / prod-db-write | ops tool | Only general-purpose production SQL entrypoints; single-statement AST validation; read-only or rollback by default. | script | bun run prod-db-* | |
| Ops scripts | revops-deal-load | ops tool | Rehearse and apply one as-of RevOps deal export into an org; insert-only. | script | bun run revops-deal-load | The only loader for revops_deals data on main. |
| Ops scripts | Content-insight bootstrap | ops tool | Prepare, rehearse and apply content-insight bootstrap with fresh-capture guards. | script | prodDbContentInsightBootstrap*.ts | |
| Ops scripts | Insight lock proof | ops tool | Lock-behaviour proof against a disposable Postgres. | script | prodDbInsightLockProof.ts | |
| Ops scripts | Historical drop-off regeneration | ops tool | Generate, preview, rehearse, apply, verify per org and cohort date. | script | historicalDropoffRegeneration.ts | No all-tenant default. |
| Ops scripts | Email tracking signature review | ops tool | Separates scanner opens from real opens. | script | bun run email-tracking:signature-review | |
| Ops scripts | Phase-2 deploy runbook and data step | ops tool | Task 0 deletions, worker split, monitoring alert definitions. | script | phase2*.ts, phase2*.md | |
| Ops scripts | workspace:clean | ops tool | Stale worktree and artefact clean-up (dry run by default). | script | bun run workspace:clean | |
| Ops scripts | operations:check | ops tool | Typecheck plus vitest for operations and Nexus scripts. | script | bun run operations:check | |
| Ops scripts | nexus:prepare-approved-backfill | ops tool | Rehearses seeding three approved taxonomy catalogs per tenant into disposable Postgres; no production writes. | script | scripts/nexus/* | |
| Ops scripts | Configurable demo data generator | ops tool | Portable demo bundle (Workspace London, Starline Tours or custom) for a chosen local database. | script | bun run demo:data:generate:configurable | Seed with demo:data:seed. |
| Ops scripts | Visible showcase rehearsal | ops tool | Showcase rehearsal on a disposable testcontainer; never reads env or a live database. | script | rehearseVisibleShowcase.ts | |
| Ops scripts | reconcileSixFreshsalesDay3Tasks.ts | custom: Addison Lee removal scheduled | One-off UC2 Freshsales task reconciliation. | script | Manual | Delete late Nov 2026. |
| Ops scripts | importUc2Campaign.ts | custom: Addison Lee removal scheduled | UC2 campaign cohort import. | script | Manual | Delete late Nov 2026. |
| Ops scripts | collectUc2ReplyBackfill.ts | custom: Addison Lee removal scheduled | Backfill of UC2 campaign replies. | script | Manual | Delete late Nov 2026. |
| Ops scripts | previewOutboundCampaignEmail.ts | custom: Addison Lee removal scheduled | Offline preview of one UC2 email; cannot send or draft. | script | Manual | Delete late Nov 2026. |
| Ops scripts | runUc2SealedRehearsal.ts | custom: Addison Lee removal scheduled | Sealed UC2 rehearsal. | script | Manual | Delete late Nov 2026. |
| Removed features | AI outbound calling | removed | on_cadence_call_start and cadence call stages (Task 0, T0.1). | — | — | Rollback must not restore it ("a legal issue"). outboundRoutes residue remains. |
| Removed features | Outbound customer webhooks | removed | Customer-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 API | removed | Nine target/conversation routes, /api/docs, OpenAPI, API-key auth and the Developers API-key card (T0.3). | — | — | Residue: api integration type, sanitizeAdditionalInformationForExport. |
| Removed features | Scheduler job detectDropoffEvents | dropped | Dropped by product decision. | — | — | Recorded in the jobs manifest. |
| Removed features | Scheduler job processAdvancedInsightObservations | dropped | Dropped by product decision. | — | — | advanced_insight_observations table dropped. |
| Removed features | Scheduler job reconcileAdvancedInsightObservations | dropped | Dropped by product decision. | — | — | |
| Removed features | Scheduler job runEmailCampaign | dropped | Dropped by product decision. | — | — | |
| Removed features | Scheduler job sendEmailReminders | dropped | Dropped by product decision. | — | — | |
| Removed features | Jobs revivalGateSweep, revivalOutcomeLookback, calendarBookingMagicLinkSweep | deferred | Deferred by product decision; not registered. | — | — | |
| Removed features | Freshsales CRM sync-back | disabled | Sync-back to Freshsales. | — | — | TODO(freshsales-syncback) "intentionally disabled". |
| Removed features | Cadence SMS stages | dropped | SMS stages were not in the legacy stage union and were dropped. | — | — | |
| Removed features | Insights V2 additive-action and semantic drop-off streams | retired | Routes /insights/additive-v2, /insights/dropoffs, /insights/sentiment-v3 retired; /insights/revival now redirects. | — | — | Retired with no fallback. |
| Removed features | revival_metrics table | dropped | Revival metric storage. | — | — | (README still lists revival metric fields — stale.) |
| Removed features | Four-state "Sales Motion" design and sales_motion_observation flag | superseded | LLM-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 features | Standalone Nexus Conflicts tab | superseded | Separate conflicts UI. | — | — | Not present. |
| Removed features | Nexus semantic remediation groups | stopped | Experiment grouping findings by remediation. | — | — | |
| Removed features | Gemini 3.6 upgrade | superseded | Planned tier move to Gemini 3.6 Flash. | — | — | Tiers now map to gemini-3.8-flash. |
| Removed features | Schema cleanup phase 2 | merged; follow-up open | Verified 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 & planned | RevOps checkpoint-run pipeline | branch dormant | Resumable, cost-capped XState machine: one deal at one checkpoint; publishes revops_deal_days in one fenced transaction. | worker (branch) | True-admin tRPC only | claude/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 API | branch admin-only | Checkpoint grid, run list, spend; start/cancel/resume runs, org config. | api / web (branch) | trueAdminProcedure | |
| Branch-only & planned | Deals forecast, renewals and past-blockers pages | branch flag: revops_deals | Portfolio, forecast, renewals pages reading a fictional demo dataset. | api / web (branch) | /deals/forecast, /deals/renewals, /deals/past-blockers | Deterministic clock-simulation forecast; renewals "schema" is a Zod schema in the demo dataset, not a table. |
| Branch-only & planned | RevOps demo portfolio generator | branch | Seeded generator of invented portfolios (facilities seller, football-club hospitality). | script (branch) | bun run revops:demo-portfolio:generate | Newer datasets only on a separate step-2 branch. |
| Branch-only & planned | RevOps ingest library | branch | Turns Freshsales email-conversation pages into write-once stored messages. | script (branch) | Probe scripts only | No production trigger. |
| Branch-only & planned | RevOps loader conversations-only mode | branch | Loads a deal and its conversations only. | script (branch) | revops-deal-load | |
| Branch-only & planned | RevOps Intelligence plan (art_f7b5664c) | planned | Exec "exceptions" MVP on up to 5 Addison Lee deals: Exceptions list → Blockers / Timeline / Evidence. | — | — | Draft rev 4, approval pending. |
| Branch-only & planned | Identity substrate (art_73a5ddf7) | planned | Multi-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 & planned | Managed runtime for custom client workflows (art_e7fce6a6) | planned | A "case lane" on the XState runner core; first tenant hotel chargebacks. | — | — | Not approved, nothing built. |
| Branch-only & planned | Custom-client scalability | parked | Move 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 & planned | Calendar booking truth | planned | Durable appointments ledger with voice correlation. | — | — | Approved; no appointments table (only slot locks). |
| Branch-only & planned | Outbound voice hold detection | planned | Stop vendor billing while outbound calls sit on hold. | — | — | Off-repo plan only; no code. |
| Branch-only & planned | Native audio (OpenAI / Gemini realtime) | planned | Replace the ElevenLabs agent platform with native realtime audio. | — | — | Draft MVP testing plan; no runtime code. |
| Branch-only & planned | Account / OAuth provider linking | planned | Link Google/Microsoft OAuth to existing email/password identities. | — | — | Web wires only GoogleAuthProvider. |
| Branch-only & planned | Org language settings / Spanish UI | planned | Org base language plus user override (en/es); localised emails. | — | — | Only en-US and en-GB exist. |
| Branch-only & planned | 21 Degrees pilot | planned | Communication 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 & planned | 60-day data retention purge | not found | Opt-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 & planned | Freshsales deals | planned | Deal sync for Freshsales. | — | — | Not built. |
| Branch-only & planned | User ACL slice 10 | planned | Reminder acknowledgement flows, escalation job, notification preferences. | — | — | "Not started"; only the settings contract exists. |
| Branch-only & planned | Workflow envelope stack-aware mirror (steps 2–4) | planned | Stack-aware scheduler mirror and invariant detector. | — | — | Step 1 (instant machines) is built; successor contract is still restorePrevious: boolean. |
| Branch-only & planned | Workflow lock contention Q1–Q7 | planned | Target-busy semantics everywhere, durable target mailbox, shorter lock ownership, CRM replay. | — | — | Unapproved; only S0 deferral is built. |
| Branch-only & planned | OpenAI usage control (remaining) | planned | Telemetry envelope with daily reconciliation, response-quality gate, MiCampus downshift, OpenAI Batch lifecycle. | — | — | Only the tier mapping and cost telemetry shipped. |
Per-client view
| Client | What is custom for them | Detail |
|---|---|---|
| Stay Club | CRM-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 |
| Lingua | Outbound 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 |
| MiCampus | Google 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 Scholar | Email-CRM parser; get_trip_list tool; road_scholar_trip_interest call param. No hook slots. | #custom |
| Addison Lee | UC1 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 |
| Others | No 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,enableddefault false.packages/webapp-contracts/src/admin/index.ts:225-272— the 4-key catalog, alldefaultEnabled: 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—organizationFeatureProcedurewith true-admin bypass (:333);:403trueAdminProcedure;:374adminProcedureunused.apps/web/src/routes/AuthGates.tsx:90-128,294-301—OrganizationFeatureGateandAdminOnlyGate.apps/web/src/components/AdminOnlyOverlay.tsx:88,102— overlay defaults toaccess='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, defaultclassic.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.
/nexusnexus.view / nexus.updategpt.ultraclaude.smart structured-output fallbackunavailable, reply suppressedWhat 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).
- Researcher model. The planning docs describe Vertex Gemini (
gemini.fast, minimal reasoning, no cross-provider fallback). The code defaults to a source-memo strategy ongpt.ultra(gpt-6.1-sol, reasoning high) with aclaude.smart(Bedrock Claude Sonnet 5) structured-output fallback. It returnsresearch_completed, not the epic's four typed statuses. - GPT-first routing. Generations authored as
gemini.*are remapped togpt.*at initial generation, so curation and the generic Nexus generations run ongpt-6-lunafirst; Gemini serves as fallback or for token accounting. - No per-org toggle.
organizations.nexus_enabledis gone from the Drizzle schema and no longer read (the physical column remains until a later contract migration). The runtime rule ischannel !== '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—/nexusroutepackages/webapp-contracts/src/userAcl/index.ts:254-255—nexus.view,nexus.updateplanning_docs/nexus-researcher/epic.md:14-18,41-46;handoff.md:53-59— problem statementplanning_docs/nexus-generic-parity/epic.md:8,19-29— 2.0 replaces the tool implementation onlypackages/llm/src/nexusResearchMemoGeneration.ts:80-86;packages/llm/src/nexusResearcher.ts:741— source memo ongpt.ultra; commit665ed4eeb(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 remappackages/db/drizzle/0065_daffy_strong_guy.sql:1-5—nexus_enabledno longer selected;agenticReplyAdapter.ts:176-179— channel ruleplanning_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.
| Group | Table / field | What matters |
|---|---|---|
| Documents | knowledge_documents | One 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. |
| Documents | staging + deletion columns | ingest_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). |
| Chunks | knowledge_chunks | content, token_count, chunk_index (unique per document), embedding vector(3072), HNSW halfvec index. |
| Revision guard | knowledge_corpus_revisions | One integer revision per organisation; the compare-and-swap guard for curated publication. |
| Curated ingest | knowledge_ingest_sessions | mode 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 ingest | knowledge_ingest_sources | Extracted text per submitted source (upload | url | text), with expires_at, content_deleted_at. |
| Curated ingest | knowledge_ingest_candidates | Proposed 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 gaps | knowledge_query_capture_events | Transient durable inbox for ElevenLabs post-call payloads (provider = elevenlabs only); unique per provider event; lease/retry columns. |
| Observed gaps | knowledge_query_observations | One 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 gaps | knowledge_gap_findings | One 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 gaps | knowledge_gap_occurrences | Observation → finding link; unique on (observation_id, atomic_aspect_index). |
| Taxonomy | knowledge_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. |
| Provenance | nexusCitationSnapshot | Optional field in the transcript's agentic_response metadata: researchTaskHash, workflowIds, corpusSnapshotId, status, generatedAt, and per evidence item documentId, version, chunkId, exactQuote, citedTitle, workflowId. |
| Removed | knowledge_query_diagnostics, knowledge_review_runs | Old 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 columnspackages/utilities/src/workflowId.ts:6;packages/services/src/knowledge/library.ts:70-72,743— default workflow id, key formats, text stored as uploadpackages/db/drizzle/0030_natural_mister_fear.sql:1-19— deletion columns and archived-row migrationpackages/db/src/schema/knowledgeChunks.ts:21-60;knowledgeEmbeddings.ts:4-18;0000_initial.sql:219— chunks, halfvec castpackages/db/src/schema/knowledgeCuration.ts:26-158;knowledgeIngestSessions.ts:42-98;packages/repositories/src/knowledgeCuration.ts:36-37— curated tables, TTLspackages/db/src/schema/knowledgeGaps.ts:34-355— gap tables (migration0045_heavy_morbius.sql)packages/db/src/schema/knowledgeGapTaxonomy.ts:27-645— taxonomy tablespackages/db/src/schema/conversations.ts:79-126— citation snapshot schemapackages/db/drizzle/0046_nifty_cardiac.sql:1,5— dropped tables
Pipeline at a glance
Ingestion
Accepted inputs and chunking
| Input | Extraction |
|---|---|
| txt / md | read as UTF-8 |
| docx | mammoth |
| doc | word-extractor |
pdf-parse | |
| PNG / JPEG / WebP | LLM OCR via llmClient.generateText on gpt.smart, temperature 0 |
| URL | fetched 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.
- 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. - Extract text (table above).
- Upload bytes to GCS at
knowledge-base/<orgId>/<yyyy>/<mm>/<uuid>-<sanitized name>(needsGCP_STORAGE_BUCKET). - Insert
file_storage(categoryknowledge-base, providerGCS). - Insert the next version of
knowledge_documents, inactive andready. - Chunk and embed, each chunk sequentially, on Vertex
gemini-embedding-2through the direct@google/genaiSDK (locationus,taskType: 'RETRIEVAL_DOCUMENT'). A code comment calls this SDK path temporary. The model list holds one locked model. - Insert chunks and update
chunk_count. - Activate.
activateVersionin 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. - Hard delete in the background.
knowledgeDeletionTickruns 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 urgentaudit_trailsystem_issue("Nexus source deletion is delayed"). Retrieval drops the document immediately becauserequestDeletionsetsisActive=falseand corpus reads require it.
Evidence
packages/services/src/knowledge/library.ts:27-39— MIME types, 5 MBpackages/services/src/knowledge/extraction.ts:11,26-27,111-161,167-224,263-326— extractors, OCR tier, URL fetchpackages/services/src/knowledge/ingestion.ts:1-3,38-196,214-275— chunkingapps/api/src/trpc/knowledge-base/index.ts:604-782— direct proceduresapps/api/src/app.ts:237-239;apps/api/src/trpc/nginxTimeoutContract.test.ts:66-83— 8 MB body, 5-min laneapps/web/src/ui/new/knowledge/KnowledgeBulkPanel.tsx:82-110;packages/webapp-contracts/src/knowledge/index.ts:148— bulkpackages/gcp/src/storage/knowledge.ts:16-31,83;library.ts:451-628— GCS key, insert, embed, activate, rollbackpackages/llm/src/embeddings.ts:9-14,28,152-172,221-263— embedding model and SDKpackages/repositories/src/surfaces/knowledge.ts:125-126,333-360,596-655— active-only reads,requestDeletion,activateVersionpackages/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.
- Create session. Snapshot the selected workflow's corpus (snapshot id + org corpus revision); persist with mode
addorupdate. - Prepare: claim and limits. Hash inputs; combined sources ≤5 MB; claim with
expectedRevision 0. - 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"). - Prepare: knowledge units. The LLM proposes atomic units with exact source quotes.
validateAndRenderNexusCurationchecks spans, exact quotes, critical facts and duplicates (codes includemissing_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). - Stale-corpus check. If the snapshot changed since session creation: "Start a new ingest session".
- 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). - Conflict check before publication. Each rendered proposal becomes a probe; probes plus the current corpus go through
nexusResearcher.scanConflicts. Adirect_conflictagainst anything but the proposal's own replace target throwsCONFLICT. - Stage drafts as inactive documents with chunks and embeddings (
createKnowledgeDocumentFromTextwithstaging). - Operator review. Edit, split/combine, exclude or retarget;
reviseNexusIngestProposalbumpsproposal_revision. - Apply (
applyApprovedBatch): check idempotency key, expiry and proposal revision; incrementknowledge_corpus_revisionsonly if it still equalsbase_corpus_revision(CAS); recompute snapshot; verify staged docs are not active or deleting; activate the whole batch in one transaction. - Cleanup. Raw staging and proposal content are deleted on apply, abandon or expiry; the deletion tick runs
processKnowledgeIngestCleanupBatchfirst.
| Limit / setting | Value |
|---|---|
| Per file and combined sources | 5 MB |
| Extracted text | ~75k estimated tokens |
| Session TTL | 7 days idle, 30 days max |
| Prepare / propose model | authored gemini.fast, reasoningEffort: 'minimal'; remapped to gpt.fast at runtime |
| Prepare attempt | 120 s timeout, 32k output cap |
| Fact classifier, conflict scan | 30 s attempt timeouts |
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 codesapps/api/src/trpc/knowledge-base/nexusCurationOrchestration.ts:13,91— one retrypackages/llm/src/nexusResearcher.ts:33-40,784-822— classifier, timeoutspackages/repositories/src/knowledgeCuration.ts:365+,396-552—applyApprovedBatchCASpackages/services/src/knowledge/deletionLifecycle.ts:25-70;knowledgeDeletionTick.ts:20-25— cleanuppackages/llm/src/prompts/knowledge/nexusCuration.ts:3-18— curation models and limitsapps/api/src/trpc/nginxTimeoutContract.test.ts:85-91— durable-jobs TODOplanning_docs/nexus-knowledge-curation/epic.md:7;adr.md:22-37— built status
ElevenLabs sync (voice)
syncElevenLabsis atrueAdminProcedureusing envELEVENLABS_API_KEY. It returns{status:'scheduled'}and runs on a microtask; an in-process guard returnsalready_in_progressfor a concurrent sync of the same org and folder.- Resolve the KB folder by id, or by name (creating it if absent).
- Delete every document in that folder.
- Load
getFullKnowledgeBankfor 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 orKnowledge_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 procedurepackages/services/src/knowledge/elevenLabsSync.ts:2-16,67-189,214-234— scheduling, guard, wipe, uploadapps/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-clickpackages/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 workflow | Restrict flag | Knowledge it can read |
|---|---|---|
| Default | (any) | ['__default__'] |
| Named | on | [named] only |
| Named | off | ['__default__', named] |
Text agent: step by step
Entry point packages/workflows/src/defaults/agenticReplyAdapter.ts.
- Scope and engine. Resolve the scope;
useNexusKnowledge = channel !== 'web_chat'. Web chat opted out in commit7a3aae18e(2026-09-15). - Fast-reply preload. If the template has
fastReplyfor 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. - 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. - Planner decides. "Nexus is deliberately invisible to the planner". Persisted graph keys are unchanged:
knowledge_search_rag, the typo aliasknowledge_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). - 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 onunavailableorinvalid_output; the terminal is cached per request. - Canonical corpus.
buildNexusCorpusdoes 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 returnsdisabled_empty_corpus. No ranking, no top-k. - 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 ongpt.ultra(reasoning high, fallbackclaude.smart) returns, per customer request, selected section ids and amissingDetail. It does not write the answer. The host renders the memo from the original source text and returnsresearch_completedwith 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. - Server validation checks claims and evidence against the corpus. Invalid output →
invalid_output; provider failure/timeout →unavailable;corpus_ineligible→unavailable. - 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_completedthe finalizer usesNEXUS_MEMO_REPLY_SYSTEMandNEXUS_MEMO_REPLY_REVIEW_SYSTEM. Host guards:nexusActionGuard(a "completed" or "promised" action needs a successful tool result; channel mentions must be declared) andnexusValueTokens(no new material numbers or prices; money-like values from the supported text must be kept). - Effects and provenance. A
nexusEffectwith an idempotency key from target, conversation, template, corpus snapshot and status. An urgentneeds_assistanceaudit only forconflicting_evidence,invalid_outputandunavailable; failures also emit a system issue. The citation snapshot goes intoagentic_responsemetadata, and a knowledge-query observation draft is staged in the runner'stx_finaldomain-write buffer.
Status (enforceNexusMessagingOutcome) | Customer reply | Escalation |
|---|---|---|
invalid_output, unavailable | Suppressed | Silent escalation |
answered | Sent | None from Nexus |
partially_answered, insufficient_evidence, conflicting_evidence, disabled_empty_corpus | Sent (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.
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 filterspackages/db/src/schema/agenticMessagingTemplates.ts:144,285-286;apps/web/src/features/foundry/graph/FoundryGraphEditor.tsx:171— restrict flag and toggleagenticReplyAdapter.ts:176-179,209-247,326-329,365-530,819-822— channel rule, preload, hidden tools, attempts, executor bindingpackages/workflows/src/defaults/agenticReplyKnowledgePreload.ts:13-62;packages/services/src/knowledge/preloadCorpus.ts:11— 16k preloadpackages/llm/src/agentic/plannerNode.ts:305-306,328-334,408-412— invisible to planner, forced exitagenticReplyKnowledge.ts:39-51,356-478,564-567— attempts, descriptors, effect, snapshot, question prompt, ineligible mappingpackages/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 capspackages/llm/src/nexusResearcher.ts:575-755;nexusResearchMemoGeneration.ts:16-125;prompts/nexusResearchMemo.ts:1-13— strategies and memopackages/workflow-composition/src/defaultMachines.ts:59;apps/api/src/app.ts:144;apps/worker/src/agentPreviewConsumer.ts:45— production callerspackages/services/src/knowledge/nexusResearcher.ts:100-320— server validationpackages/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 guardspackages/workflows/src/machines/textMessageEscalationAudit.ts:132-215— auditspackages/services/src/knowledge/search.ts:7-8,70-98,240-266;surfaces/knowledge.ts:895-947;buildDefaultMachineDeps.ts:429-433— legacy RAGplanning_docs/workflow-scoped-knowledge/epic.md:27,74,321-331— voice out of V1
Sub-features
| Sub-feature | Status | Runs where | Who uses it |
|---|---|---|---|
| Query diagnostics / observed knowledge gaps (ZUBEA-268) | GA rollout verification pending per doc | Runner (text capture), webhooks (voice capture), scheduler hourly | Automatic; operators read Review |
| Diagnostics automation (weekly taxonomy) | flag: nexus_taxonomy | Scheduler: weekly + 15-min poller | Zube admin toggles; runs automatic |
| Diagnostics recovery | S1 GA · S2–S4 planned | Runner; future operator script | Engineers |
| Researcher (ZUBEA-261) | GA | Workflow runner, worker preview | Every text channel except web chat |
| Test Nexus | GA | API | nexus.update operators |
| Conflict finder | GA as ingest check; Conflicts tab not built | API (curated ingest prepare) | Implicit in Add |
| Knowledge curation (ZUBEA-263) | GA | API, synchronous | nexus.update operators |
| Semantic remediation groups | planned experiment stopped, no code | — | — |
| Generic parity contract | GA design in code; org-flag part superseded | Runner | All text clients |
| Workflow-scoped knowledge | GA (doc says draft — stale) | Everywhere the corpus is read | Foundry template authors |
| ElevenLabs KB sync | admin-only | API, detached microtask | Zube true admin |
| Nexus Review in demo orgs | ops tool | zube-demo-org skill | Demo 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.
- Text capture. Before the transcript is sanitised for the LLM,
textMessageReplyActorresolves the latest user message'sreferenceId, timestamp and text. After the reply,buildTextKnowledgeQueryObservationDraftcreates a deterministic-id observation when Nexus endedpartially_answered/insufficient_evidence/conflicting_evidence(kept as authoritativedirectDisposition), or endedresearch_completed, or an eligible custom tool succeeded (no direct disposition). The draft commits atomically with the workflow transition intx_final. If an eligible terminal cannot produce a draft, the actor reportsknowledge_query_observation_draft_not_stagedto error tracking. - Eligible custom tools opt in with
diagnosticEligibility: 'knowledge_query': MiCampus (get_properties) and Road Scholar (get_trip_list). - Voice capture. A valid ElevenLabs
post_call_transcriptionpersists a capture event before the webhook acknowledges. - Hourly job
knowledgeQueryDiagnostics(cron0 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 tologger.error. - 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).
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, statuspackages/workflows/src/machines/textMessageReplyActor.ts:92-98,139-154;textMessageGenerationDiagnostics.ts:44-60,154-210— capture, tx_final stagingagenticReplyKnowledge.ts:178-264;agenticReplyAdapter.ts:921-939— draft builder, reason codespackages/client-tools/src/tools/clientVoiceToolDefinition.ts:18,67,106;clients/micampus/customTools.ts:244;clients/roadScholar/customTools.ts:51— opt-insapps/webhooks/src/inbound/elevenlabs/dispatch.ts:303-369— persist before ackpackages/services/src/scheduler/jobs/knowledgeQueryDiagnostics.ts:6-212;elevenLabsKnowledgeGapMaterializer.ts:587— hourly jobpackages/services/src/knowledge/knowledgeGapProcessor.ts:23,421-676— processing and groupingpackages/services/src/knowledge/knowledgeGapGeneration.ts:14,197-276;apps/scheduler/src/composition.ts:351-354— modelsapps/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.)
runWeekly(nexusTaxonomyWeekly,0 4 * * 0Europe/London) checks the row matcher is available, then pages over orgs with the flag on anddiagnostics_enabled.- No catalog:
initial_backfill. One structured bootstrap call over all of the org's finding text; counts tokens first and blocks withcorpus_too_largeabovemaxInputTokens: 900_000. Then one batch item per finding, to OpenAI if configured, else Vertex. - Catalog exists:
weekly_matching. JEV (OpenRoutermicrosoft/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). WithoutOPENROUTER_API_KEYthe matcher is an "unavailable" stub. nexusTaxonomyPoller(every 15 min) collects finished batches and publishes only validated rows.- 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, gatespackages/webapp-contracts/src/admin/index.ts:224-258;packages/repositories/src/knowledgeGapTaxonomyRuns.ts:55;NexusDiagnosticsWorkspace.tsx:252-258;useKnowledgeReview.ts:26— flagpackages/services/src/scheduler/jobs/nexusTaxonomyWeekly.ts:3-29;nexusTaxonomyPoller.ts:3-22— jobspackages/services/src/knowledge/nexusTaxonomyAutomation.ts:127-175;nexusTaxonomyBootstrap.ts:206-280— run logicapps/scheduler/src/composition.ts:264-268,300-350;packages/llm/src/nexusTaxonomy.ts:18-25— providers, JEV thresholdsapps/api/src/trpc/knowledge-base/index.ts:456-527;NexusProcessedTaxonomyPanel.tsx— group API and UIpackage.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.
resolveLatestTextKnowledgeQueryDiagnosticOriginreads the unsanitisedmergedTranscriptand passes the origin beside the prompt; failures surface as reason codes. Commit1c1a33e31(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 exacttx_finalproof, 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/ optionalclassifyKnowledgeUpdateFactsinpackages/ports, adapter inpackages/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 sameresolveKnowledgeWorkflowScope; template must be active, text, with knowledge tools on. Calls the sameanswerNexusQuestionas 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 byvalidateNexusConflictGeneration. R5 labelled evaluation: 100% direct precision and recall (50/50), 0/60 benign mislabels, 0/100 prompt injections. NoscanNexusConflictsprocedure 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— recoveryplanning_docs/nexus-researcher/handoff.md:5-8,106-140;r7-client-cutover.md:3-18,300-355,437-450— researcher statuspackages/ports/src/nexusResearcher.ts:448-458;packages/llm/src/nexusResearcher.ts:739-823— port and adapterapps/api/src/trpc/knowledge-base/index.ts:226-420;nexusQueryRateLimiter.ts:86-97;apps/api/src/app.ts:292-296— Test Nexusapps/worker/src/agentPreview/templateTestReply.ts:113-118;apps/web/src/ui/new/agents/foundry/TextTestDiagnostic.tsx:13-21— preview diagnosticnexusConflictScanner.ts;planning_docs/nexus-researcher/conflict-evaluation.md:3-20;nexus-query-diagnostics/epic.md:421-423— conflict finderplanning_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— curationplanning_docs/nexus-semantic-remediation-groups/index.html— stopped experimentplanning_docs/nexus-generic-parity/epic.md:7,19-48,59-66;grading-rubric.md— parity contractplanning_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 rulesapps/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.
| Area | Old UI (NexusDiagnosticsWorkspace) | New UI 2.0 (NewKnowledgeWorkspace) |
|---|---|---|
| Tabs | Documents, Ingest, Review (/nexus/documents|ingest|review) | Documents, Review; buttons Test and Add |
| Documents | KnowledgeBankTransportPage: list, detail, upload, URL, text, bulk, edit, move workflow, delete, delete-all, ElevenLabs sync | Documents tab (sync panel KnowledgeSyncPanel) |
| Curated ingest | NexusIngestPanel | Add opens KnowledgeIngest |
| Review | NexusReviewPanel, or NexusProcessedTaxonomyPanel when nexus_taxonomy is on | Findings with Repair (Add with the requirement) and Test (pre-filled); Resolve / Dismiss / Reopen |
| Test Nexus | Card 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.
| Permission | Allows |
|---|---|
nexus.view | All reads: documents, findings, scope; knowledge-base file downloads |
nexus.update | Every mutation, including paid Test Nexus and ingest |
| True admin | ElevenLabs sync |
Feature flag nexus_taxonomy | Set by an admin on /admin/feature-flags |
| Scheduler job | Cron | Purpose | Status |
|---|---|---|---|
knowledgeDeletionTick | */15 * * * * * (15 s) | Hard-delete GCS and rows; clean ingest staging | GA |
knowledgeQueryDiagnostics | 0 0 * * * * (hourly) | Observed-gap capture and grouping | GA |
nexusTaxonomyWeekly | 0 4 * * 0 Europe/London | Catalog bootstrap / weekly matching | flag: nexus_taxonomy |
nexusTaxonomyPoller | */15 * * * * | Collect batch results, publish validated rows | flag: nexus_taxonomy |
| Script / asset | Purpose | Status |
|---|---|---|
scripts/nexus/prepareApprovedBackfill.ts, approvedBackfill.ts, README.md | Taxonomy catalog seed rehearsal (bun run nexus:prepare-approved-backfill) | ops tool |
planning_docs/nexus-researcher/client-knowledge-sources.md | MiCampus cutover: nine sources to ingest into __default__ (doc, not a script) | ops tool |
client-base-prompt-patch.md | Base-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 switchapps/web/src/features/knowledge/NexusDiagnosticsWorkspace.tsx:261-349;router.ts:507-526;useNexusSearchState.ts:17— old UIapps/web/src/ui/new/knowledge/KnowledgeWorkspace.tsx:16-154;useKnowledgeReview.ts:99-120— new UIapps/web/src/ui/new/contacts/conversations/GenerationPanel.tsx:98— sources pillapps/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— permissionspackages/services/src/scheduler/registry.ts:20-23,69-72— job registration
Known limitations and open problems
| # | Problem | Detail |
|---|---|---|
| 1 | Corpus size cap | Only 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. |
| 2 | Synchronous ingest | Prepare 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. |
| 3 | Shadow-pilot privacy decision | Evaluation-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). |
| 4 | Test Nexus history | Runs are ephemeral by design; persisted history is a two-way follow-up. |
| 5 | Voice | Workflow 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. |
| 6 | Recovery backfill | Unbuilt and blocked on a decision. The 71 historical failed observations lost their payloads during failure cleanup. |
| 7 | Semantic grouping quality | Remediation-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. |
| 8 | Taxonomy gates | Independent 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. |
| 9 | Query preservation | One MiCampus multi-part conversation dropped an aspect from the internal Nexus question; recorded as a diagnostic, not a regression. |
| 10 | Embedding path | Direct @google/genai SDK marked temporary; ingest embeds chunks sequentially, one call each. |
| 11 | Web chat | Opted 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— capnginxTimeoutContract.test.ts:85-91;nexusIngestProcedures.ts:47-48— synchronous ingestplanning_docs/nexus-researcher/epic.md:166-171;transcript-evaluation.md:107-126;r6-evaluation.md:102-117— pilot, Test historyelevenLabsSync.ts:9-16,220-226;workflow-scoped-knowledge/epic.md:124,321-331— voiceplanning_docs/nexus-diagnostics-recovery/index.html— backfillnexus-query-diagnostics/epic.md:333-337— grouping limitsnexus-diagnostics-automation/index.html:168,171— taxonomy gatesr7-client-cutover.md:341-347— dropped aspectembeddings.ts:152-153;library.ts:465-475— embedding pathagenticReplyAdapter.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.
Cross-cutting facts first
Where intelligence runs
| Process | What 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/worker | Only 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.generateObjectapplies this unless the input has a video attachment.gpt.smart/gpt.fast/gpt.nanomap togpt-6-luna;gpt.ultratogpt-6.1-sol; both Gemini constants togemini-3.8-flash; Claude tiers tous.anthropic.claude-sonnet-5. - Structured-output fallback is cross-provider by default, e.g.
gpt.fast → gemini.fast → claude.fast. A call opts out withcrossProviderFallback: falseorstructuredOutputFallbacks: []— several jobs below do. - Scheduler batch work is OpenAI-first.
OpenAIFirstBatchClientuses OpenAI batch as primary whenOPENAI_API_KEYis set, with Vertex batch as fallback, using the model IDs ofgpt.fastandgemini.fast.
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 runpackages/workflows/src/machines/onConversationComplete.machine.ts:1-33,packages/workflows/src/runner/workflowRunnerAudit.ts:172-219— runner-side intelligenceguidance/engineering-constraints.md:103— single-instance schedulerpackages/llm/src/models.ts:89-97,:104-191,:196-210— model IDs and Gemini→GPT rewritepackages/llm/src/clientGeneration.ts:145-151— rewrite skipped for videopackages/llm/src/structuredOutputFallbacks.ts:4-17,clientGenerationRoutes.ts:97-127— fallback chainsapps/scheduler/src/composition.ts:240-277— OpenAI-first batch clientplanning_docs/insights-v2/README.md:21-24,planning_docs/hourly-flex-insights/epic.md:27— stale Gemini claims
Access vocabulary
aclProcedure('<perm>')insights.view.@getzube.com, including while impersonating a customer user.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 definitionapps/api/src/trpc/trpc.ts:326-372,packages/db/src/schema/organizationFeatureFlags.ts:8-27— feature procedure and tablepackages/webapp-contracts/src/admin/index.ts:225-271— the four flags, all default-off
Feature summary
| Feature | Status | Trigger / schedule | Model / tier | Tables | UI surface |
|---|---|---|---|---|---|
| Daily metrics + content insights | GA | aggregateInsights daily 12:05 UTC | gemini.fast authored (starts gpt.fast); batch OpenAI-first | daily_metrics, daily_content_insights, content_insight_facts | /insights/* (insights.view) |
| Monthly rollups | GA | aggregateMonthlyInsights 13:00 UTC, day 1 | none (SQL) | monthly content insights, monthly drop-off metrics | ranges > 60 days |
| Content-insight curation | GA | anchored fortnightly + startup | gpt.ultra high, no fallback | content_insight_configurations, content_insight_curation_states | none (catalog maintenance); category CRUD admin-only |
| Call Insights + lead score | GA | on_conversation_complete | gpt.smart (GPT-6 Luna, high effort) | targets insight columns | target Insights tab |
waitingOnTarget | admin-only | inside Call Insights | gpt.smart | targets | target Insights tab |
| Conversion workspace + CRM projection | flag: insights_conversion | projection rebuild every 10 min + startup | — (not stated in research) | crm_conversion_*, crm_stage_* measurements | Conversion workspace |
| Deferred Sentiment Analysis | admin-only | 5,35 * * * * UTC | gpt-6-luna batch, else gemini-3.8-flash | sentiment_analysis_observations | target Insights tab (admin) |
| Custom analyzers | GA | same half-hour job | same as above; online helper gpt.fast | organizations.custom_analyzers → content insights custom | /account/analyzers |
| Guardrail counting | GA | each inbound text turn | planner matches; code counts | transcript item metadata on conversations | agentic template config |
| Escalation routing (Tier 1/2/3) | GA | before an urgent audit row persists | Tier 2: Microsoft Decision-1 | audit_trail | /account/escalations, /reminders/audit-trail |
| Guardrail email forwarding | GA (unverified rollout) | post-commit, inbound email / awaiting-action | none | — | guardrail emailForwarding opt-in |
| Lead lifecycle stage (shadow) | flag: lead_lifecycle_stage | parallel to Call Insights | Decision-1 | lifecycle observation | none ("Nothing is displayed") |
| Reminders | GA | processDueReminders hourly :00:20 | gpt.fast | audit_trail | /reminders/audit-trail |
| Acknowledgement metrics | GA | read-time | none | audit_trail | /insights/audit-metrics |
| Drop-off observation (current) | admin-only | 02:15 UTC reconcile + per-minute processor | gpt.fast, high, no fallback | dropoff_observations | /contacts/revival |
| Legacy drop-off tables | legacy | monthly rollup only | none | thread_dropoff_events, daily_/monthly_dropoff_metrics | true-admin read procedures |
| Daily loss-reason generation | flag: insights_conversion admin-only review | branch of the 12:05 UTC tick | gemini-3.8-flash via OpenAI or Vertex loss batch | loss_insight_* | Conversion loss reasons; /insights/loss-records |
| Historical drop-off regeneration | ops tool | CLI, per org + cohort date | same explanation call | historical_regeneration_* | none |
| Client report generation | custom: MiCampus custom: Stay Club custom: Addison Lee | processDueReports every minute :30 | none (deterministic) | report_definitions, report_runs | /integrations/reports |
| Client semantic routing | custom: Lingua custom: MiCampus custom: Stay Club | client hooks | gpt.fast (Lingua also Decision-1) | — | none |
| Lead auto-assignment | GA | new unassigned target creation | llm strategy: gpt.fast | target_assignment_events | org accessControlSettings (route not in research) |
| Voice transfer outcome buckets | GA | inside daily metrics | none | daily_metrics | Insights Performance |
| RevOps deals | flag: revops_deals | ops load script | pipeline not in tracked repo | revops_* | /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
aggregateInsightsruns 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
channelMetricsJSONB,avgLeadScore,leadScoreDistribution,hourlyBreakdown,dayOfWeekand 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. Thehllcolumn is a custom Drizzle type over the Postgreshllextension;hll_*functions are on the raw-SQL allowlist.
daily_metrics sketches hash the raw target ID. HMAC pseudonymisation applies only to content-insight facts.Daily content insights and pseudonymised facts
- 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). - Types: built-in
concerns,competitors,unanswered_questions,interests,decision_factors,caller_profiles;customtypes come from each analyzer'saggregationSpec. The enum also holdsdropoff_reason,outcome,sentiment_dissatisfaction,loss_reason. - Category normalisation: each raw term maps to an existing category code or a proposed new one (
code,displayName,keywords). Single-call path:generateObject, authoredgemini.fast(starts ongpt.fast), sharedinsightsCategorizeSystemPrompt. Batch path when a group has more than one unresolved term and the batch client is wired:batchGenerateKeyedObjects, sheet idinsights::<type>. Failed batch rows get up to ten single-call recoveries. - Fail, don't invent: any decision still missing throws
BatchCategoryNormalizationIncompleteError; the job fails rather than making a category from the raw term. - Pseudonymise:
targetPseudoId = HMAC-SHA256(secret, targetId), secretaggregatedInsightsHmacfromAGGREGATED_INSIGHTS_SECRET_HMAC. A missing secret throws inside the org loop and the outer handler aborts the remaining legacy tenants for that run. - Write (
appendDailyContentInsightContributions, one transaction per scope): resolve aliases to canonical codes; insert only new (canonical category, pseudoId) memberships intocontent_insight_facts— "first observed target/day/canonical-category membership owns its counted snapshot"; upsert thedaily_content_insightsbucket withunique_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/deleteCategoryare 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 (anchor2026-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-urgentsetup_pendingaudit row. Internal error →logger.errorplus urgentsetup_failedaudit 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, promptcontent-insight-curationv2. Allowed actions are onlyretain | 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, timezoneaggregateInsights.ts:276-279,:303-345,:426— 8-day window, inputs, writepackages/db/src/schema/dailyMetrics.ts:35-140,:169-200— row shapepackages/repositories/src/surfaces/metrics.ts:56-69,:87-112;packages/db/src/schema/hll.ts:3-23;guidance/engineering-constraints.md:82— HLLaggregateInsights.ts:58-65,:87-116,:126-129,:474-483,:640-689;contentInsightFacts.ts:16-28— types and sourceaggregateInsightsCategoryNormalization.ts:53-68,:106-136,:142-182,:193-204— normalisationaggregatedInsightsSecret.ts:1-12;aggregateInsights.ts:443-447,:724-728,:773-777,:840-850— HMACpackages/repositories/src/contentInsightContributions.ts:123-163,:183-295— write pathcontentInsightFacts.ts:30-59,dailyContentInsights.ts:21-61— tablesaggregateMonthlyInsights.ts:53-57,:94-135,:151-162;packages/repositories/src/surfaces/insights.ts:520-545,:602-625— monthlypackages/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 sidecurateContentInsights.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— curationplanning_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.
| Piece | Status | Notes |
|---|---|---|
Target detail /target/$id, one Insights tab; /contacts/$id redirects | GA | Base insights (summary, concerns, competitors, next step, actionable insights…) for all authorised users. |
waitingOnTarget (max five things the lead owes) | admin-only | Produced 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 Analysis | admin-only | See §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_conversion | Backed 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 streams | retired | No 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) | planned | Held. |
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.
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-1592apps/web/src/features/contacts/useContactDetailSearchState.ts:6,apps/web/src/routes/router.ts:364-380,:858-872apps/web/src/ui/new/contacts/detail/ContactInsights.tsx:130-150,:172onConversationComplete.persistence.ts:596,:608-647;packages/db/src/schema/targets.ts:328;packages/llm/src/prompts/insights/callInsights.ts:343,:656-659—waitingOnTargetapps/api/src/trpc/insights/salesMotionProcedures.ts:428-474— admin sentiment readapps/api/src/trpc/insights/crmOutcome.ts:560-697;rebuildCrmConversionProjections.ts:51-60;crmConversionProjectionBuildService.ts:73;crmConversionProjections.ts:46,:99,:247;crmStageMeasurements.ts:52,:139,:211packages/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).
- Short-circuit low-token transcripts (
shortCircuitLowTokens). - Not-interested classification with
gpt.fast. On that branch the machine writes score 0 plus a summary. Voice'son_call_completeruns no insight generation; its only insight side effect is a fixedscore=0, "Caller indicated they are not interested." write. Voice Call Insights come fromon_conversation_complete. - Generate (
generatingInsights): the adapter resolves the workflow's content-insight configuration and callsgenerateCallInsightsatgpt.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). - Persist in lane 1, committed in the runner's
tx_final:targets.updateTargetInsights, skipped when target status iscompleted | override | help_needed | paused. A conversation-summary fallback write also runs. - Reconcile reminders with
gpt.fast(reconcilingReminders).
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,:524packages/services/src/conversations/classifyNotInterested.ts:12,:35;onConversationComplete.persistence.ts:175-216,:560-605,:650-682packages/workflows/src/machines/onCallComplete.machine.ts:1-11defaultMachineActorAdapters.ts:454-490;packages/services/src/insights/callInsights.ts:19,:210-247;packages/llm/src/models.ts:167-174packages/llm/src/prompts/insights/callInsights.ts:103-106,:250-330,:613-640— schema and rubricpackages/services/src/reminders/validator.ts:33,:109-164README.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, cron5,35 * * * *UTC, non-singleton, needs thellmBatchresource. - 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'saggregationSpec. - Model: with a batch client,
BATCH_MODEL_ID = 'gpt-6-luna'through OpenAI-first batch (Vertex fallback); otherwisegemini-3.8-flash. - Store:
sentiment_analysis_observations, one row per (org, conversation, transcript hash) withmessageStartIndex,messageCount,observedAtand JSONBresult. 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 onlinegenerateCustomAnalysishelper usesgpt.fast; in services/workflows the scheduled path is the batch job.
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,:576apps/scheduler/src/composition.ts:255-263packages/db/src/schema/sentimentAnalysisObservations.ts:18-61,:118-134packages/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-144planning_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,escalateAfterX1–10, default 1),escalate,respondAndEscalate. Each can opt intoemailForwarding. - Hidden identity:
guardrailIdis stable across edits;guardrailRevisionIdbumps only on behavioural change; the server reconciles dropped IDs. Backfill:bun run migration:backfill-guardrail-ids.
"LLM matches, code counts"
- The planner copies the matching guardrail's
guardrailIdintoguardrail_directive.matchedGuardrailId(or null); planner and finalizer propagate it. The production prompt no longer doesprior_hits/total_hitsarithmetic (those strings appear only in a test file). - Code writes a
GuardrailEvaluationMetadatarecord on the triggering inbound transcript item: action,lookbackWindowSeconds,priorHitCountInLookback,totalHitCountInLookback = prior + 1. countPriorGuardrailHitsInLookbackcounts earlier evaluations in the same conversation transcript with the sametemplateIdandguardrailId, default lookback 3 days, deduplicated byguardrailViolationId.- Threshold:
escalatealways;respondAndEscalatewhentotalHit ≥ escalateAfterX;redirectwhenpriorHit ≥ escalateAfterX— soescalateAfterXis the number of redirects allowed before handoff. - 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.
- 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_configuredand routing falls through. - Tier 3: push to
defaultPushUserIdif supplied, else email toopsEmail, else nothing. - Runner wiring (slice 4a): the workflow runner calls the synthesiser for urgent, non-
system_issueentries withopsEmail: nulland no default push user, so a workflow escalation with no matching rule sends nothing and is visible in the app only.processDueReminderssupplies adefaultPushUserIdand 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.
Evidence
planning_docs/guardrail-escalation-intelligence/epic.md:5-16,:48-58,:297-320,:353-358;checklist.mdslice 1packages/webapp-contracts/src/agentConfig/index.ts:119-157;apps/api/src/trpc/templates/guardrailIdentity.ts;package.json:132packages/llm/src/prompts/fragments/guardrails.ts:7-10;plannerNode.ts:196-215,:474-480;finalizerNode.ts:90-181packages/workflows/src/machines/textMessageGuardrails.ts:23,:39-74,:474-569;packages/db/src/schema/conversations.ts:66-72packages/services/src/auditTrail/escalationSynthesis.ts:115-192,:274-454packages/workflows/src/runner/workflowRunnerAudit.ts:172-219;processDueReminders.ts:391-400packages/notifications/src/ses/escalationEmail.ts:19-39;apps/web/src/routes/router.ts:791packages/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).
| Use | Behaviour | Gate |
|---|---|---|
| Escalation rule Tier 2 | One 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 syncback | Non-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 matching | Uses 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-38packages/llm/src/jevTransport.ts— OpenRoutersystemoneURLpackages/llm/src/escalationRuleDecision.ts:17-44,:59-89,:215-267;jevLeadLifecycle.ts:19-20;jevCampusSelection.ts:16-17packages/app-composition/src/runtimeInputs.ts:160-187;packages/config/src/env.ts:251packages/services/src/insights/leadLifecycle/conversationClassifier.ts:19-24,:112-206;packages/webapp-contracts/src/admin/index.ts:256-262packages/services/src/runtime/clientHookEffects.ts:171-231;packages/workflows/src/clients/lingua/hooks/crmSyncback.ts:225-245packages/services/src/knowledge/nexusTaxonomyMatchers.ts:305
7. Audit trail, take-over rows, reminders, acknowledgement metrics
audit_trail: 16-value type enum; sourcesystem|user|zube|external; severityinfo|warning|error|urgent; categorypositive_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_issueinputs to error tracking instead of persisting them. - Take-over row:
buildCannotRespondTakeOverAuditproduces the standard "AI Requested Human Help" row with a deterministic ID. - Notification cooldown: 24 h default, bypassed for human-owned status transitions.
- Reminders:
processDueRemindershourly at :00:20 validates and disposes due reminders withgpt.fast. UI/reminders/audit-trail. - Acknowledgement metrics (
aclProcedure('insights.view'), route/insights/audit-metrics): scope is urgent rows whose category is notsystem_issueorinformational, acknowledged with a non-null acknowledger, in the org-local date range (org timezone, UTC fallback); pending is the same scope withacknowledged=false. Non-goal: no acknowledgement event ledger, so only the latest acknowledger counts.
Evidence
packages/db/src/schema/auditTrail.ts:20-60,:79-120guidance/engineering-constraints.md:136-141;packages/repositories/src/surfaces/auditTrail.ts:50-54,:145-153,:586-595,:660,:729packages/services/src/auditTrail/cannotRespond.ts:17-30;notificationCooldown.ts:11-89processDueReminders.ts:715-725;apps/web/src/routes/router.ts:396,:489-496planning_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.
| Generation | Status | What it is |
|---|---|---|
| 1. Legacy tables | legacy | thread_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" design | planned (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 explanation | admin-only | Below. |
Current pipeline
reconcileSalesMotionObservations, daily 02:15 UTC: "enqueues the prior 48–72 hour drop-off cohort". PagesdropoffObservations.listDailyCandidates, rebuilds a deterministic candidate, enqueues keyed by snapshot date and prompt hash.- 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. 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 (elsesource_changedand invalidate), rejects journeys over 700k rendered characters, calls the LLM, and publishes in a source-fenced transaction.- 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. - Output: nullable
causalReason(basis: explicit_evidence|contextual_inference, existing category ID or new proposal, 1–4 evidence refs) and nullabletopic(code, label, 1–4 refs); strict, no prose. The prompt forbidsstopped_responding,unknown,otheras causes and forbids inferring cause from topic alone; the host rejects unknown evidence refs, silence categories and colliding new codes. - 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. - Surface (true-admin):
/contacts/revival(/insights/revivalredirects);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.
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:48planning_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-230reconcileSalesMotionObservations.ts:23-31,:42-90packages/repositories/src/dropoffObservations.ts:130-228;dropoffCandidateDomain.ts:21-31,:340-370processSalesMotionObservations.ts:7-8,:28-56;packages/services/src/insights/dropoffObservation.ts:25-26,:91-193,:221-267packages/llm/src/prompts/insights/dropoffExplanation.ts:7-53;packages/db/src/schema/dropoffObservations.ts:79-114apps/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_runsandloss_insight_records, plus aloss_insight_reason_collationsartifact that populates the sharedloss_reasoncatalog ininsight_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
aggregateInsightstick: claims a UTC day window per org (duplicate ticks make no provider calls); candidates are targets with a resolved CRMlostoutcome 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). Modelgemini-3.8-flash,maxBatchAttempts: 1per adapter call, thinkingMEDIUM; composition wiresOpenAILossInsightBatchwhenOPENAI_API_KEYis present, elseVertexLossInsightBatch. Tablesloss_insight_daily_runs,loss_insight_daily_items. Terminal reasons such assubmission_uncertainandloss_snapshot_base_changedare 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 unscopedgetLossReasonspath was removed); internal reviewlossRecords.getOverview/list/getDetail(true-admin) at/insights/loss-records; true-admin category toolsresolveOrCreateLossReasonCategory,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.htmlpackages/db/src/schema/lossInsights.ts:29,:72;lossInsightReasonCollations.ts:72;lossInsightDaily.ts:54,:103packages/services/src/insights/dailyLossGeneration.ts:68-95,:121-170,:312,:611-688packages/llm/src/insights/lossInsightBatch.ts:36,:169-176;apps/scheduler/src/composition.ts:642-645apps/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 throughnormalizeLossReasonCategory. - Historical regeneration ops tool: recomputes drop-off explanations for past cohort dates with the same
prepareDeterministicDropoffCandidateandgenerateDropoffExplanation. Runner APIpreview,run,runReviewed,rehearse,apply,verify. Manifests are hashed and validated; state inhistorical_regeneration_*tables (manifests, sources, outputs, checkpoints, archived observations/categories, active scopes). - CLI:
scripts/operations/historicalDropoffRegeneration.tswithapply|generate|preview|rehearse|verify; requires explicit--env-file,--organization,--cohort-date("no all-tenant default");applyneeds--applyand--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-230dropoffObservation.ts:181-207,:249-252;packages/repositories/src/dropoffObservations.ts:124-128packages/services/src/historicalRegeneration.ts:1-25;historicalRegenerationContracts.ts:251-276;historicalRegenerationManifest.ts:146-436;packages/db/src/schema/historicalRegeneration.ts:141-378scripts/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 stuckrunningpast a 30-minute TTL) → due-scan (one pending run per missed window, CAS onnext_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:
listReportTypesfilters togenerator.organizationId === actor.organizationId; view/list needorganizationSettings.view; upsert, delete,generateReportneedorganizationSettings.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.mdpackages/db/src/schema/reportDefinitions.ts:30,reportRuns.ts:40packages/services/src/scheduler/jobs/processDueReports.ts:1-18,:694-704packages/workflows/src/clients/reporting.ts:16-26;packages/client-tools/src/clients/reporting.ts:24-34;apps/scheduler/src/composition.ts:115,:225apps/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 aregpt.fast. - Lingua: exact canonical lookup first, then Decision-1, then the
gpt.fastfallback. - 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-67packages/services/src/runtime/clientHookEffects.ts:261,:292,:339,:361,:400packages/workflows/src/clients/stayClub/llmSelectionPrompts.ts:3;cadences/outboundCadences.ts:24;postWorkflowHandoffs.ts:728packages/workflows/src/clients/lingua/hooks/crmSyncback.ts:215-255
13. Lead assignment strategies
autoAssignCreatedLeadruns only for newly created, unassigned targets; settings in orgaccessControlSettingsJSONB.- 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.fastpicks auserIdfrom 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_issueaudits, which the repository diverts to error tracking. History goes totarget_assignment_events.
Evidence
packages/services/src/leadAssignment/autoAssignment.ts:21-55,:76-95,:282-287,:395-690;contracts.ts:139-150packages/services/src/targets/inboundResolution.ts:565;email/inboundDispatch.ts:447;email/historySyncBody.ts:398;metaMessaging/historySyncBody.ts:797;manualImport/createTarget.ts:377packages/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.
| Bucket | Rule |
|---|---|
completed | Transfer completed. |
reachedNoPickup | Last attempt status no_answer or amd_machine. "NOT a Zube fault". |
callerHangup | Last status dialing or dial_call_ended, or a dial/bridge error while the caller hung up. |
failed | Genuine dial or bridge error, or no usable signal. |
notAttempted | No attempt records. |
Evidence
packages/services/src/insights/dailyMetricsReducer.ts:133-204;packages/db/src/schema/dailyMetrics.ts:44-56packages/services/src/insights/performance.ts:197-198,:466;packages/webapp-contracts/src/insights/index.ts:763aggregateInsights.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 withisCheckpoint,pipelineVersion). - Load:
scripts/operations/prodDbRevopsDealLoad*.tsloads "one as-of RevOps deal export into an existing organization": rehearse against a loopback DB, then apply viaprodDbSql, which rolls back unless--commit. - API:
revopsProcedure = organizationFeatureProcedure('conversations.view', 'revops_deals')exposinglistDeals,getDealDay,getConversation,listConversations,searchConversations,getDealNotes. - UI:
/deals(overview, pipeline,/$dealId) behindOrganizationFeatureGate; client-side deal models inapps/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-143scripts/operations/prodDbRevopsDealLoad.ts:19-23apps/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-filesshows no tracked pipeline code
Doc-vs-code drift
| Area | Doc says (stale) | Code says |
|---|---|---|
| Insight LLM route | Gemini 3.6 primary | Gemini tiers rewritten to GPT-6 Luna on initial generation; Call Insights authored as gpt.smart |
| Deferred sentiment / custom | Vertex gemini-3.7-flash | gpt-6-luna via OpenAI-first batch |
| Drop-off model | Gemini 3.7 Flash adjudicates active / dropped_off / plausible customer | Deterministic selection; gpt.fast explains cause/topic only |
sales_motion_observation flag | Gates customer reads | Not in the feature-key enum; reads are true-admin |
| Voice sentiment in admin timeline | Included | Text conversations only |
| Report registry | V1 ships empty | 4 generators registered |
| Guardrail email forwarding | Slice 6 post-June fast-follow | forwardMessage and a post-commit forwarder exist |
| Jev | TypeSafe Jev | microsoft/microsoft-decision-1 via OpenRouter |
| Lingua Jev trial | Behind a per-org default-off flag | No flag check; gated only by the Lingua hook and key presence |
| README revival metrics | Lists revival metric fields | revival_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-24vspackages/llm/src/models.ts:196-210,packages/services/src/insights/callInsights.ts:19planning_docs/hourly-flex-insights/epic.md:27vsprocessDeferredConversationAnalyses.ts:44,apps/scheduler/src/composition.ts:255-263planning_docs/dropoff-observation/epic.md:13-15,:134-139,:151-153vsdropoffObservation.ts:25,dropoffExplanation.ts:7-53,packages/webapp-contracts/src/admin/index.ts:225-230planning_docs/insights-v2/epic.md:256-259vssalesMotionProcedures.ts:463-471planning_docs/client-report-generation/epic.md:6vspackages/workflows/src/clients/reporting.ts:16-21planning_docs/guardrail-escalation-intelligence/epic.md:5-16vsgoogle.ts:515,guardrailForwarding.ts:52planning_docs/jev-decision-research.md:19-21vsescalationRuleDecision.ts:17-18planning_docs/jev-tests/experiments/README.md:3vsclientHookEffects.ts:171-231,crmSyncback.ts:225-245README.md:281-300vspackages/db/drizzle/0065_daffy_strong_guy.sql:48aggregateInsights.ts:5-6vs job body
Open uncertainties
- Production deployment and enablement of every feature: which orgs have
insights_conversion,lead_lifecycle_stage,revops_dealsornexus_taxonomyon, and whetherOPENROUTER_API_KEYandOPENAI_API_KEYare set in production. Not inspected. - Where the historical voice summary/sentiment repair named in the Insights V2 README lives.
- Whether the revival historical regeneration apply ever ran in production (gated as of 2026-09-08).
- Whether a transfer-outcome historical backfill was ever applied.
- Where the RevOps deal-reconstruction pipeline code lives.
- 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.
OutboundCadenceConfig registered per client; no builder UIoutboundCadenceEnabledtrue2b5147e32)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; commit2b5147e32removed 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).
| Feature | Status | Client | Where it runs | Key evidence |
|---|---|---|---|---|
| Generic outbound cadence engine | GA custom: per-client cadences | Stay Club, Lingua, miCampus | scheduler wake sweep → workflow runner | outboundMessagingCadence.machine.ts:723-928; registerClients.ts:531-542 |
| Cadence quiet hours (message window) | UNCLEAR (unverified) | — | — | fields exist; no enforcement found |
| miCampus Google Ads WhatsApp cadence | custom: miCampus live | miCampus | CRM sync → runner → cadence | micampus/postWorkflowHandoffs.ts:104-136 |
| Addison Lee UC1 prospecting drafts | custom: Addison Lee | Addison Lee | email poller → client pre-hook | addisonLee/registerClient.ts:291-330; draftPersistence.ts:1-20 |
| Addison Lee UC2 cold outbound | custom: Addison Lee removal scheduled | Addison Lee | scheduler, 30 s tick | clientOutboundTick.ts:5-22; outboundCampaignPolicy.ts:5-17 |
| Send-safety hold | GA | all | workflow runner, around WhatsApp template sends | targets.ts:166-205; workflowRunnerAudit.ts:357-410 |
| Outbound AI phone calls | removed | — | — | commit 2b5147e32 |
| Outbound voice hold detection | planned (unverified) | — | — | owner notes only |
| Embedded webchat | gated per-org setup | 2 unnamed clients | webhooks (HTTP + WS), worker (turns), scheduler (idle finalise) | apps/webhooks/src/webchat/*; apps/webchat-widget |
| Webchat → WhatsApp/email continuation | gated off by default | — | webhooks, WhatsApp ingress, email poller | services/webchat/continuation.ts; epic :8 |
| WhatsApp coexistence (SMB echo, app-state, history) | GA | — | webhooks (receipt, connect), worker | whatsappBusinessApp/router.ts:356-427; smbEcho.ts:1-12 |
| WhatsApp BSUID / username | GA (cadences phone-only) | — | worker | whatsappIdentity.ts:22-30; userIdUpdate.ts |
| WhatsApp edit safety | GA | — | worker | editReplyPolicy.ts:1-60 |
| Multilingual WhatsApp templates | GA deploy + sync step | Lingua | cadence stage send | commit 9a2f9372f |
| Messenger / Instagram | GA | — | worker; scheduler (history resumer) | services/metaMessaging/index.ts |
| Calendar tools (Calendly, Microsoft) | GA | — | agentic runtime; telephony-infra (voice) | builtInToolCatalog.ts:153-166 |
| Magic booking link | GA | generic | agent tool; api (public tRPC); web page | calendarToolExecutors.ts:381-470; trpc/magicLinks/index.ts:522-600 |
| Calendar booking truth (appointments ledger) | planned (approved) | — | — | no tables in schema |
| Link domain redirects | dormant partial | Stay Club example | web host + api | services/magicLinks/index.ts:218-242 |
| Configurable public voice demos + notes generator | admin-only | Zube sales | api (public + true-admin), web | admin/publicVoiceDemos.ts:219-415 |
| Vodafone call import | GA backfill only | miCampus | api + web upload | importCall.ts:1-22 |
| NICE CXone | partial connect only | Addison Lee (owner notes) | api, web | niceCxone.ts:1-32 |
| Telephony human transfer | GA | — | telephony-infra | transferToHuman.ts; transferSequence.ts |
| Lusha prospecting connector | custom: Addison Lee (only consumer) | Addison Lee | UC1 pipeline | prospecting/src/lusha.ts |
| 21 Degrees | planned | 21 Degrees | — | 21-degrees/positioning.md:3 |
| Dynamics 365 | gated release gates pending | pilot TBD | scheduler CRM jobs; webhooks (OAuth callback) | crm/src/dynamics*.ts; epic :166-179 |
| Freshsales | GA read-only; deals not built | Addison Lee | scheduler CRM sync | freshsales/syncArm.ts; epic :173-198 |
| CRM identity convergence | GA | MiCampus evidence | repositories (CRM sync path) | crmIdentity.ts:383, 615 |
| Syncback reliability recovery | GA | MiCampus, Lingua | scheduler syncback | epic :59-75 |
| MiCampus Salesforce syncback hardening | GA (quiet period now 2 h) | MiCampus | scheduler CRM jobs | crmCandidates.ts:28-33 |
| Microsoft email auth recovery | GA | Addison Lee incident | email connector; scheduler | microsoftEmailAuthProtocol.ts:123-140 |
| Account / OAuth provider linking | planned | — | — | firebase.ts:9, 116 |
| en-GB UI locale | GA | UK/EU orgs | web | locale/index.ts:5 |
| Spanish / org language settings | planned | — | — | 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.
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.
Definition and registration
- Config.
OutboundCadenceConfigis a Zod schema. Stages are a discriminated union ofwhatsappTemplateandemail.- WhatsApp stages carry
templateName, an optional pinnedwabaIdandsenderPhoneNumber,requireApprovedTemplate,languageCode, alanguageCodeByPhoneCountrymap andleadSourceAfterSuccess. - Email stages carry a subject, a body, an optional
promptand anllmModelNametier. - The config also holds call/message windows, weekend flags, blackout dates and month-days, spread/rate knobs,
stopOnAnyReply(default true),completeOnSuccessfulCallandcompleteOnCallBooked. - SMS stages are dropped: they were not in the legacy
OutboundStageunion.
- WhatsApp stages carry
- 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
buildOutboundCadencePostWorkflowHandoffafter 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
next_action_at is unverified; see below.- Machine.
outbound_messaging_cadencehas states START → CALLING → COMPLETED and does no I/O. Inputs areCADENCE_STARTEDandHANDOFF_DELIVERY. Target statusescompleted,override,help_neededandpausedstop it. Machine internals are in the machines chapter; the runner that hosts it is in XState runner. - Wake.
checkAwaitingActionruns every 30 s and re-enters targets inawaiting_action_from_targetwhosenext_action_atis due. It readsoutboundCadenceEnabledper org and skips cadence work where it is off. - 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.
- 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_FAILEDwith a WARNING audit. Client pre-send guards run before the immediateCADENCE_STARTEDsend and before every WAKE. - Provider send.
cadenceProviderSendHookruns the due stage after the machine parks in CALLING, then feeds backPROVIDER_RESULTorPROVIDER_FAILED.- WhatsApp:
cadenceWhatsappStageSendresolves the org's WhatsApp credential, renders template components against the target and callssendTemplateMessage. If the stage requires an approved template, a missing or non-APPROVEDtemplate 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 inblockedChannels. Targets without a phone are skipped. - Email:
executeCadenceEmailStagerenders in TEMPLATE, PARTIAL_TEMPLATE or FREE_FORM mode. Links and opens are tracked throughhttps://link.zube.ai/e.
- WhatsApp:
- Next stage = now +
delayAfterPrevious, or now on the provider-failure advance. - Kill switch.
defaultContactPreferences.outboundCadenceEnabled, defaulttrue, exposed as a toggle in the contact-preferences settings editor. When false, cadence handoffs are refused.
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
| Client | Cadence | Shape |
|---|---|---|
| Lingua | lingua_outbound_cadence | WhatsApp 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. |
| Lingua | revival cadence | Mixed email and WhatsApp stages |
| Stay Club | legacy-ported cadences | Includes a Meta-ads parent variant |
| miCampus | micampus_new_lead_{1,2,3}_<locale> | Google Ads WhatsApp cadence, next section |
Evidence
packages/workflows/src/registry/outboundCadenceRegistry.ts:49-85— stage union;:90-127config;:94-126windows and stop flags;:1-11, 232-273registry;:134-165pre-send guardpackages/workflows/src/runner/cadenceProviderSendHook.ts:34-35— SMS stages dropped;:1-30send hook;:37-49email modes;:716-737failure advance;:739-746blockedChannelsskippackages/workflows/src/clients/registerClients.ts:531-542— registered cadencespackages/workflows/src/clients/postWorkflowHandoffs.ts:10, 31— handoff builder, 900 s minimum (commitc260a5ada)packages/workflows/src/clients/stayClub/cadenceSelection.ts:266;packages/workflows/src/clients/lingua/postWorkflowHandoffs.ts:7— client entry pointspackages/workflows/src/machines/outboundMessagingCadence.machine.ts:1-38pure transducer;:87-92stop statuses;:723-928states;:797-836WAKE branches;:964inputspackages/services/src/scheduler/jobs/checkAwaitingAction.ts:1-9, 152-188, 384-385— wake sweep, per-org switch, 30 spackages/workflows/src/safeguards/outboundMessagingCadenceSafeguards.ts:1-29— 6-rule matrixpackages/workflows/src/runner/workflowRunnerCadence.ts:37,cadencePreSendGuardHook.ts— guard placement;:535-557handoff refused when switch offpackages/services/src/whatsappBusinessApp/cadenceWhatsappStageSend.ts:1-14, 11, 576-597;credentialResolver.ts:1-15packages/services/src/email/emailTrackingInstrumentation.ts:10— tracking originpackages/workflows/src/runner/cadenceStepFailedScheduling.ts:20-34— next-stage timepackages/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(commit9a2f9372f);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
CreatedDatewithin 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__cmissing, null, orNo 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, elseen, 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 anAPPROVEDtemplate.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
leadSourcebecomes[Zube] Outbound WhatsApp. The miCampus syncback pre-hook writes that value to SalesforceLeadSourcefor Lead targets. - Stop it with the account
outboundCadenceEnabledswitch, or a code change. Historical backfill is a non-goal.
:49).Evidence
planning_docs/micampus-google-ads-whatsapp-cadence/epic.md:8live promotion;:29-30backfill non-goal;:49vs:163LeadSource contradiction;:61-67, 97-100first-name textpackages/workflows/src/clients/micampus/postWorkflowHandoffs.ts:44-56, 67-102, 104-136, 123— selector (commitseafcec666dry run,71183fc35launch,13fbd5c43first name removed)packages/workflows/src/clients/micampus/outboundEligibility.ts:3-6, 34-71— source, residence, 10-minute windowpackages/workflows/src/clients/micampus/cadences/outboundCadence.ts:10-27, 36-68, 43, 45, 77, 91-99— locales, stages, attributionpackages/workflows/src/clients/micampus/cadences/outboundPreSendGuard.ts:17-57— guardpackages/workflows/src/clients/micampus/index.ts:49-63— Salesforce LeadSource write (commit49891b8b7)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
- 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.
- 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".
- Enrichment. Lusha V3 (lookalikes, decision makers, email reveals) via
packages/external-connectors/prospecting; ZoomInfo via the client-custom connector. - 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
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 pattern | How UC2 does it |
|---|---|
| Cohort isolation | Reviewed CSV imported as pending targets under the dedicated campaign workflow ID; campaign state in versioned additionalInformation; no schema change. Claim protocol in precomputedOutboundCampaignProtocol. |
| Hard caps | 1,000 emails/day; 250 new admissions/day; at most 3 emails and 25 actions claimed per tick |
| Send window | Europe/London, pacing floor(N × elapsed fraction of 09:00–17:00); bounded bursts; nothing starts at or after 17:00 |
| Calendar | Stages on UK workdays 1, 3, 5, 9, 12, 14; hard-coded UK bank-holiday calendar |
| Sequence | Day 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 channel | LinkedIn 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 stop | Dedicated Microsoft mailbox via the Microsoft email wrapper; tick returns needs_attention if that exact integration is unavailable |
| Receipt-only stops | Any 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. |
| Precedence | A UC1 match pauses UC2 first |
| Kill switch | Org 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-330UC1 pre-hook;:502-516UC1 precedencepackages/workflows/src/clients/addisonLee/pipeline.ts:1-11;draftPersistence.ts:1-20, 78, 293-294packages/external-connectors/prospecting/src/lusha.ts:1-13, 51;src/index.ts:1-21;packages/external-connectors/client-custom/src/addisonLee/zoominfo.ts:18packages/services/src/scheduler/jobs/clientOutboundTick.ts:5-22;packages/services/src/scheduler/registry.ts:54-55apps/scheduler/src/tasks/addisonUc2CoreComposition.ts:234-249, 237-238, 239-247, 255-263, 264-275— executor, kill switch, mailbox, Freshsales auditapps/scheduler/src/tasks/addisonUc2FreshsalesRunner.ts:1-4, 21-45;packages/services/src/runtime/schedulerWiringTypes.ts:361, 377deletion markers (commit90faee3da); commits520415143,4ff95de5dpackages/workflows/src/clients/addisonLee/outboundCampaignPolicy.ts:5-17, 25;outboundCampaignSchedule.ts:23, 51, 800-846packages/repositories/src/precomputedOutboundCampaignProtocol.ts:1-3,precomputedOutboundCampaignRepository.tsplanning_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.executionSafetyis 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
warnbreadcrumb, 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-38packages/db/src/schema/targets.ts:166-205— JSONB shapepackages/repositories/src/workflowExecutionSafety.ts:18-30—PausedWorkflowHoldpackages/services/src/whatsappBusinessApp/workflowSend.ts:1-10packages/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(commit2b5147e32). 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.
| Stage | Behaviour |
|---|---|
| Embed | One async <script> with a public widget ID. apps/webchat-widget: vanilla TypeScript + Vite IIFE, shadow-DOM panel, served by GET /webchat/widget.js. |
| Config + session | GET /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". |
| Turns | WS 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 capture | Non-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. |
| Escalation | No 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 end | webchatIdleFinalizeJob 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. |
| Reconnect | GET /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-27slices;:37-39rollout;:109-115clients;:152-169non-goals;:444-458, 475-516, 548, 563-580apps/web/src/ui/new/integrations/channels/NewWebchatChannelPage.tsx:151-217— widget setupapps/webchat-widget/src/main.ts,ui.ts,transport.ts;apps/webhooks/src/webchat/router.ts:350, 385, 444, 530packages/db/src/schema/integrations.ts:419-436, 472-490— config and defaultsapps/webhooks/src/webchat/sessionToken.ts:43;rateLimit.ts:44-48;turnDelivery.ts:22;frameHandler.ts:1-24, 503, 628-633packages/db/src/schema/targets.ts:88-94—web_chat::handleapps/worker/src/webchat/turnProcessor.tsplanning_docs/webchat-channel-handoff/epic.md:16— escalation change;planning_docs/embedded-webchat/help-needed-continuity-plan.md:22-30packages/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.
- Eligibility, server-side: after 3 visitor messages, or immediately when the run sets
webchatPendingEscalation. - Summary. After the agent reply is persisted and pushed, Zube generates a 1–2 sentence first-person summary of the current webchat only (
generateObject, tiergpt.fastwith minimal reasoning, max 600 chars; the planning doc saysgemini.fast, which is stale), then pushes acontinuation_optionsframe. - 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 JSONBcontinuationobject; no new table. - Deep links. A WhatsApp prefilled message
[Zube Summary]: … [Zube handoff code: CODE], or amailto:with the same body. - 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.
- 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.
- 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-297packages/services/src/webchat/continuation.ts;packages/repositories/src/webchatContinuation.ts,webchatContinuationRisk.ts;apps/webhooks/src/webchat/continuationBridge.tsapps/web/src/ui/new/integrations/channels/NewWebchatChannelPage.tsx:582-588— toggle
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,subscribeAppper new WABA, and app-state sync (contact book) plus history sync per new phone number, throughPOST /{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.
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-243packages/external-connectors/meta/src/base/types.ts:3-16— coexistence meaningapps/webhooks/src/whatsappBusinessApp/router.ts:164, 356-427;packages/external-connectors/meta/src/whatsappBusinessAppAdmin.ts:388-425apps/worker/src/inbound/whatsapp/events/smbEcho.ts:1-12;appStateSync.ts:1-12packages/services/src/whatsappBusinessApp/templateSync.ts:1-16,whatsappTemplateSendActor.ts:1-14,sendFailureClassifier.ts:232,cadenceWhatsappWrapperFactory.ts:1-15planning_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-129planning_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.tspackages/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
/conversationspulls, driven by thehistorySyncResumerscheduler job. - Per-key async spacing plus a usage-percent backoff rate limiter.
- Inbound processing in
apps/worker/src/inbound/{messenger,instagram}; transport inpackages/external-connectors/meta/src/{messenger,instagram}.ts.
Evidence
packages/services/src/metaMessaging/index.ts:1-38;historySyncBody.ts:1-10;rateLimiter.ts:1-4packages/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 standalonemessaging_referralsevents; a standalone referral only updates an existing target and never dispatches a workflow. - A duplicate-target merge keeps the earliest
firstand the latestlastclick. The agentic planner sees the attribution in the contact profile. - Pages connected before this shipped lack the
messaging_referralssubscription.scripts/integrations/resubscribeMessengerPageWebhooks.tsinspects 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 shareCalendarToolServicewith the ElevenLabs voice tools (calendarListSlots,calendarCreateBookinginapps/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_linkandsend_booking_link_via_whatsapptools return hard-coded per-residence URLs.
Magic booking link GA
- The agent calls
calendar_get_booking_link, a "7-day booking link" write tool. - 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_bookingrow inmagic_links. - URL:
<webPublicUrl>/magic/book-meeting?token=…. - The lead opens the public
BookMeetingpage, which calls public proceduresvalidateBookingLink,listBookingSlots,bookMeeting. - 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-368packages/llm/src/agentic/builtInToolCatalog.ts:153-166;packages/workflows/src/defaults/calendarToolExecutors.ts:1-15, 381-470apps/telephony-infra/src/inbound/elevenlabs/toolCalls/calendarListSlots.ts,calendarCreateBooking.tspackages/db/src/schema/calendarBookingSlotLocks.ts:5-25packages/client-tools/src/clients/micampus/customTools.ts:255-300packages/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-57planning_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.
| Built | Not found |
|---|---|
|
|
Evidence
planning_docs/link-domain-short-links/epic.md:5, 7, 9-20, 24-50packages/db/src/schema/magicLinks.ts:25, 87-110, 145-168;packages/services/src/magicLinks/index.ts:218-242, 362-395apps/api/src/trpc/magicLinks/index.ts:500-530;packages/repositories/src/surfaces/magicLinks.ts:90-103apps/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(statusdraft | published | archived; per-minute and per-day start limits, default 500/day),public_voice_demo_modes(key, title, position, providerelevenlabs | 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→ publicdemo.getBySlug,recordView,startVoiceSession,reportSessionState. Session creation is provider-neutral, with reservation, rate-limit and unavailable errors. Retell transport inretellWrapper.ts. - Admin.
/admin/demos; every procedure istrueAdminProcedure: 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.generatereturns draft page copy plus a transient voice-agent system prompt that is never persisted. Generation writes nothing. Model config: tiergpt.ultra,fallback: [](planning doc pinsgpt-5.6-solhigh reasoning — stale; howgpt.ultramaps today is unverified). - Non-goals: creating provider agents, customer-owned pages, recordings, transcripts, CRM targets.
Evidence
packages/db/src/schema/publicVoiceDemos.ts:22-188apps/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-358packages/services/src/demoVoice/publicDemoVoiceSession.ts;packages/external-connectors/voice/src/retellWrapper.tspackages/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.
- Manual Uploads → "Import call audio": upload a zip of
.wav+_metadata.jsonpairs to private GCS via signed URLs (manualImport.callImport.mintUploadUrl,submit,getProgress), gated by theleads.updateACL. - The Vodafone adapter maps direction, external party and our line.
recordingPartyis the ground-truth seat;endTimeis ignored. - Mono STT with diarisation via ElevenLabs Scribe.
- A
gpt.smart(low effort) pass decides which speaker is the org's rep. - A completed
voiceconversation is upserted withcallProvider: '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_humanandcheck_transfer_availability; inmode="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-211packages/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(commit77a9bb336)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.tsxapps/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/prospectingcustom: 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_pollsscheduler 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:18planning_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'], ausers.localeenum 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.tsplanning_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.
| Area | Status | What to know |
|---|---|---|
| Microsoft Dynamics 365 / Dataverse | gated | Server-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. |
| Freshsales | GA read-only | Inbound 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) | GA | Auto-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 recovery | GA | Trust 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 hardening | GA | Country-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 recovery | GA | Triggered 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 linking | planned | Draft: 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:46planning_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-347planning_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, 615planning_docs/crm-syncback-reliability-recovery/epic.md:10, 59-75;packages/services/src/crmWorkflows/shared/identityReconciliation.ts:543-613planning_docs/micampus-salesforce-syncback-hardening/approval.md:3, 11-30;packages/repositories/src/targets/crmCandidates.ts:28-33, 93-98planning_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.tsplanning_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.
| Doc | Doc says | Code at HEAD |
|---|---|---|
micampus-google-ads-whatsapp-cadence/epic.md:61-67, 97-100 | First-name requirement; late first-name update path | No first-name check; created targets only (commit 13fbd5c43) |
same, :49 | Zube source not synced back to Salesforce | Syncback pre-hook writes [Zube] Outbound WhatsApp (micampus/index.ts:58-63) |
addison-lee-media-production-outbound/epic.md:65-69 | Tick is a disabled shell | Tick wired and running the real executor |
embedded-webchat/epic.md:511-516 | Escalation gated on contact capture | "escalation no longer waits for contact capture" (webchat-channel-handoff/epic.md:16) |
whatsapp-edit-safety/epic.md:17 | Implementation uncommitted | In repo (commit 37362a8a9) |
magic-booking-link/epic.md:8, 109 | Draft; no public router or page | Built (commit 8aee7e650) |
configurable-public-voice-demos/index.html | Status "Proposed" | Built: schema, admin router, public router |
vodafone-call-import/pitch.md:17-20 | Run post-call workflow, flip to override | Backfill only, no workflow dispatch (importCall.ts:16-19) |
micampus-salesforce-syncback-hardening/approval.md:11 | 15 min quiet, 30 min cap | 2 h quiet period, no bypass (crmCandidates.ts:28-33) |
public-voice-demo-notes-generator/index.html | Pins gpt-5.6-sol high | Tier gpt.ultra, no fallback (demoDraft.ts:3-6) |
freshsales-crm-integration/epic.md:3 | Pilot "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).
Summary
| Feature | Status | Audience | Where it runs |
|---|---|---|---|
| Firebase auth and request-actor resolution | GA | customer, operator | api (tRPC middleware), web client |
Impersonation (x-persona-user-id) | admin-only | operator | web client + api |
| User ACL (groups, permissions, lead and channel scope) | GA | customer | api |
| Automated lead assignment (round robin / random / LLM) | GA | customer | worker inbound paths, email history sync |
| Reminder acknowledgement / escalation job (ACL slice 10) | planned | customer | settings contract only |
| Customer user management | GA | customer org admins | api |
| Password setup invites | GA | customer | api + SES + Firebase |
Zube admin console (/admin) | admin-only | operator | web + api (trueAdminProcedure) |
| Organisation feature flags | admin-only | operator | api |
| Customer change requests log | admin-only | operator | api + GCS signed URLs |
| Public voice demos manager | admin-only | operator | api; nightly retention job in scheduler |
| Magic booking links | GA | customer's leads | api public tRPC; issued by agent calendar tool |
Redirect short links (link.zube.ai) | ops tool | customer's leads | api public tRPC + nginx; no in-app issuer found |
Client proposals (proposals.zube.ai) | gated | prospects, internal staff, engineers | api Express routes, SPA, nginx host block |
| Inactive-demo-account policy | GA | internal staff | services runtime dispatchers, scheduler repositories |
| Demo data toolchains | ops tool | engineers | local scripts, prod-db-write |
| 60-day data retention / purge | not found | — | not in this checkout |
| LLM and vendor spend telemetry | ops tool | engineers, internal staff | LLM client + scheduler crons → PostHog |
| Hard spend cap / per-org budget | not found | — | — |
Status page (status.zube.ai) | gated | customers / public | separate Compose project on the app VM |
External developer API /api/v1 | removed 2026-09-30 | — | — |
| Custom connector secrets | GA | customer org admins, engineers | api (KMS-encrypted); consumed by client code |
| Agent preview / Foundry test chat / Generate reply | GA | customer, operator | api enqueues; worker runs |
| Manual lead import (CSV/XLSX) | GA | customer | browser parse, api review/submit, worker |
| Manual call-audio import | internal MVP | internal staff | synchronously inside the api request |
| Support manifest | ops tool | engineers | packages/services/src/support |
| Files (signed downloads) | GA | customer | api + GCS |
| Home dashboard | GA | customer | api |
Production SQL tooling (prod-db-read / prod-db-write) | ops tool | engineers, agents | developer machine → loopback Cloud SQL proxy |
| Schema cleanup phase 2 (compatibility release) | ops tool | engineers | migration 0065; contract drop not done |
| DB connection resilience / execution-safety holds | gated | engineers, on-call | db pool, workflow runner |
| Webhook durability (receipts, spool, replay) | GA | engineers, on-call | webhooks, scheduler, GCS |
| Workflow envelope invariant | step 1 steps 2–4 | engineers | workflow runner |
| Workflow lock contention fixes | S0 + mitigations Q1–Q7 | engineers | workflow runner, CRM sync |
| CI validation reuse | shadow-only | engineers | scripts/checkremote |
| Vulnerability scanning | ops tool | engineers, compliance owner | GitHub Actions (hosted + self-hosted runner) |
| Cloud SQL backup monitor | gated | engineers, compliance owner | Cloud Run job (unprovisioned by default) |
| Vanta remediation | inventory | compliance owner | planning doc |
| Multi-app split Phase 1 (five containers) | shipped 2026-09-27 | engineers | app VM Compose |
| Multi-app split Phase 2 (worker split) | merged | engineers | apps/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)
- Verify the token. Missing or invalid →
anonymous. - Look up
usersby Firebase UID. An internal-domain principal with no row is auto-provisioned intoAUTH_INTERNAL_ORGANIZATION_ID, and default user groups are ensured. - Still unknown →
access_required_unprovisioned, withshouldDeleteFirebaseUser: !isInternalUser(an unprovisioned external Firebase user is flagged for deletion). - 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. NoisActivecheck is applied to the persona, consistent with the inactive-demo policy. - Assemble the actor. The effective user's group ACL, organisation, owner flag and demo flag resolve in parallel. While impersonating,
actor.isAdminfollows the persona's email domain, not the human's.
Procedure tiers
| Tier | Authorises on | Rule | Typical use |
|---|---|---|---|
publicProcedure | nothing | open | magic-link validation, booking, redirect resolution |
protectedProcedure | effective actor | authenticated and org-scoped | self-service setMyCrmIdentity / setMyLocale / setMyUiMode |
aclProcedure(permission) | effective actor | owner or admin bypass; else effective permissions must include the path. Denial carries accessReason: missing_permission | permission_setup_incomplete | most customer features |
organizationFeatureProcedure(permission, featureKey) | effective actor + org | ACL check plus per-org feature flag; both skipped for true admins | flagged features (see feature flags) |
adminProcedure | effective actor | effective actor is internal (persona-faithful) | persona-faithful internal checks |
trueAdminProcedure | logged-in human | human is internal, regardless of persona; never for tenant business data | all /admin server procedures |
resolveIsTrueAdmin exists separately for field-level redaction.
| Request deadline | Applies to |
|---|---|
| 30 s | default |
| 285 s | named long-running paths (e.g. admin delete organisation) |
| 585 s | templates.testReply, conversations.generateReply, knowledgeBase.testNexusQuery |
| 60 s | report generation |
| 30 min | the whole manualImport.* namespace |
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 headerapps/web/src/lib/persona.ts:1-43—zube.personaUserIdstorageapps/api/src/middleware/auth.ts:3-8;apps/api/src/app.ts:194— header read, CORS allowpackages/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— tierspackages/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.
| Family | Permissions |
|---|---|
leads | view, viewUnassigned, update, delete, own, manageUnowned, manuallyAssign |
conversations | view, reply |
remindersAndAuditTrails | view, update, acknowledge |
nexus | view, update |
insights | view |
foundry | viewClientConfig, updateClientConfig |
integrations | manageOwn, manageAll |
organizationSettings | view, manage |
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:
autoAssignCreatedLeadruns only for newly created, unassigned targets. Strategies:round_robin(durable cursor inaccessControlSettings),random, andllmwith 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—leadChannelScopepackages/services/src/userManagement/index.ts:331-340— additive direct permissionsplanning_docs/user_acl/implementation_status.md:20-27,:309-311,:370-376apps/api/src/trpc/leadAccess.ts:14-80— record-level accesspackages/db/src/schema/users.ts:98,147;packages/db/src/schema/targets.ts:307packages/services/src/leadAssignment/index.ts:40,144;autoAssignment.ts:282-300,397-398,566,628-776apps/worker/src/inbound/whatsapp/shared/whatsappIdentity.ts:452;apps/worker/src/inbound/instagram/events/assignment.ts:39;packages/services/src/email/historySyncBody.ts:398packages/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-468packages/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:142planning_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.
| Capability | Behaviour |
|---|---|
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 picker | listImpersonationTargets; the UI sets personaUserId. |
| Active flag | updateUserActive with an audit row. |
| Delete organisation | Refuses 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 / reset | sendPasswordSetupInvite, recordPasswordResetTrigger. |
| Feature flags | Catalogue 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)
| Key | Note |
|---|---|
| flag: insights_conversion | |
| flag: nexus_taxonomy | |
| flag: lead_lifecycle_stage | shadow; 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 routesapps/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-722packages/webapp-contracts/src/admin/index.ts:243-273— flag catalogueapps/api/src/trpc/admin/publicVoiceDemos.ts:165,:219-343;apps/api/src/demoVoice.ts:1-40packages/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 tRPCvalidateBookingLink,listBookingSlots,bookMeeting. (Booking-link epic says "draft discovery" — stale.) - Redirect short links on
https://link.zube.ai/<slug>, with reserved slugs, resolved by publicresolveRedirect; host detection in the SPA and an nginx block. No in-app caller ofissueRedirectMagicLinkexists outside the service, so creation is presumably a data operation (unverified). - Other types throw
TODO(magic-link-expansion).setup-accountis in the enum but the service rejects issuing it.
Evidence
packages/db/src/schema/magicLinks.ts:25-28,129-130packages/services/src/magicLinks/index.ts:1-8,:99-134packages/workflows/src/defaults/calendarToolExecutors.ts:455apps/api/src/trpc/magicLinks/index.ts:500-600apps/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.
- Host split.
selectApplicationHostreturns'proposal'for that hostname and lazily imports a proposal-only entry, so the staff router and analytics never load on the public host. - nginx. A dedicated
server_nameblock with its own Let's Encrypt cert proxies/api/proposals/toapi:3001and everything else to the Firebase-hosted SPA. - 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 passrequireOrigin. - Code challenge.
randomInt(0, 10_000)zero-padded; 30-minute code lifetime; 24-hour absolute session. Code stored asscrypt$salt$digestand compared withtimingSafeEqual; the browser token is stored only as a SHA-256 digest. Email via a dedicated SES template. - Eligibility. Exact
getzube.comaddresses can open published or unpublished proposals. External addresses needpublished = trueand an exact allowlist match. Every content read and visit write re-authorises. - Data.
client_proposalsandclient_proposal_accesses(migration0074). Visits are a UUID-keyed JSONB map with server-clampedvisibleMs. - Document contract.
proposalDocumentSchemais a discriminated union onschemaVersion1 and 2. v1 blocks: prose, stepper, columns, example, table, scopeExplorer, cta. v2 adds a trustedcustomsection (html≤ 131,072 chars, optionalcss≤ 32,768) andpresentationMode. 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.
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-331apps/web/src/applicationHost.ts:3-4;apps/web/src/main.tsx:7-9;apps/web/src/ProposalEntry.tsx:5-17infrastructure/nginx/nginx.conf:102-130;apps/api/src/app.ts:219-221apps/api/src/proposals/router.ts:188,207,242,259,275,299packages/services/src/proposals/index.ts:19-20,91,95-108,146packages/repositories/src/proposals.ts:138,376-379,582,660packages/webapp-contracts/src/proposals/index.ts:270-340apps/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 andlogger.errorfires. Audit rows and target / help-needed state are still persisted. - Bootstrap:
actor.isDemoOrganizationanddemoInsightsReferenceAtgo to the web client. Migration0071addsorganizations.demo_insights_reference_at; Insights pages use it as the virtual "today". - Scheduler:
organizationHasActiveUseris 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.
Two demo-data toolchains
| Toolchain | What it is | Use it for |
|---|---|---|
| Configurable generator | bun 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
elevenLabsCostRollupcheckpoint for three days. - No
ongoingvoice calls; no healthy orauth_errorintegrations (usedisabled). - No escalation rules with email or
crmTasktargets; all users inactive;outboundCadenceEnabled: false. - The seeder's
--use-bundle-organizationoverwrites settings and owner; never re-seed after extras.
Evidence
planning_docs/inactive-demo-account-policy/epic.md:5,11-45,85-88packages/services/src/demoAccountPolicy.ts:9-21;packages/services/src/runtime.ts:647-677;packages/services/src/runtime/runtimeDispatchers.ts:213-241packages/services/src/auth/bootstrap.ts:127-143,403-430;packages/db/drizzle/0071_demo_insights_clock.sql:1-56packages/repositories/src/organizationActiveUser.ts:7-21;guidance/data-operations.md:92package.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
What does exist and looks like retention:
| Mechanism | What it deletes | Cadence |
|---|---|---|
webhookReceiptMonitor | webhook_receipts (raw inbound WhatsApp bodies, contain PII) past a fixed 14-day expires_at | hourly |
publicVoiceDemoUsageRetention | identity-free public voice-demo session/view receipts older than 13 calendar months, 10k batches | nightly 00:00 UTC, singleton |
knowledgeDeletionTick | Nexus document hard-deletion and expired ingest-session sources, with backoff | every 15 s |
| Admin delete organisation | whole tenant; manual | on 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:148packages/services/src/scheduler/jobs/publicVoiceDemoUsageRetention.ts:1-65;registry.ts:28,78packages/services/src/scheduler/jobs/knowledgeDeletionTick.ts:13-16;packages/services/src/knowledge/deletionLifecycle.ts:1-25packages/db/src/schema/webhookReceipts.ts:38-43;webhookReceiptMonitor.ts:201planning_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.
- Semantic tiers → physical models. Callers ask for
gpt.nano|fast|smart|ultra(and Gemini/Claude tiers).gpt.ultra→gpt-6.1-soleffort high;gpt.smart→gpt-6-lunahigh;gpt.fast→ Luna low;gpt.nano→ Luna none. Rates versionedopenai-rates@2026-09-29. - Per-call LLM cost events. PostHog
$ai_generationwith 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. - Voice/telephony spend crons (scheduler, singleton, gated on
POSTHOG_ENABLED):telnyxCostRollupevery 3 h at :15 (onevendor_usage_recordedper billable voice leg, attributed through the phone-line directory);elevenLabsCostRollupevery 3 h at :25;elevenLabsRateRefresherweekly 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. - Per-request generation budget (
ProviderGenerationBudget) bounds attempts across provider fallback and retries. - 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-118packages/analytics/src/client.ts:347-370,381-405packages/services/src/scheduler/jobs/telnyxCostRollup.ts:55-66;elevenLabsCostRollup.ts:60-70;elevenLabsRateRefresher.ts:29-34apps/scheduler/src/tasks/postHogSpendWiring.ts:9-31,96-147packages/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).
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-111infrastructure/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:
sanitizeAdditionalInformationForExportstrips the reserved_internalMetadatakey fromtargets.additional_informationbefore it leaves the system (workflow actor payloads, deferred custom-analysis inputs).apps/webhooks/src/external-api/kms.tsis just a re-export ofresolveCredentialCipher.- Manual import still dispatches
CRM_RECORD_RECEIVEDwithobject_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
88c4096b6message;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:95packages/services/src/manualImport/createTarget.ts:6-8packages/db/src/schema/integrations.ts:493-502;apps/api/src/trpc/integrations/integrationCustomSecretsRouter.ts:133,190-263;apps/api/src/trpc/integrations/index.ts:37packages/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.
- The API creates an
agent_preview_runsrow (kindstemplate_test_reply,conversation_generate_reply; statusespending|completed|failed) and enqueues anagent-previewpg-boss job in the same transaction; job id = run id. - Entry points:
templates.testReply/getTestReplyStatus(foundry.updateClientConfig) andconversations.generateReply(conversations.reply). - The
workerrunsbuildGenerateAgenticReplyin preview mode: the persisting/sending workflow machine is not invoked, client tools are draft-only,calendar_create_bookingand booking links are neutered, availability lookups run live. - The web app polls; status mapping never exposes a failed run's stored error.
- Queue expiry 300 s;
jobQueueHealthMonitorreconciles 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-29apps/api/src/trpc/templates/index.ts~:575-640;apps/api/src/trpc/conversations/index.ts:883-927apps/worker/src/workerProcess.ts:188;apps/worker/src/agentPreview/previewReplyAdapter.ts:1-7;templateTestReply.ts:1-7packages/services/src/agentPreview/previewStatus.ts:8-29;packages/db/src/jobQueue/queueConfig.ts:9-14;jobQueueHealthMonitor.ts:218-230
Manual import
Leads (CSV / XLSX)
- The browser parses CSV (hand-rolled RFC-4180-ish parser) or the first XLSX sheet via
xlsx; max 5 MB. reviewBulkImport/reviewSingleContactvalidate rows and return counts and the workflow id;submitBulkImport/submitSingleContactstore a batch and enqueuemanual-import;getImportStatuspolls. AllaclProcedure('leads.update').- The
workerprocesses the batch under a per-batch session advisory lock on a dedicated connection. - Each row goes through
createTargetFromRequest→CRM_RECORD_RECEIVED→ theOnCRMSyncWorkflowidentity-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 countryUS. - 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-246apps/api/src/trpc/manual-import/index.ts:556-700;packages/services/src/manualImport/batch/submitBatch.ts:36-60apps/worker/src/manualImportConsumer.ts:1-17;batchLock.ts:8-25;batchProcessor.ts:30-37packages/services/src/manualImport/createTarget.ts:1-44;queueConfig.ts:9-18apps/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/supportis not customer support. It is an engineering inventory:PROVIDER_MANIFEST(provider → integration type → connector package) andscheduledJobsManifest(shipped,dropped,deferredProductDecision). Dropped:detectDropoffEvents,runEmailCampaign,sendEmailReminders. Deferred:revivalGateSweep,calendarBookingMagicLinkSweep. No customer help-desk integration exists in the web app.- Files.
file_storagerows (providerGCS | GOOGLE_DRIVE,file_category,gcs_uri).files.getById/getDownloadUrlreturn metadata or a GCS signed URL after a per-category check:knowledge-base→nexus.view,contact_attachment→leads.view, elseconversations.view; owner/admin bypass. - Home.
home.myDay(overdue and today's reminders, unacknowledged escalations, paginated),home.ownerCoverage,home.activity(audit feed), allremindersAndAuditTrails.viewand owner-scoped viascopeFor(actor);home.communication(insights.view). Acknowledge/unacknowledge urgent audit rows. KnownTODO(perf): reminders and recent conversations are filtered in memory.
Evidence
packages/services/src/support/manifest.ts:1-40,113-158packages/db/src/schema/fileStorage.ts:16-46;apps/api/src/trpc/files/index.ts:31-139apps/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.
- Connection pinning. Reads only the primary checkout's
.env.cloudsql. Refuses unlessDATABASE_URLispostgres(ql)://on127.0.0.1/::1/localhost, port5433, with no query string or fragment: the owner-managed loopback Cloud SQL proxy. Agents never start or stop the proxy. - AST validation with
libpg-query(PostgreSQL 16 parser): exactly one top-level statement; read mode =SELECTonly, write mode =INSERT|UPDATE|DELETEonly. - Function ban. Any
FuncCall/FuncExpr/SQLValueFunctionis rejected. Reads may use plaincount/min/max/sum/avgonly (unqualified orpg_catalog; noOVER,WITHIN GROUP,ORDER BY,VARIADIC). NoSELECT INTO, no lockingSELECT, no data-changing CTE in reads. - Provably restrictive write predicates.
UPDATE/DELETEneed aWHERE;UPDATE FROM/DELETE USINGrejected; anyOR, wildcard, tautology (1=1,true,x = x) or non-comparison fails; at least oneANDarm must compare a target column with a literal or another column.INSERT … ON CONFLICT DO UPDATEneeds a restrictiveWHEREthat does not referenceexcluded. - Transactions. Reads:
BEGIN READ ONLY, alwaysROLLBACK. Writes:BEGIN,SET CONSTRAINTS ALL IMMEDIATE, thenROLLBACKunless--commit.SET LOCALstatement_timeout60 s,lock_timeout5 s,idle_in_transaction_session_timeout30 s by default, each overridable within bounds. - Unknown commit. A connection failure during
COMMITraisesCommitOutcomeUnknownErrorrather than guessing. - Insight table fences.
--lock-insight-tables, or--lock-insight-bootstrap-tableswith--insight-bootstrap-organization-id, take orderedSHARE ROW EXCLUSIVElocks underREAD COMMITTEDbefore the DML snapshot. - Output is one JSON line
{mode, outcome, command, rowCount, rows}. There is no affected-row cap: callers gate the commit on the dry-runrowCount.
--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-143scripts/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-125packages/db/drizzle/0065_daffy_strong_guy.sql:1-2; rg overpackages/db/drizzle/*.sqlfinds only0031,0062,0065mentionspackage.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):
/readyuptime 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
executionSafetyfield 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
ROLLBACKon an idle session (commit52bfbf552).
Evidence
planning_docs/db-connection-resilience/epic.md:11,20-26,83-134;adr-execution-safety.md:1-38and "Consequences"packages/db/src/client.ts:176,239packages/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-dayexpires_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.tsrequires explicitallowCustomerSideEffectsand a confirmed receipt id equal to the target id; success scriptswebhookSpoolSuccess.ts,receiptReplaySuccess.ts.
Evidence
packages/db/src/schema/webhookReceipts.ts:13-56apps/webhooks/src/composition.ts:46-55; commit5ab94d08epackages/services/src/scheduler/jobs/webhookReceiptMonitor.ts:11-20,144-147,201;packages/repositories/src/webhookReceipts.ts:185-216scripts/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.
| Step | Status | Detail |
|---|---|---|
1. instant registry class, forced restore-on-failure | built | "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 + detector | planned | not found |
3. Explicit restore | cancel successor contract | planned | still restorePrevious: boolean |
| 4. Stack-aware mirror + WAKE unwinding | planned | not 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, §4packages/workflows/src/registry/workflowRegistry.ts:179-185;workflowRunnerEnvelope.ts:28-82onConversationComplete.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:
WorkflowTargetBusyErrorboundary error. The CRM sync orchestrator and email-CRM syncer treat it as a deferral:crm_sync_record_deferred_lock_contendedinfo event, no audit, nologger.error, cursor not advanced, no attempt-budget burn. - Handoff coalescing: when a successor declares
coalesceHandoffEventDataKey, older pendingworkflow_handoff_pendingrows for the same target/successor/key are markeddone(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
WorkflowTargetBusyErrorit 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, §9packages/ports/src/workflowRunner.ts:30;packages/services/src/crmWorkflows/syncOrchestrator.ts:121;packages/services/src/scheduler/jobs/emailCrmSyncer.ts:432packages/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-98scripts/checkremote/run.ts:28,616-623;planning_docs/aws-checkremote-parity/index.htmlplanning_docs/vibe-code-cleanup/index.md:5,83;10-client-hardcoding.md:3;package.json:15,19,53,72,98,143
Security and compliance
| Control | Status | What it does |
|---|---|---|
| Vanta remediation matrix | inventory | 2026-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 scan | built | Semgrep 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 evidence | built | Self-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 monitor | gated | Independent 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,148package.json:11-13;guidance/security-scanning.md:1-80;.github/workflows/security-scan.yml:3-11,39-173,286-290scripts/security/assessProductionVulnerabilityEvidence.ts:10-18infrastructure/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):
| Container | Owns | Deploy |
|---|---|---|
api | Express + tRPC, proposals | overlap |
webhooks | Meta/IG/Messenger/ElevenLabs post-call, OAuth, callbacks, webchat HTTP+WS; verify → receipt → enqueue → 200 | overlap |
worker | pg-boss consumers + the three dispatcher ticks (plus the webhook spool drain when a spool is configured) behind a singleton session advisory lock | overlap |
telephony-infra | /telnyx/*, /voice-tools/*, /client_tools/*, process-local call state | only 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 |
scheduler | crons | in-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 removal | Status | Commit |
|---|---|---|
| All AI outbound calling (legal) | removed | 2b5147e32 |
| Outbound customer webhooks | removed | 15f22eddd |
/api/v1 developer API | removed | 88c4096b6 |
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-155planning_docs/multi-app-split/worker-split.md:3,7, §2apps/{api,webhooks,telephony-infra,worker,scheduler}/package.json— workflows dependency presencepackages/db/src/jobQueue/queueConfig.ts:9-14scripts/operations/phase2Task0Deploy.md;scripts/operations/phase2Monitoring.md:5; commits verified ancestors of HEADguidance/engineering-constraints.md:103
Doc-vs-code discrepancies
Trust the code over these docs. Whoever maintains onboarding should fix or annotate them.
| Doc | Claim | Code reality |
|---|---|---|
planning_docs/user_acl/implementation_status.md:309-311 | Slice 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.html | AWS not approved; do not run | run.ts accepts only --target aws; which blockers closed is unverified |
planning_docs/organization-feature-flags/epic.md:8 | implementation blocked | Feature-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.md | manifest = exactly api/webhooks/scheduler | Assessor expects five services |
infrastructure/status/README.md:111 | release tuple api/webhooks/scheduler | Five-container topology |
guidance/engineering-constraints.md:111 | admin = @getzube.com | Default 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.
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)
| Kind | What |
|---|---|
| Hooks | On 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 machine | stay_club_crm_requested_viewing_booking: books the requested viewing, then sends confirmed / unavailable / clarification emails and hands off to the cadence. |
| Cadences | Legacy-ported coliving/student follow-ups, WhatsApp openings, long-stay promo, university fair, Meta Ads students/professional/parent. |
| Other | Email-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)
| Kind | What |
|---|---|
| Hooks | preCrmSyncback 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 machine | lingua_conversation_complete: a templated post-conversation email (en/es HTML templates). |
| Cadences | WhatsApp outbound, localised by phone region (es LatAm / pt_BR / en); a revival cadence that is registered but has no producer. |
| Custom tool | get_enrollment_link: the runtime owns the URL and folds it into the reply (finalReplyPolicy: append_output_field). |
MiCampus (student residences, Spain/Portugal; Salesforce)
| Kind | What |
|---|---|
| Hooks | Salesforce 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). |
| Machines | micampus_call_complete; micampus_outbound_whatsapp_dry_run dormant. |
| Custom tools | get_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). |
| Other | Reports: 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)
| Kind | What |
|---|---|
| Registration | Email-CRM parser only (sets road_scholar_trip_interest, with a TODO pending client mapping). No hook slots. |
| Custom tool | get_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)
| Kind | What |
|---|---|
| UC1 custom | A 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 scheduled | A 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. |
| Other | ZoomInfo 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
- Define it in
packages/client-tools/src/clients/<client>/customTools.tswithcreateClientVoiceTool({clientName, functionName, description, plannerCallable, sideEffect, diagnosticEligibility?, finalReplyPolicy?, plannerInputSchema, inputSchema, outputSchema, handler}). The wrapper validates input and output with Zod. Put the name constant incustomToolNames.ts. - Add it to
CLIENT_CUSTOM_TOOL_BUNDLES({clientName, organizationId, tools}). An owner mismatch throws at import. - 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 withclientToolEffects. - Text: add the tool key to a
tool_node.allowedToolKeysin 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.
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 keypackages/workflows/src/clients/registerClients.ts:21-167;registry/expectedRegistrations.ts:30-106;registerClientHooks.ts:4-49packages/client-tools/src/tools/clientVoiceToolDefinition.ts:58-120;clients/customTools.ts:6-24;tools/clientVoiceTools.ts:54-130apps/telephony-infra/src/inbound/elevenlabs/toolCalls/customClientTool.ts:28-187packages/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-20scripts/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.
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.
| Piece | Status | Detail |
|---|---|---|
4 tables: revops_deals, revops_deal_targets, revops_conversations, revops_deal_days (migration 0094) | merged | People 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_deals | New UI only; Classic renders not-found. |
bun run revops-deal-load | ops tool | Inserts one pre-computed as-of deal export; rehearse → dry run → --commit. |
XState checkpoint-run machine (revopsCheckpointRun: claiming → loading → step loop → committing) | branch: claude/revops | 58 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 log | branch | "Latest run wins": a rerun replaces the state at C and deletes later days. |
| Decision-1 moved from OpenRouter to Azure Foundry (EU/US) | branch | Cross-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 construction | dormant | No 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 pages | branch | Run 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, unbuilt | Its branch has 0 commits; none of its tables exist. The gating decision for live RevOps. |
RevOps Intelligence plan (art_f7b5664c, rev 4) | draft | An 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)
| Theme | Built | In flight / planned |
|---|---|---|
| Agent quality & knowledge | Nexus 2.0 researcher, curated ingest, observed gaps, workflow-scoped knowledge, guardrail escalation, gpt.fast semantic routing, Decision-1 gates, GPT-6 tiering | Taxonomy rollout gates; diagnostics-recovery backfill (awaiting a decision); semantic remediation groups (stopped) |
| Insights & revenue evidence | Conversion insights (flag), loss reasons, drop-off observations (admin), half-hour sentiment, acknowledgement metrics, 4 client reports | Automated revival, quality→outcome metric and privacy-safe long-term aggregates are held; waitingOnTarget missed its precision gate |
| CRM as system of record | CRM Sync V2 Track A + safety substrate, identity convergence, syncback recovery, Freshsales (no syncback; tasks only), Dynamics | Canonical single writer; Dynamics release gates; Freshsales deals; 21 Degrees "layer above any CRM" positioning (commercial only) |
| Channels & conversion | Webchat + continuation, WhatsApp BSUID/edit safety, magic booking links, public voice demos | Calendar booking truth (approved, no tables yet), link-domain admin UI, native realtime audio (draft), OAuth account linking, Spanish UI |
| Platform reliability | Five-service split, execution-safety holds, lock-contention fixes, deploy release transaction, webhook spool, status page | Stack-aware workflow mirrors, CI validation reuse cutover, durable Nexus ingest jobs, target mailbox |
| Governance & compliance | User ACL milestone 1, org feature flags, Semgrep/audit/Trivy evidence, backup monitor | Vanta 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_e7fce6a6first (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)
| Doc | Purpose | Code reality |
|---|---|---|
| 21-degrees | Positioning for a trades/renewables group pilot | commercial only |
| account-organization-oauth-linking | Link Google/Microsoft login to existing accounts | not built |
| addison-lee-media-production-outbound | AL UC2 campaign | built deletion late Nov |
| audit-trail-acknowledgement-metrics | Are urgent events acknowledged? | built |
| aws-checkremote-parity | Remote checks on AWS | AWS is now the only target; doc stale |
| calendar-booking-truth | Durable appointments ledger | approved, no tables |
| channel-workflow-routing | Per-endpoint workflow routing | partial (endpoint workflowId exists) |
| ci-validation-reuse | Validate once across CI/deploy | shadow-only substrate |
| client-custom-tool-ownership | Move tool names out of generic layers | done |
| client-proposals | proposals.zube.ai microsite | built; host activation pending per doc |
| client-report-generation | Recurring client spreadsheets | built (4 generators; doc stale) |
| client-semantic-routing-gpt-fast | Replace regex classifiers | built |
| configurable-public-voice-demos | Registry for /demo pages | built (doc says proposed) |
| crm-identity-convergence | Merge targets sharing a CRM ref | built |
| crm-sync-v2 | Canonical CRM sync | Track A + B substrate built |
| crm-syncback-reliability-recovery | Recover failed syncbacks | built; replay state unverified |
| db-connection-resilience | Pool handlers, execution-safety holds | built |
| deploy-downtime-and-webhook-recovery | Release transaction, rollback | built |
| dropoff-observation | Sales-motion observations | built differently (deterministic + cause only) |
| embedded-webchat | Website chat channel | built, per-org setup |
| freshsales-crm-integration | Freshsales as a CRM | built read-only; deals not built |
| gemini-36-upgrade | Move tiers to Gemini 3.6 | superseded (3.8 + GPT-first) |
| guardrail-escalation-intelligence | Template guardrails, escalation routing | built (incl. forwarding) |
| hourly-flex-insights | Half-hour batch sentiment/custom | built (GPT-first, doc says Gemini) |
| inactive-demo-account-policy | Demo orgs with inactive users | built |
| insights-v2 | Conversion, journeys, sentiment | partly built; several slices retired or held |
| integration-auth-recovery | Microsoft email auth recovery | built |
| jev-decision-research · jev-tests | Probabilistic decision model research | Decision-1 used in 4 places |
| language-settings-localization | Org/user language, Spanish UI | en-GB only; Spanish planned |
| link-domain-short-links | link.zube.ai redirects | partial (no create UI) |
| loss-reason-intelligence | Conversation-derived loss reasons | built |
| magic-booking-link | Self-serve booking link | built (doc says draft) |
| micampus-google-ads-whatsapp-cadence | Google Ads → WhatsApp cadence | live |
| micampus-salesforce-syncback-hardening | SF syncback field rules | built (2 h quiet period now) |
| microsoft-dynamics-crm | Dynamics via app user | built; release gates pending |
| multi-app-split | Five-service topology | shipped |
| native_audio | Realtime voice instead of ElevenLabs | draft |
| nexus-* (7 docs) | Researcher, curation, diagnostics, taxonomy, parity, remediation | see Nexus |
| openai-usage-control | GPT tier mapping, usage control | tier mapping built; controls planned |
| organization-feature-flags | Org-scoped preview features | built (doc says blocked) |
| periodic-vulnerability-scanning | Host CVE evidence | built in CI (Trivy + VM Manager) |
| plane-cleanup-plan | Backlog clean-up preview | ops note |
| public-voice-demo-notes-generator | Demo setup from notes | built |
| revival-shared-categories | Shared loss/drop-off categories, regeneration | built; prod regeneration gated |
| schema-cleanup | Drop dead schema | 0065 merged; contract step not done |
| status-page-mvp | status.zube.ai | infra built; operator steps unverified |
| user_acl | Groups, permissions, assignment | milestone 1 + auto-assignment built |
| vanta-remediation | SOC 2 control inventory | inventory only |
| vibe-code-cleanup | Remove agent-written smells, ratchets | ratchets landed; client hardcoding parked |
| vodafone-call-import | Import recorded calls | built (backfill only) |
| webchat-channel-handoff | Webchat → WhatsApp/email continuation | built, off by default |
| whatsapp-bsuid-username-migration | BSUID identity | built |
| whatsapp-edit-safety | Edited messages fail closed | built |
| workflow-envelope-scheduler-invariant | Mirror the earliest due work | step 1 built; rest planned |
| workflow-lock-contention | Busy-target deferral, coalescing | S0 + mitigations built; Q1–Q7 planned |
| workflow-scoped-knowledge | Scope knowledge to workflows | built (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-271claude/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 withbun 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/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 / command | Runs on | What 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.yml | same runner, production environment | Triggers: 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.yml | ubuntu + self-hosted | Semgrep 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.yml | ubuntu (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.yml | ubuntu-latest → IAP SSH | weekly certbot backstop |
bun run check:remote · check:full:remote | same AWS host | Ships 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 thenodebinary fromnode:22.23.1-bookworm-slim. It runs asUSER bunwithCMD 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
startupProbethat 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, withDEPLOY_SHAbaked in./readyreports 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.tsupdates it without a rebuild.
Observability
| Signal | How |
|---|---|
| Logs | pino JSON to stdout → Docker gcplogs driver → Cloud Logging. Severity isn't mapped, so metrics regex-match "level"/"msg"; keep msg names stable. |
| Trace ids | x-request-id reused or generated per HTTP request; every scheduled run gets its own requestId child logger. |
| Errors | createErrorReportingLogger 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 + alerts | error_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. |
| Uptime | GCP 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 & cost | PostHog events (closed union, PII-redacted), $ai_generation per LLM call, vendor_usage_recorded for Telnyx/ElevenLabs/LLM spend (directional, not billing-grade). |
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 devstarts api, web, webhooks, worker and telephony-infra (port 3003) undertsx watchwith the primary checkout's.env.local. The scheduler is separate:bun run dev:scheduler. The worker runs ticks only withSCHEDULER_ENABLED=true.- Local Postgres (
deps:up) exists only forbun run migration:check. Integration tests use testcontainers withdrizzle-kit push, the only sanctioned push. - Production data: only through
bun run prod-db-read/prod-db-writeover the owner-managed Cloud SQL proxy on127.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-44scripts/deploy/runProdDeploy.ts:1713-1992;scripts/deploy/lib/releaseTransaction.ts:103-1127;lib/changeDetection.ts:1-177;lib/greenShaResolver.ts:1-28infrastructure/scripts/deploy-recovery.sh:1-68,commit-release.sh:9-76scripts/checkremote/run.ts:167-195,900-1015,1550-1551,2445-2480apps/api/Dockerfile:1-24;apps/api/src/startupProbe.ts:1-3;scripts/deploy/lib/productionProbe.ts:8-46packages/logging/src/index.ts:14-278,requestContext.ts:27-61;infrastructure/terraform/monitoring.tf:1-567,compute.tf:55-87guidance/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
| File | Read it before… |
|---|---|
CLAUDE.md / AGENTS.md | anything. 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.md | code, schema, provider, infra or ops changes: tiers, types, SQL, auth, migrations, logging, deployment |
guidance/code-discipline.md | any code change: try/catch only with a job, no invented fallbacks, edge cases need evidence, minimal diffs, formatting, lint ratchets |
guidance/type-rules.md | types: any banned, unknown boundary-only, as X banned outside as const, per-site // Boundary(<category>): markers |
guidance/testing-strategy.md | tests: layers, port fakes over vi.fn(), no mocking connectors, the local static gate |
guidance/frontend-conventions.md · observability.md · data-operations.md | web work · logging/audit decisions · any production data change (rehearse locally first) |
guidance/claude-setup.md | setting 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.md | big plans · approved epic execution · Plane tracking · live LLM probes |
Agent roles
| Agent | Model · effort | Job |
|---|---|---|
| coordinator (main session) | Opus · high | requirements, decisions, routing, integration, talking to you |
implementer · test-author | Opus · medium | one bounded slice in an assigned file set · failing tests first |
reviewer | Opus · high | fresh, independent slice review, then recheck and approve |
final-reviewer | Opus · xhigh | pre-merge review for any cron, webhook or non-webapp change |
check-monitor · retriever · mechanical-editor | Sonnet · medium | run 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
| Category | Gates (all in bun run check:static) |
|---|---|
| Architecture | workspace-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 escapes | types:check + baseline (AST-based), raw-sql:check (query builder unless schema / allowlist / Parity: / Boundary(raw-sql):) |
| Test hygiene | integration-boundary:check (no mocking internals), test-source-reads:check |
| Shrink-only ratchets | file-size:check, duplicates:check (jscpd), duplicate-helpers:check, eslint-suppressions:check, comments:check + baseline, format:check, casing:check, migration-baseline:check, tracked-inputs:check |
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:staticon 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-tasklistMCP). Plans are published to the private engineering-plans server withbun 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.jsoncheck:staticscript (~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
| # | What | Why it matters | Where |
|---|---|---|---|
| 1 | Scan mirrors show only the top workflow envelope | A 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 |
| 2 | Migrations are never reversed on rollback | Every migration must work with the previous image (expand → contract) | scripts/deploy/lib/releaseTransaction.ts:1037-1046 |
| 3 | The scheduler relies on in-process singleton guards | Running two schedulers would double-run crons and email polls | createScheduler.ts:121-180; emailPollingRunGuards.ts |
| 4 | Cadence quiet hours: config fields exist but no enforcement was found | Don't promise message windows on WhatsApp/email cadences without checking | outboundCadenceRegistry.ts:94-116; cadenceStepFailedScheduling.ts:20-34 |
| 5 | voice-post-call has no NOTIFY; a failed enqueue loses the post-call | Up to 30 s pickup latency; the stale-call sweep is the backstop | 0076_pgboss_12_34_0.sql:444; apps/telephony-infra/src/app.ts:91-111 |
| 6 | Voice custom-tool endpoints check only the shared secret and client name | No org-to-bundle check; worth a deliberate decision | customClientTool.ts:126-149 |
| 7 | WhatsApp POST webhooks are unsigned by design (only replays are signed) | Intentional per the code comment; the reason isn't stated | apps/webhooks/src/inbound/whatsapp/dispatch.ts:15-17 |
| 8 | The per-org llmInferenceRegion is read only by the lead-lifecycle classifier | Agentic replies, insights and batches use the global client regardless | conversationClassifier.ts:125-130 |
| 9 | The default agent system prompt hard-codes an education "enrollment advisor" persona | Non-education tenants rely on base and node prompts to override it | agenticReplyPrompt.ts:17-38 |
| 10 | The Lusha key is decrypted in a composition root, not inside its wrapper | Deviates from "wrappers own decrypt" | addisonClientRuntimeFactory.ts:252-262 |
| 11 | PROVIDER_HOST_TOKENS misses some hosts used inside connectors | A leak of those hostnames outside the wrappers wouldn't be caught | noDirectExternalProviderAccess.ts:36-57 |
| 12 | CREATE EXTENSION (vector, hll, pgcrypto) isn't in any migration | A fresh environment needs them provisioned out of band | packages/db/drizzle/*.sql |
| 13 | Demo orgs are inferred: "≥1 user and all users inactive" | Marking a real customer's only user inactive silently suppresses their escalation emails and CRM tasks | packages/services/src/demoAccountPolicy.ts:9-21 |
| 14 | The internal/admin email domains default to getzube.com and zube.ai | The guidance says only @getzube.com | packages/config/src/env.ts:10,212-216 |
| 15 | Prod runs Node; dev and tests run Bun/tsx | Prove runtime-sensitive behaviour under Node | apps/*/Dockerfile |
| 16 | In-memory dedupe caches are per process | During a two-worker overlap each instance can accept a duplicate; receipt and runner guards are the real defence | receiptProcessor.ts:5-7; elevenlabs/eventProcessor.ts:1-15 |
| 17 | No 60-day data-retention purge exists in this checkout | Webhook 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 |
| 18 | ElevenLabs agents (prompts, tool URLs) are configured outside the repo | Voice behaviour changes may need ElevenLabs-side edits that code review never sees | packages/ports/src/elevenLabs.ts:250-258 (CRUD unused) |
| 19 | The RevOps branch removes OpenRouter for Decision-1 | Merging it without the Azure keys in prod stops escalation Tier 2, lead lifecycle, Lingua campus and the Nexus matcher | claude/revops handoff |
Planning docs and comments that lag the code
| Source | Says | Code says |
|---|---|---|
magic-booking-link | draft discovery; no public page | Booking links issued and redeemed end to end |
organization-feature-flags | blocked on credentials | Flag table, admin UI and organizationFeatureProcedure exist |
workflow-scoped-knowledge | draft, do not implement | V1 shape implemented (Foundry "Restrict Nexus to this workflow") |
configurable-public-voice-demos · vodafone-call-import | proposed | Built |
client-report-generation | V1 ships an empty registry | 4 generators registered |
schema-cleanup · vibe-code-cleanup | not merged · no code changes yet | Migration 0065 merged · ratchets landed |
user_acl slice 9 | not started | Auto-assignment (round robin / random / LLM) exists |
aws-checkremote-parity | not approved; don't run on AWS | AWS is the only accepted target |
| Insights V2, hourly-flex, drop-off, gemini-36 docs | Gemini 3.6/3.7 on Vertex is primary; drop-off adjudicates four states | Gemini tiers run on GPT-6 first; batch is OpenAI-first; drop-off is a deterministic cohort plus a gpt.fast cause/topic |
| Nexus epics | Gemini researcher, per-org nexus_enabled, a Conflicts tab | gpt.ultra source memo; on for all text channels except webchat; conflict scan only at ingest |
| AL UC2 epic | the tick is a disabled shell | Wired and running (until its scheduled removal) |
| WhatsApp edit safety | uncommitted | Merged |
| MiCampus SF hardening · Google Ads cadence | 15/30 min quiet period · first-name checks | 2 h quiet period · no first-name check |
| Jev tests | Lingua trial behind a per-org flag | No flag check on that path; gated only by the hook and the API key |
Root README.md | revival metric fields | revival_metrics table dropped (0065) |
guidance/engineering-constraints.md | Cloud SQL Postgres 16 | Terraform pins POSTGRES_18 (live value unverified) |
guidance/security-scanning.md · Terraform comments · status README release tuple | three services / three containers (api, webhooks, scheduler) | Five services |
phoneLineDirectory.ts header · Telnyx dispatch comment · "outbound bootstrap" comments | used by api/webhooks · dispatches CALL_ENDED in-process · outbound calls | Scheduler-only · enqueues voice-post-call · outbound AI calling removed |
multi-app-split/worker-split.md | 2 dispatcher ticks | 3 ticks + spool drain |
Glossary
| Term | Meaning here |
|---|---|
| target | One 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. |
| machine | An XState v5 machine registered in the workflow registry; nine exist. |
| envelope | The JSONB in targets.workflow_state: machine id, run id, version, xstate snapshot, nextActionAt, previousState, executionSafety. |
| tx_final | The 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. |
| WAKE | The event the 30 s checkAwaitingAction sweep sends to targets whose next_action_at is due. |
| handoff | Machine chaining through a durable workflow_handoff_pending row. Not the same as webchat "continuation". |
| instant machine | A machine that must finish in one dispatch (conversation-complete, CRM sync, call-complete, client successors). |
| restorePrevious | A successor's request to pop the stacked predecessor envelope back. |
send-safety hold / executionSafety | A 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 row | The standard "AI Requested Human Help" activity-log entry (needs_assistance). |
| system_issue | The audit category for Zube-only faults; diverted to logger.error and never shown to clients. |
| preHook / postHook / getPostWorkflow / preCrmSyncback | The typed client hook slots on the runner and the syncback service. |
| Foundry | The web-app area (and table agentic_messaging_templates) where orgs configure agent templates, graphs and guardrails. |
| tier | A semantic model name (gpt.fast, claude.smart…) resolved to a concrete model in packages/llm/src/models.ts. |
| Nexus / Nexus 2.0 | The knowledge base and its full-corpus, evidence-only researcher. Nexus Review is the operator queue of observed knowledge gaps. |
| Jev / Decision-1 | The probabilistic decision model (microsoft/microsoft-decision-1). Files still say "jev". |
| UC1 / UC2 | Addison Lee's two custom use cases: draft-only inbound prospecting, and a one-off cold outbound campaign (removal scheduled). |
| workflow-free runtime | The service runtime used by api, webhooks and telephony-infra: no runner, no machines. |
| tick lock | The advisory lock that elects which worker runs dispatcher ticks. |
| receipt / spool | The raw WhatsApp body stored in webhook_receipts / the raw body written to GCS when DB capture fails. |
| cadence · kill switch | A code-defined outbound sequence run by outbound_messaging_cadence · the per-org outboundCadenceEnabled setting. |
| continuation | The webchat feature that carries a conversation to WhatsApp or email via a bearer code. |
| BSUID | WhatsApp's business-scoped user id, used when Meta omits the phone number. |
| coexistence / SMB echo | A 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 · persona | A logged-in internal-domain human (even while impersonating) · the user an admin is impersonating via x-persona-user-id. |
| UI 2.0 | The "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 run | RevOps 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 lane | The 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.