# Sales CRM

Sales and custom pipelines use deals plus a separate **Accounts** tab. Accounts
are workspace records and remain visible without a deal or fundraising pipeline
membership. The sales account editor has industry, company size, ARR/MRR,
renewal date, tags, products and segments; investor fields remain available in
fundraising projects. All deal amounts and forecasts currently use USD.

## Pipeline and forecast

Stages support `probability` from 0 to 1 (or null when unknown) and an explicit
`outcome` of `open`, `won` or `lost`. Set them in workspace settings for the
selected project. Existing labels such as `Discovery (10%)` remain readable as a
fallback; no imported labels or probabilities are rewritten.

Columns show counts, known amounts and weighted totals. The sales dashboard
shows open pipeline, weighted open pipeline, won deals and a weighted forecast
for a selected close-date interval. Unknown amounts add no estimated revenue;
unknown probabilities are reported separately. Forecasts exclude closed deals
and undated deals. Money is rounded to cents per deal before totals are summed.

Deals can link people with named roles (champion, buyer, etc.), an external owner
label, products, segments, competitors, tags, deal type, source, next-step date
and lost reason. Workspace member assignment remains distinct from external
owner labels; naming an external owner grants no access.

Stage moves append server-owned history in the same transaction. Repeated saves
in the same stage do not append history. History starts with recorded changes;
older changes cannot be reconstructed. Project stage edits reject removal of
stages still in use. Previously unconfigured deal stages remain visible as
additional lanes. Cards and tables show recorded last activity and time in stage.

## Prospect pages

Click a contact in the acquisition report or Prospects list to open its dedicated
page at `/app/WORKSPACE/PROJECT/prospects/PERSON_ID`. Breadcrumbs retain workspace,
project and prospect context. **Back to report** or **Back to prospects** restores
the originating filters and slice. Legacy `?section=prospects&personId=PERSON_ID`
links redirect to the same page.

Activity opens with recorded conversation threads in separate lanes beside a
canonical event stream. The stream combines messages, notes, approval events
and prospect changes, newest first. Use **Locate in all events** or **Show
conversation** to move between views; **All events** expands the stream.
Chat-style messages show participants, channel, author and time. Saved profile
images are used when present, with initials as the fallback; privacy mode masks
identity and suppresses images. `profileImageUrl` accepts an authorized HTTPS
photo URL through the existing person update API/CLI.
Provider, mailbox and thread identity keep distinct conversations apart. Messages
without a thread ID stay separate. Unknown occurrence dates are labelled and
appear after dated events; importing a note does not invent a contact date.
**Load earlier activity** retrieves older visible entries when available.

Details groups outreach status, ownership, next step and segments in one compact
form. Saves use the current record version and only changed fields. History
retains the recorded actor, reason and old/new values. Read-only access, field
redaction and privacy mode apply throughout; opening the workspace sends nothing.

## Sales work

The **Sales work** tab contains activity, tasks, collateral/documents, catalogs
and outreach sequences. The first-party CLI exposes the same routes with
`crm:read`/`crm:write` scopes and an optional project binding:

| Collection | Route | Purpose |
| --- | --- | --- |
| activities | `/api/pipeline/activities` | Email, call, meeting and note timeline |
| tasks | `/api/pipeline/tasks` | Due dates, assignee, progress and completion |
| resources | `/api/pipeline/resources` | Linked/Markdown collateral, case studies, contracts and invoice metadata |
| catalogs | `/api/pipeline/catalogs` | Workspace products, segments, competitors and the dimension rows that govern segments |
| views | `/api/pipeline/views` | Saved filters and explicit account/deal lists |
| sequences | `/api/pipeline/sequences` | Steps, enrolled people, outreach status and next due dates |

GET returns the plural collection and `{pagination:{limit,offset,hasMore}}`.
PUT creates or patches a record and returns its singular key. IDs may be supplied
for repeatable sync; omitted IDs are generated. Calendar dates use `YYYY-MM-DD`;
timestamps include an offset. All references must belong to the selected tenant;
linked deals must also belong to the selected project. Catalog kinds cannot be
changed after creation; archive them instead. Activity email `messageId` supports
idempotent ingestion. Notes and Markdown render as text, never executable HTML.

Saved views support search, tags, stage/owner/account IDs and product, segment,
competitor filters. The UI exposes search/tag views and checkbox-based lists;
the API supports the full filter shape. Bulk import and merge tools are CLI/API
workflows. Merges default to a preview, require explicit apply and workspace admin
access, and preserve target scalar fields plus combined notes and links. People
merges additionally require access to private person notes. Review the preview
and retain a pre-merge export; applying a merge removes the source record.

## Documents, email and automation

CLI 0.2.0 supports multipart deck uploads/versioning and Dataroom attachments
with scoped tokens. Contracts/invoices here are CRM records; existing Signatures
and Dataroom surfaces provide document storage and signature workflows. No
accounting ledger, payment collection or automatic contract execution is implied.

Connected apps supports opt-in continuous metadata capture from ZMail, ZCal,
ZergMeeting and existing Gmail connections. Each connection belongs to a member
and selected project, defaults to private, and exposes matching, health and
durable job results. Exact contact-email matches associate accounts and only
unambiguous deals. Private items appear in their owner's record workspace and
My day. Workspace publication requires an explicit visibility choice. Previously
published metadata remains in audit history after visibility changes. Google
OAuth stays in the browser; other sources use scoped read credentials. No
upstream account is connected automatically by deployment. See the CLI/API docs
for source setup and capture windows.

Account/contact/deal drawers include activity, tasks, documents, meetings, deck
engagement and attributed history. Quick actions log work, create/complete/snooze
follow-ups, and attach files or links. My day groups due work, upcoming meetings,
unanswered-email candidates and owned deals missing next-step details. Record
versions and preconditions protect edits against concurrent knowledge-base
syncs. `crm sync plan/apply` provides reviewable, conflict-preserving patch
results; `crm changes` supports incremental pull and checkpointing. It does not
install an Obsidian folder watcher.

Sequences are a plan and manual progress tracker. They do not send messages or
run a background campaign. No outreach is sent by any of these CRM writes.

## Library folders and ZergBox

Every Library section (Decks, Memos, Blurbs, Signatures and Dataroom) shows the
project's files in one folder tree on the left, with the section's own viewer
in the remaining width. The tree belongs to the project, so a folder holds any
mix of decks, memos, blurbs, signature envelopes and dataroom files; each
section lists its own kind, and **All files** shows the rest, which open in their
own section. Files without a folder sit at the root. The selected file is kept
in the URL (`?section=decks&item=ID`), including a file just created. A section
shows only the folders that hold one of its files (with a count while closed) and
empty folders; **All files** and **Move to…** show every folder. Open folders,
the panel width and whether the panel is collapsed are remembered in this browser
only.

The tree works from the keyboard: arrows move and open folders, Enter opens,
F2 renames a folder, Delete deletes one, and Shift+F10 or the context-menu key
opens a row's menu (Rename, Move to…, Delete folder, Open in ZergBox). Dialogs
take focus, keep Tab inside and close on Escape, and focus returns to the row.
In the Dataroom, files dropped from the computer onto a folder upload into it.

People who can read the project's Library can read the tree. Owners, admins and
members can create, rename, move and delete folders and move files, by drag and
drop or with **Move to…**; viewers and read-only project roles cannot. "New
deck", "New memo", "Upload file" and the other new-file actions put the new file
in the selected folder. Folder names are unique per parent without regard to case,
have no slashes and nest at most 12 levels deep. A folder can never move into
itself or a folder inside it. A folder that is not empty is deleted only by
choosing to move its contents up to its parent first. Every change sends the
version it read and is refused with 409 `CRM_VERSION_CONFLICT` when someone
changed the folder first. Each change is recorded with who made it
(`GET /api/pipeline/library/history`).

Routes (all need `ws` and `projectId`; writes are browser-only and same-origin):

| Method | Path | Contract |
| --- | --- | --- |
| GET | `/api/pipeline/library/tree` | `{folders[], items[], canEdit, zergbox:{enabled, webUrl, connect?}}` (`connect` is `connect` or `reconnect` for an owner or admin while the workspace has no working ZergBox Library). Each item has `kind`, `id`, `name`, `folderId` (null at the root) and `placementVersion` (0 until first moved). `crm:read` tokens allowed (`zdesk library tree`) |
| PUT | `/api/pipeline/library/folder` | Create `{name, parentId?}` (ZergDesk assigns the id; sending one with `expectedVersion:0` is refused with 400 `LIBRARY_FOLDER_ID_ASSIGNED`); rename, move or re-sort `{id, expectedVersion, name?, parentId?, sort?}`. Refusals: 400 `LIBRARY_NAME_REQUIRED` / `LIBRARY_NAME_INVALID` / `LIBRARY_NAME_TOO_LONG` / `LIBRARY_TOO_DEEP` / `EXPECTED_VERSION_REQUIRED`, 404 `LIBRARY_FOLDER_NOT_FOUND`, 409 `LIBRARY_NAME_TAKEN` / `LIBRARY_FOLDER_CYCLE` / `CRM_VERSION_CONFLICT` |
| DELETE | `/api/pipeline/library/folder` | `{id, expectedVersion, mode:'empty'\|'move-to-parent'}`. 409 `LIBRARY_FOLDER_NOT_EMPTY` for a full folder in `empty` mode; `move-to-parent` returns `{deleted, moved:{folders, items}}` and refuses with 409 `LIBRARY_NAME_TAKEN`, changing nothing, when a child folder's name is taken in the parent |
| PUT | `/api/pipeline/library/placement` | `{kind:'deck'\|'memo'\|'blurb'\|'signature'\|'dataroom', itemId, folderId (null for the root), expectedVersion}`. 404 `LIBRARY_ITEM_NOT_FOUND` for an item outside the project |
| GET | `/api/pipeline/library/history` | `?folderId=` or `?kind=&itemId=`; newest first |
| POST | `/api/pipeline/library/zergbox-copy` | Owners and admins, browser only. `{dryRun (default true), limit (1-500, default 50)}`; see below |
| GET, POST | `/api/pipeline/library/zergbox-connection`, `zergbox-connect`, `zergbox-return` | The workspace's ZergBox Library connection; see below |

Signature envelopes and dataroom files keep their existing project scoping; the
dataroom's `category` stays as file metadata that groups files on share pages
(the upload form calls it the share page section), independent of folders.

### Storage and the ZergBox flag

File bytes stay in PostgreSQL (BYTEA) behind a `LibraryStorage` interface
(`put`, `get`, `stat`, `delete`, `list` by path). The PostgreSQL implementation is
the default and changes nothing about how files are stored or served. A ZergBox
implementation (`server/utils/zergbox-library-storage.ts`) stores files in the
project's folder of the workspace's ZergBox Library.

`ZERGDESK_ZERGBOX_LIBRARY=true` (default off) turns on the ZergBox features: the
connection, the one-way copy, "Open in ZergBox" on folders and files that have a
copy, and "Open project box". Everything follows "ZergDesk Library on ZergBox:
storage contract v1" and appstore's later refinements; see
[ZergBox library contract v1](#zergbox-library-contract-v1) below.

| Route | Who | Contract |
| --- | --- | --- |
| `GET /api/pipeline/library/zergbox-connection` | Members | `{enabled, state, webUrl, organizationName, connectedAt, pending, attention, canConnect}`. `state` is `disconnected`, `pending`, `connected` or `attention` (ZergBox stopped granting the library: reconnect). `pending` (`{approvalUrl, expiresAt}`) is shown to owners and admins only |
| `POST /api/pipeline/library/zergbox-connect` | Owners and admins, browser, same-origin | Asks ZergBox for one approval (C1) and answers `{requestId, approvalUrl, expiresAt, reconnect}`. Open `approvalUrl`. A workspace that had a library reconnects to the same folder. 409 `ZERGAI_LINK_REQUIRED` until the workspace is linked to zergai; 403 `ZERGAI_IDENTITY_REQUIRED` without a Zerg sign-in; 502 `ZERGBOX_REFUSED` with ZergBox's `{status, code, message}` |
| `GET /api/pipeline/library/zergbox-return` | Owners and admins | ZergBox's return address (`?ws=&connection_request=`). Reads the outcome (C2) for the workspace's own pending request and redirects to `/app/{ws}?zergbox=connected` (or `pending`, `denied`, `expired`, `unavailable`, `unknown-request`) |
| `POST /api/pipeline/library/zergbox-copy` | Owners and admins, browser | `{dryRun (default true), limit (1-500, default 50)}`; see below. A real run needs the connection: 409 `ZERGBOX_NOT_CONNECTED`, or 409 `ZERGBOX_RECONNECT_REQUIRED` once ZergBox stops granting it |

The Library tree offers **Connect ZergBox** (or **Reconnect ZergBox**) to owners
and admins while the workspace has no working library (`tree.zergbox.connect`).
A real copy or connect needs `ZERGDESK_ZERGBOX_BASE_URL` (503
`ZERGBOX_URL_MISSING`) and `ZERGDESK_ZERGBOX_PRIVATE_KEY_PEM` (503
`ZERGBOX_SIGNING_UNAVAILABLE`; 503 `ZERGBOX_SIGNING_KEY_INVALID` for a key that is
not PKCS#8 Ed25519). The signer is read from that key by default while the flag is
on; `registerZergBoxSigner` in `server/utils/zergbox-connection.ts` only overrides
it (tests, or a key held elsewhere).

The copy mirrors the folder tree into the project's folder of the library and
copies uploaded deck versions (the current version's PDF or PPTX), dataroom files
and signature documents. Memos and blurbs are text and are not copied; Google
Slides decks have no file to copy. Run it with `dryRun:true` first: that reads
PostgreSQL only and lists each `ensure-box`, `mkdir`, `write`, `update`, `move`
and `skip`. A real run first reads the library's change feed, then writes at most
`limit` files and records each folder's and file's ZergBox id and revision as soon
as ZergBox confirms it, so it can be repeated until `done:true`. A repeat only
writes files whose bytes changed (replacing them under `If-Match`), puts back
folder and file names and places that changed in either app, and copies afresh
what people trashed or moved out of the library. Something trashed and restored
(or moved out and back) before the next run is still Desk's copy and is not
copied again. It never deletes or changes the BYTEA content. A copy someone
edited in ZergBox is reported as `edited_in_zergbox` and never overwritten; a
change that races the run is reported as `etag_mismatch`. A file whose ZergBox
copy already holds its new bytes (Desk's own overwrite whose answer was lost) is
recorded and skipped as `already-in-zergbox`. A dry run is `done` only when every
action is a skip.

Linked folders are renamed and moved before new folders are created, so a new
folder can take a name an old one gave up. A folder is created with an id Desk
chose and recorded first, so a lost answer is retried with the same id; a
same-named folder a person made in ZergBox is reported as `name_conflict` and
never taken over. Desk's own ZergBox folder for a Desk folder since deleted never
blocks a name: a new Desk folder with that name in that place takes it over
(`skip`, reason `reused`), and a Desk folder renamed to that name moves it aside
as "<name> (removed in ZergDesk)", keeping what is in it. A same-named file is adopted as a file's copy only when its size
and SHA-256 match (Desk's own upload whose answer was lost), and one of another
size is never downloaded. Names follow ZergBox's rules (exact and
case-sensitive; no `< > : " / \ | ? *` or control characters, no trailing dot or
space, no Windows reserved name): titles are sanitized and keep a real extension.

The client never follows redirects (a 3xx is refused as `redirect_refused`),
sends only UUID ids (any version), never sends a capability anywhere but the base URL, and
bounds what it reads (64 MiB of file content, 4 MiB of JSON) and uploads (32 MiB,
Desk's deck cap; ZergBox's own limit is the space's 5 GB quota, refused as
`too_large`).

### ZergBox library contract v1

The client (`server/utils/zergbox-client.ts`), the signer
(`server/utils/zergbox-envelope.ts`) and the library operations
(`server/utils/zergbox-library.ts`) are written to the contract and proved against
it: `server/lib/zergbox-library-contract.test.ts` makes every assertion of
ZergBox's executable contract test (`library-contract.postgres.test.ts`, A9)
through Desk's own client, against the fake ZergBox
(`server/test-support/fake-zergbox.ts`) and, with `ZERGBOX_REFERENCE_DIR` (a
ZergBox checkout) and `ZERGBOX_REFERENCE_DATABASE_URL` (a scratch database), against
ZergBox's own route handlers.

- **Control plane.** C1 connect, C2 connection status, C3 capability, C4 grant
  status, C5 revoke and C6 source mount are `POST`s of the signed managed-app
  envelope: Ed25519 over the canonical JSON of `{audience, expiresAt, issuedAt,
  issuer, method, nonce, path, requestSha256, subject, version}`, audience
  `zergbox-managed-box-v1`, the route path without any base URL prefix, a fresh
  32-byte base64url nonce and a 60-second window. A test pins Desk's output to the
  contract's test vector (seed `0x07`×32) byte for byte. Every request carries the
  workspace's zergai claim `{directoryOrganizationId, appTenantId: workspace id}`.
- **Capabilities.** One 15-minute `zsg_` capability per workspace, server-side
  only, re-issued when less than two minutes remain or once on a 401.
- **Data plane.** ZergBox's id-based routes: list (`GET /api/folders/{id}`, every
  page), stat, download (304, single ranges with `If-Range`, `If-Match` on the
  `"zb-<revision>-<sha256>"` validator), versions, upload (`If-None-Match: *`,
  create-only), overwrite, mkdir (with `clientFolderId`), move and delete
  (`If-Match: "<revision>"`), and the per-root change feed. Revisions and sizes may
  be numbers or strings. Web URLs are `{ZergBox}/app/file/{id}` and
  `/app/folder/{id}`, on ZergBox's public origin.
- **Errors.** Refusals become `{status, code, message}`, where `message` is
  ZergBox's `statusMessage`. `code` is ZergBox's own code whenever it sends one:
  under `data.code` on C1 and C2, at the top level on C3–C6 (contract 4.1). Those
  are `invalid_request` (a malformed envelope: "Managed app request is invalid"),
  `payload_too_large` (an envelope over 64 KiB, answered with a readable 413),
  `invalid_signature`, `expired_assertion` and `invalid_assertion` (a signed
  envelope ZergBox would not accept), `app_not_registered`, `app_not_installed`,
  `app_disconnected`, `nonce_replayed`, `library_required`, `zergai_link_required`,
  `zergai_link_mismatch`, `app_scope_denied`, `grant_unavailable`,
  `source_principal_not_member` (the approver left the space),
  `approver_access_reduced` (the approver of a write library became a viewer),
  `source_folder_unavailable` (the library root is in trash),
  `invalid_capability_lifetime`, and C6's `grant_access`, `not_found` and
  `invalid_path`, which C6 now sends in the same `{statusCode, statusMessage,
  stack, code}` shape. Desk names only the refusals ZergBox sends without a code,
  by status and route: `invalid_request` for C1's return-address and
  wrong-app-library 400s, `not_found` for C2's 404, `grant_unavailable` for C3's
  "Source capability exceeds approved access" and a device folder's "Source grant
  authority changed", and on the data plane (contract 4.2) `capability_invalid`
  (401), `forbidden`, `not_found`, `name_conflict`, `client_id_conflict` and
  `busy` (409s, by message), `etag_mismatch`, `precondition_required`,
  `invalid_request`, `too_large` and `range_not_satisfiable`. Every lost-grant
  code (`grant_unavailable`, `source_principal_not_member`,
  `approver_access_reduced`, `source_folder_unavailable`, `grant_access`,
  `app_not_installed`, `app_disconnected` and the zergai and scope codes) asks for
  **Reconnect ZergBox**. C4 reports a grant that stands but cannot be used as
  approved as `status: "attention"`, with `reason` (at the top level and on the
  grant) set to the code C3 would refuse with: `approver_access_reduced` or
  `source_folder_unavailable`; Desk reads it as `reason`, null otherwise. ZergBox
  marks every control-plane answer `Cache-Control: no-store`, and takes any UUID
  as an entry id, UUIDv7 included.
- **Change feed and echo suppression.** Each run reads the library root's feed from
  Desk's cursor and applies it to Desk's links in one transaction per page: new
  names, parents and revisions, the latest content hash, and entries trashed or
  moved out (a folder with every link under it). An event at or below the revision
  Desk recorded for that entry is Desk's own write and is skipped. Entries Desk
  never held (a person's upload) are not imported.

**Known limitation.** ZergBox credits every file Desk writes to the admin who
approved the connection (contract 2.6), and deletes a person's uploads when their
account is deleted. If that admin's ZergBox account is deleted, the Library copies
go with it; the next run copies them afresh. If the approver leaves the space or
becomes a viewer, ZergBox stops granting the library (a viewer's write capability
stops at once, and a reconnected library, which attaches its root, stops reading
too) and Desk asks for **Reconnect ZergBox**, which another owner or admin can do.

### Turning on the ZergBox Library (runbook)

1. ZergBox (appstore) ships the library contract and adds ZergDesk's registry
   entry to `ZERGBOX_CONNECT_APPLICATIONS`:
   `{"issuer":"https://zergdesk.com","subject":"zergdesk","displayName":"ZergDesk","signingPublicKey":"<Desk PEM>","allowedReturnOrigins":["https://zergdesk.com"],"zergaiZapp":"zergdesk","scope":"library","consentText":"ZergDesk keeps your Library files in this folder. It cannot see your other files."}`.
2. Make Desk's key in shell memory only (never on disk), stage it as a Fly secret,
   and send appstore the public half printed:
   `KEY="$(openssl genpkey -algorithm ed25519)"; printf '%s\n' "$KEY" | openssl pkey -pubout; fly secrets set --stage -a epoch-pipeline-q1 ZERGDESK_ZERGBOX_PRIVATE_KEY_PEM="$KEY"; unset KEY`.
3. Set `ZERGDESK_ZERGBOX_BASE_URL=https://zergbox.com` (and, if they differ from
   the defaults, `ZERGDESK_ZERGBOX_APP_ISSUER` and `ZERGDESK_ZERGBOX_APP_SUBJECT`),
   check `ZERGAPP_PUBLIC_URL=https://zergdesk.com`, then
   `ZERGDESK_ZERGBOX_LIBRARY=true`, and deploy.
4. The workspace must be linked to zergai (it is provisioned through the zergai
   directory) and the ZergBox space must be linked to the same zergai
   organization.
5. An owner or admin opens a project's Library and chooses **Connect ZergBox**,
   allows ZergDesk on ZergBox's page (signed in with the same Zerg account), and
   is sent back to Desk with `?zergbox=connected`.
6. Run the copy with `dryRun:true`, then repeat a real run until `done:true`.
7. To turn it off, set `ZERGDESK_ZERGBOX_LIBRARY=false`; the copies stay in
   ZergBox. To end access, Disconnect ZergDesk in ZergBox (Settings → workspaces
   → Workspace apps); **Reconnect ZergBox** later attaches the same folder, so every
   link stays valid.

## Discovery and post-call notes

A discovery call is logged as a `meeting` or `call` activity with a `discovery`
block (I023, I004). The block holds:

- `date`: the day the meeting was held. Omit it and Desk takes it from
  `occurredAt` in the workspace time zone; the post-call form always leaves it to
  Desk. A stored date follows the meeting when a later write moves `occurredAt`.
- `attendees`: Desk people as `{personId}` and anyone else as `{label}`. Attendee
  people are added to the activity's `personIds`, after the meeting's own person,
  so the meeting appears on their timelines, their record access is checked, and
  campaign analytics still counts it for the person it belongs to. Desk records them
  in `linkedPersonIds` and removes them again when they leave the attendee list or
  the notes are removed. To keep someone on the meeting regardless of the notes,
  link them as a participant.
- `problemsHeard` (`{theme, detail}`), `toolsUsed` and `workflows`: short labels
  the roll-up groups. Case and spacing differences count as one label.
- `answers` (`{questionId, answer}`): answers to the linked campaign's guide.
- `nextStep`, `nextStepDate` and `recordingConsent` (`unknown`, `yes` or `no`).
- `loggedAt`: set by Desk the first time notes are saved, never by a client. Later
  edits keep it, and restoring an earlier version from history brings back that
  version's time.
- Saving notes sets the activity's `observationType` to `meeting.held` unless it
  already names an observation other than `meeting.booked`, so campaign analytics
  counts the meeting as held.

Rules:

- Discovery notes are allowed only on meetings and calls (400 `DISCOVERY_KIND`).
- A timed meeting more than an hour in the future is refused
  (`DISCOVERY_MEETING_IN_FUTURE`).
- A `date` the client names must be the meeting's day (`DISCOVERY_DATE_MISMATCH`).
  A timed meeting may be a day either side, because of time zones; a date-only
  meeting, which only a historical import can be, must match exactly. A write that
  only moves the meeting is never refused for its stored date.
- Each answer must cite a question in the linked campaign's guide
  (`DISCOVERY_QUESTION_UNKNOWN`). Answers already stored for the same campaign stay
  valid after the guide drops their question, so an unrelated edit never fails, and
  a history restore brings back the version's answers as they were.
- Attendee IDs must be people in the workspace (`DISCOVERY_ATTENDEE_INVALID`).
- `discovery: null` removes the notes.

**Campaign link.** Any activity can carry `campaignId`. It must be a campaign in
the same project (400 `ACTIVITY_CAMPAIGN_INVALID`; another tenant's or project's
campaign reads as not found), and a newly linked campaign must not be archived
(`ACTIVITY_CAMPAIGN_ARCHIVED`). A link made before the campaign was archived
survives later edits. Activities that never send `campaignId` or `discovery`,
including the knowledge-base sync through `activities upsert`, save exactly as
before. A record that does send them gets the same rules from `activities upsert`,
in a dry run as in a write. A later sync that omits them keeps the notes and link
already stored, so notes logged with `zdesk discovery log --id` on a synced meeting
survive the next sync. Campaign analytics does not yet read `activity.campaignId`; per-campaign
results arrive with M3.

**Discovery guide.** A campaign may hold `discoveryGuide: {questions:[{id,text}]}`,
1 to 30 ordered questions with unique IDs, saved with the campaign's
`expectedVersion` like any campaign edit. `null` removes it. A human enters the
real guide in one of two ways, and never in the repository:

- **Browser:** Campaigns → select the campaign → **Edit brief** → **Discovery
  guide** tab. Add, reword, reorder or remove questions, then **Save campaign**.
- **CLI, from a private file:** keep the questions in a file outside any
  repository, one per line (list numbers and bullets are ignored), or as JSON
  `{"questions":[{"id"?,"text"}]}`. Read the campaign's version with
  `zdesk campaigns get CAMPAIGN_ID`, then run
  `zdesk discovery guide set CAMPAIGN_ID --file ~/private/guide.txt --expected-version N`.
  Questions whose text is unchanged keep their IDs, so earlier answers stay linked.
  A new question, in the file or the browser, gets a random ID (`q_` and 12 hex
  digits) that no question has held, so answers stored under a removed question never
  come to read as answers to a new one. The command prints the question IDs and
  counts, never the wording.

**Where people log notes:**

- **Post-call notes** on a prospect page and on a company page. It puts the
  prospect on the call, links the account, and can link an open campaign.
- **Log meeting** in a campaign's detail view, when the campaign has a guide. It
  shows the guide's questions as answer fields.
- The CLI: `zdesk discovery log`.

**Roll-up and the 24-hour measure.** The campaign detail view and the Campaigns →
**Insights & approvals** tab show `GET /api/pipeline/analytics/discovery`. It counts, per calendar
month of the meeting date and in total:

- distinct meetings, people and accounts;
- per theme, tool or workflow (`groupBy`), how many meetings mentioned it, and the
  people and accounts involved.

The logging measure counts every discovery meeting:

- **on time:** notes first saved within 24 hours of a timed meeting, or within 24
  hours after the end of a date-only meeting's day in the workspace time zone;
- **late:** first saved after that;
- **missing:** a meeting linked to a campaign with a guide, with no notes once its
  24 hours have passed;
- **pending:** still inside its 24 hours;
- **unmeasured:** historical imports, since Desk saw them only when backfilled.

The rate is on time ÷ (on time + late + missing). Every meeting passes the same
restricted-record filter as a timeline read: a restricted meeting counts only for
admins and its author. A principal whose access hides note or message bodies gets
activities without `discovery` (listed in `restrictedFields`) and an empty roll-up
marked `restrictedFields: ["discovery"]`; meetings still waiting for notes are left
out too, so the logging share is never measured over them alone. Record-scoped
principals get 403, and a `crm:read` token may read it. Nothing here sends a message
or enrolls anyone.

**History restore.** Restoring an activity from history follows the same reading
rules. A principal whose access hides notes or bodies restores the other fields and
leaves those as they are now, and the answer omits them; a meeting the principal
cannot read, now or in that version, is refused with 403 `FORBIDDEN`.

## Project identity

Project updates accept an explicit `slug`; renaming a display name alone keeps
the current URL. Update both when a URL should change, then refresh clients and
bookmarks. Project types are `fundraise`, `sales` and `custom`; custom projects
default to deal workflows and may set `settings.pipelineMode` to `fundraise`.
Workspace and project IDs remain stable across name and slug changes.

## Migration and verification

Schema changes are additive and idempotent. Existing imported accounts, deals,
contacts, stages, deck versions and share URLs are retained. No production CRM
import, merge, outreach or mailbox sync is part of deployment. Tests use fresh
PostgreSQL schemas and synthetic records; run the full suite with
`ZERGDESK_TEST_DATABASE_URL` set as described in the checkout README.

### CLI 0.2.0 release validation

The October 22, 2026 release passed `npm run verify`: 258 server/UI/database
tests, 140 CLI tests, four scoped typechecks, the 208-route catalog check and the
production build. Shared npm catalog/branch-policy checks passed 21 tests.
Chrome checks used a disposable database for accounts without deals, forecasting,
activity, task creation and project settings. The disposable fixture was removed.

Targeted mutation results (slices, not whole-application coverage):

| Area | Mutants | Killed | Timeout detections | Survived | Uncovered |
| --- | ---: | ---: | ---: | ---: | ---: |
| Sales metrics and saved-view filters | 300 | 293 | 0 | 7 | 0 |
| CRM configuration, stage transactions and deletion | 258 | 256 | 0 | 2 | 0 |
| Workflow input/reference/handler slices | 251 | 213 | 0 | 36 | 2 |
| Deck/merge tenant guards | 23 | 23 | 0 | 0 | 0 |
| CLI upload/import automation | 98 | 97 | 0 | 1 | 0 |
| Paginated sales exports | 72 | 65 | 7 | 0 | 0 |

Mutation testing exposed missing boundary assertions that were added before
release. The export timeout detections are altered-loop cases hitting runner
limits; the unchanged export tests pass normally. Surviving/uncovered counts are
reported conservatively rather than treating every remaining variant as killed.
Reports are generated under `reports/mutation/` and `cli/reports/` (git-ignored).

Production health, authenticated-route rejection, additive schema migration and a
synthetic weighted forecast were verified after deployment. Fingerprints of the
existing account, person, deal, deck, deck-version and project fields matched
before and after deployment. Historical stage ages remained unset, as intended.
No production import, merge, mailbox sync or outreach was executed.

CLI 0.2.0 was packed and smoke-tested through both aliases in an isolated install.
The existing global CLI installation was retained to avoid changing another
agent's commands mid-session.

## Ask Zerg: the Desk bot

Open **ZTC** in the left sidebar, or press **Ask Zerg** on an account or
prospect page, a row of the status-by-segment matrix, a campaign's toolbar or
the GTM review ("Prep Monday review"), to talk to Zerg beside the current
project. Zerg answers from your CRM with read tools only: the segment tree and
matrix, campaigns and their results, the GTM plan and agenda (owners and admins
only), prospects, accounts, people and deals, intro paths and connector reach,
activities and observations (with the discovery roll-up), the action queue with
each draft's gate status (`zergdesk_gate_status` reads one draft's gate as the
action's page shows it, without your own pending decisions), your bot proposals,
and My day. It cannot change records, approve or send anything, run a shell or
browse files. Attach material to its CRM record, not to the conversation.

**Proposals (M4).** While `ZERGDESK_BOT_PROPOSALS_ENABLED` is on, Zerg can also
*propose* a change with its `zergdesk_propose_*` tools, for a signed-in owner,
admin or member (never a viewer, a token-asked turn or a `@zerg` mention). The
changes it can propose are: a plan item's triage fields (owners and admins);
segments; a campaign's name, start, segments or owner; campaign members; a
prospect's status, next step, owner, owner group, hold reason or persona; a new
task; a reply tag; a sourced signal; and a new contact hold. It cannot propose do
not contact, lifting or changing a hold, a founder-only plan field (priority,
owners, decisions, goals, the starter set), consent, approvals or activation.

A proposal changes nothing. It waits, for at most 14 days, in a tray above the
conversation and on the prospect or account page it concerns, and in the
**Bot proposals** tab of the action queues. It shows each field before and
after, the bot's reason as plain text and its evidence.

**Apply** is the requester's, or any owner's or admin's. It re-runs the
record's own save as you, from the browser, so every check runs again (versions,
founder-only fields, the send policy's join guard, holds, do not contact). The
change history names the bot (`{system: 'zergdesk-bot', externalId: <proposal>,
path: 'bot:zerg/<tool>', runId: <conversation>}`). If the record changed in the
proposed fields since, the proposal goes out of date instead; a check that
refuses the apply leaves it waiting and records why. Any member who can see a
proposal may reject it, with a reason unless it is their own. Tokens may list
and read proposals (`crm:read`) but never apply or reject them. Executor-agent
tokens and record-scoped access see none, and plan proposals show only to those
who may read the plan. At most 50 wait per person and project, and one
conversation makes at most 20 an hour.

**@zerg in team chat.** With `ZERGDESK_ZTC_MENTIONS_ENABLED` on, `@zerg` in team
chat runs one read-only turn on the same pool, under the mentioning person's
access, and posts the answer in the room. The turn sees only that message, never
the room's history. Because the room is workspace-wide, Zerg answers there only
while every workspace member is an owner or admin and no CRM access rule narrows
any of them, the asker holds no private intelligence record, and the asker
cannot read private person notes (a global admin can; ask in the Desk pane
instead). Otherwise, outside a project, or with the CRM assistant off, it posts a
fixed notice and calls no model.
`@fakeidan` no longer answers: it is a Zerg Bot persona, and Desk's chat never
calls a model with the server's own key.

**What Zerg sees.** Every tool runs on the server under your own access at the
moment of the call: hidden fields are removed, restricted records stay out,
results are bounded, and the GTM plan tools refuse anyone who is not a workspace
owner or admin. A grant that hides intro paths reads every prospect's
relationship paths as empty and is refused the warm-intro tools (paths and
connector reach) whole. Contact holds show on the prospect, people and
account lists and on a record as they do on screen, naming who holds the contact
and never why, so Zerg
can say that only the hold's owner may reach out. A person or token limited to assigned records cannot use the
tools yet. The page you have open is sent as the *Desk view*: the section, its
filters, the record in focus and up to 100 selected rows. Before each turn the
server checks every ID against your current access and labels it from the
database, so the bot gets a short card of at most 2 KB, marked as untrusted UI
state; IDs you cannot see are only counted. The chip in the pane shows what the
bot was told: the page's view, or after **Ask Zerg** the view that question was
about, which stays until the page changes. If the page cannot be shared (a view
the server refuses, or a server error) the chip says why and offers Retry, and
the bot answers without a view. The view is published again whenever the window
regains focus, so with Desk open in two tabs the one you are using is what Zerg
sees. Each conversation process is told the current view once; the stored
message keeps your words.

**Streaming and history.** The answer streams into the pane and each tool call
shows as a row with its result. Stop ends the turn. Finished messages, tool rows
and errors are kept in Postgres (`crm_ztc_sessions`, `crm_ztc_events`) per
person, project and access grant and replayed when you reopen the pane, also
after a restart or deploy; streamed text in flight is never stored. A change of
role, global admin role (it alone shows private person notes) or CRM grant starts
a new conversation. If your access changes while Zerg is answering, or you are
signed out everywhere, the answer stops within a few seconds, the pane is
cleared and nothing more from it is kept. A pane opened while an answer streams shows it
from its start. Conversations untouched for 30 days are deleted, including
those from `ztc ask`. When the server restarts during an answer, the text so far
and an error are stored before it exits. A question asked while the server is
stopping is refused at once ("ZTC is restarting; retry shortly", kept as the
pane's error), and an analyst brief due then goes back in the queue, so nothing
starts a process the restart would cut off.

**How it runs.** Zerg is the pinned `@zergai/ztc` running as a pool of headless
subprocesses on the Desk server (`server/services/ztc/`): at most two at a time
by default, each for one person, project and conversation, stopped after five
idle minutes. One person's answers hold at most one process fewer than the pool
(one of the default two), wherever they ask, so someone else always finds one; a
second answer of theirs meanwhile gets `429` ("ZTC is already answering for you
elsewhere"). A process gets only the provider key, `PATH`, locale and proxy
settings and a private home directory, never the database URL or other secrets.
Its `zergdesk_*` tools call `POST /api/pipeline/bot-tools/:name` with a
capability signed for that one turn, bound to you, the project, the
conversation and your access grant, which expires within six minutes. It is
never shown to the model, logged or stored, and the key that signs it lives
only in the server's memory, so no new secret is needed and a restart simply
invalidates it.

The CLI's `ztc ask` uses the same pool and tools for a single answer (see the
CLI reference); an ask whose client disconnects is stopped at once. The
campaign analyst writes its briefs through a separate tool-less analyst mode on
the same pool: when every process is busy, the brief goes back in the queue and
is written on a later tick, without counting against the cooldown or daily cap,
and a running brief is leased for the whole start and turn budget. The analyst
and any other scheduled job run as background turns, which together hold at
most one process fewer than the pool (at least one), so a person asking always
finds a free process: two by default leaves one for scheduled work and one for
people. A job past that limit is refused before it starts a process and goes
back in its queue. The legacy ZDBot window is retired;
`POST /api/pipeline/zd/chat-stream` answers 410.

Deployment: `ZERGDESK_ZTC_ENABLED=true` turns the pool on, and
`ZERGDESK_ZTC_PROVIDER`/`ZERGDESK_ZTC_MODEL` choose the backend (production uses
`openai` with its existing `OPENAI_API_KEY`). `ZERGDESK_ZTC_POOL_MAX` (1-4),
`ZERGDESK_ZTC_IDLE_MS`, `ZERGDESK_ZTC_TURN_TIMEOUT_MS`,
`ZERGDESK_ZTC_MAX_ITERATIONS` and `ZERGDESK_ZTC_MAX_OLD_SPACE_MB` bound it. One
process measured about 215 MB resident locally, so two processes leave headroom
on the single 2 GB machine. The workspace must also turn the CRM assistant on
in AI Assistant settings; until then nothing is sent to a model.
`ZERGDESK_BOT_PROPOSALS_ENABLED` (propose tools, the proposal routes, the tray
and the Bot proposals tab) and `ZERGDESK_ZTC_MENTIONS_ENABLED` (`@zerg` in team
chat) are off unless set to `1`, `true`, `on` or `yes`.
`ZERGDESK_BOT_WORKER_ENABLED` (off unless `1`, `true`, `on` or `yes`) starts the
M4 bot job worker, whose Monday agenda brief and reply radar run on this pool as
background turns (see the GTM review guide, Bot jobs). The radar's reply tags
are bot proposals, so they also need `ZERGDESK_BOT_PROPOSALS_ENABLED`; without
it they stay suggestions on the run.

### Zerg Bot personas (M4)

Off while `ZERGDESK_ZERGBOT_ISSUERS` is empty (the default): every Zerg Bot route
answers 404 and the bot tools refuse bearers. It lists the exact origins of the
Zerg Bot servers Desk trusts (comma-separated, https in production), and
connections need `ZERGDESK_INTEGRATION_ENCRYPTION_KEY` (32 or more characters, a
secret, never in `fly.toml`) to seal each binding's delivery secret. In **Project
settings › Zerg Bot personas** an owner or admin connects one persona at a time:
Zerg Bot asks the persona's owner to approve, then Desk mints a 30-day token for
this project holding only `crm:propose`, narrowed by a `token:` rule that hides
amounts, check sizes, terms, intro paths and private notes. Desk grants no tool
until an admin ticks the read tools (and, once bot proposals are on, propose
tools) the persona owner approved; plan tools and a person's own day are never
grantable, nor are the warm-intro tools while the persona's rule hides intro
paths. The persona reads as its grantor and closes the moment the connection
is paused or revoked, the grantor stops being an owner or admin, the assistant is
turned off, the rule is removed or the issuer is no longer trusted. Each
connection is limited to 600 tool calls an hour. Revoking ends the token and the
rule and tells Zerg Bot; Zerg Bot can revoke from its side with a signed event.
A persona reviewer on the send gate can run on a connected persona instead of the
Desk pool (`reviewers.<persona>.runtime = {kind: "zergbot", connectionId}`, a guarded
policy change like any re-brief): the review worker sends Zerg Bot a signed
evaluation of the draft (never the brief, the bar or a recipient's name) and the
run waits up to 15 minutes for its signed result, which counts only for that run
and is checked and recorded exactly like a Desk-pool review. An unfunded persona
fails the run as `needs-funding`; manual reviews stay open.
Turning it on in production needs Zerg Bot's side (its own release) first.
`ZERGDESK_REVIEW_WORKER_ENABLED` (off by default; `1`, `true`, `on` or `yes`)
starts the persona review worker, which runs the send gate's persona reviews as
background turns on this pool (see Action queues).

## Reply tags and campaign sequences (M3b)

In a record's timeline, an inbound email, DM or InMail offers **Tag reply**:
Positive, Not now (with the month they asked to hear back in), Referral,
Unsubscribe, Out of office, or Clear. The tag shows as a chip and is stored on
the activity as `replyTag` with `observationType: reply.<tag>`.
`POST /api/pipeline/reply-tags` `{activityId, expectedVersion, tag|null, month?}`
is the only write: a signed-in owner, admin or member with every record in
scope, from the browser (tokens 403 `REPLY_TAG_BROWSER_ONLY`; a stale version
409). The generic activity write refuses `replyTag` and the side-effecting
types `reply.not_now` and `reply.unsubscribe` (403 `REPLY_TAG_ROUTE_ONLY`);
a restore keeps the current tag. Effects, in the same transaction:
- **Unsubscribe** sets an active, scope-all do-not-contact on the person, which
  cancels their pending actions and sequence enrollments.
- **Not now** needs a month from this one on (400 `REPLY_TAG_MONTH_REQUIRED`,
  `REPLY_TAG_MONTH_INVALID`) and sets the prospect's next step to
  "Follow up: not now (asked for YYYY-MM)" on the first of that month, never
  before tomorrow, keeping the owner (an assignment rule never reassigns it).
- Positive, referral and out-of-office change only the tag. Out-of-office is
  not a reply in any count.

My day lists **Follow-ups due**: a next step within 24 hours of a positive reply
or a held meeting (answered by a task for the person), and a scoping call within
48 hours of a positive reply (answered by a meeting or a status at or past
meeting booked). Replies older than 14 days do not count.

A sequence may set `campaignId`. Its planned and active enrollments must then
be the campaign's members (400 `SEQUENCE_ENROLLMENT_NOT_MEMBER` with the
`personIds`), and it never links an archived or foreign campaign (400
`SEQUENCE_CAMPAIGN_INVALID`).
