# Data retention

How long a brand keeps its data, how the nightly purge removes the rest, what
erasing one person does (M1-14), and how a whole brand is deleted (M8-07,
[DOMAIN-RULES §11](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/docs/planning/DOMAIN-RULES.md#11-data-lifecycle)).

## The windows

Each brand sets its own windows on **Settings → Brand → Data retention** (it was
a card on the Danger zone page until 1.4.1; the Danger zone now holds only
**Delete this brand**). Only an Admin sees the page and only an Admin may change it
(`brand:manage`).

| Data | Default | Range | What the purge does |
|---|---|---|---|
| Closed tickets and their messages | **Forever** | Forever, or 1 to 3650 days after close | Hard-deletes the ticket, its messages, activity, tags and attachments, and queues the attachments' objects for deletion from the bucket |
| Spam tickets | **30 days** | 1 to 3650 | The same hard delete, on its own clock |
| AI call logs | **90 days** | 1 to 3650 | Nulls the prompt, response, redaction map and sources of older `ai_calls` rows and stamps `bodies_purged_at`. The row stays with its tokens, cost, latency and prompt hash, for reports and the budget meter (M7) |
| Help center search log | **180 days** | 1 to 3650 | Hard-deletes the search log (M5-05) and, in the same window, the article view rows that dedupe view counts (M5-08). The count is the search log's |
| Audit log | **730 days** | **90** to 3650 | Hard delete |
| Visitor sessions with no conversation | **30 days** inactive | 1 to 3650 | Hard-deletes inactive `widget_visitors` only when no ticket references them; a visitor with a conversation keeps its session |
| Notification rows | **30 days** | fixed | Hard-deletes rows older than the bell's display window |
| Bulk operations and their items | **7 days** | fixed | Hard-deletes the log of a bulk edit (M14-03) and the per-ticket values an Undo would put back; the Undo itself lasts 60 seconds |
| Webhook, Telegram and Meta delivery logs | **30 days** | fixed | Hard-deletes webhook deliveries that `succeeded`, `failed` or were `skipped`, Telegram replies that were `sent` or `failed`, and WhatsApp, Messenger and Instagram replies that were `sent`, `delivered`, `read`, `failed` or `refused` (M10), created more than 30 days ago. A delivery still `pending` or `queued` is kept. The rows hold copies of ticket and contact data (a webhook's frozen body, a Telegram chat id, a Meta customer id), so they do not stay as long as the audit log |
| Idempotency keys of the public API | 24 hours | fixed | Hard-deletes the stored answers of `Idempotency-Key` requests past their window (they were forgotten only when the same API key sent another POST) |
| Outbox rows and job receipts | 7 days | fixed | Hard delete, 7 days after publish or completion |

A brand that never saves the form is kept under the defaults. The form sends
every window at once (`PUT`), and the api refuses a body that leaves one out,
so a screen that predates a field can never reset it by omission.

Every save writes a `retention.updated` audit row with the windows before and
after, in days.

### "Next purge"

The third column is how many rows the next run would remove under the **saved**
windows. It is counted with the same conditions the job deletes by, so it is
the number that goes. "—" means there is nothing to count: closed tickets kept
forever, or a table that does not exist yet. For AI call logs it is the number
of rows whose bodies would be nulled.

### What counts as closed, and as spam

- A **closed ticket** is one with `closed_at` older than the window: `closed_at`
  is set the first time a ticket enters a closed state and cleared on reopen.
  Merged tickets are closed tickets.
- A **spam ticket** is one in the brand's Spam status, found by
  `ticket_statuses.is_spam` (generated from `system_key = 'spam'`) rather than by name, because a brand may rename it.
  Spam is never purged by the closed-ticket window, only by its own.

## The nightly run

```
03:00 UTC  maintenance.retention.schedule   one job per brand, then job_receipts
           maintenance.retention (brand)    closed, spam, AI call bodies, search log and views,
                                            audit log, idle visitors, notifications, webhook,
                                            Telegram and Meta delivery logs, idempotency keys,
                                            outbox → audit row
```

The worker registers the schedule on every boot, so a Redis that lost it gets
it back. Each brand's run is a job of its own, with the id
`maintenance.retention.<brandId>.<YYYY-MM-DD>`, so a tick that fires twice in
one night adds nothing the second time.

- **One brand at a time, one brand per transaction.** Every statement runs as
  the system principal of that brand alone, so row-level security keeps a run
  inside its brand.
- **Bounded batches.** Each batch is at most 500 rows in a short transaction of
  its own. A brand with a year of backlog is many short purges, never one long
  lock on `tickets`.
- **Idempotent.** Every purge is "delete what is older than the cutoff". A
  retried or repeated run finds fewer rows and removes nothing twice.
- **Objects follow their rows.** A batch reads its attachments' keys, deletes
  the tickets, and writes a `media.objects.purge` outbox row with the keys in
  the same transaction. The worker then deletes each object. A purge that rolls
  back deletes no bytes, and an object whose delete failed is retried with the
  outbox job.
- **Counts only.** Each run ends with a `retention.purged` audit row naming the
  job and carrying how many rows went per category, never an id or a value. The
  same counts are shown in the card's footer as the last run.

Anything that hangs off a ticket goes with it by `ON DELETE CASCADE`. A new
table with a foreign key to `tickets` must cascade (or set null); the retention
integration suite fails otherwise.

## Erasing one person

Erasure is immediate and not subject to these windows. It is "Anonymise" on the
contact page, and [the contacts guide](https://helpdock.oday-bakkour.com/docs/contacts/#erasure) describes it in
full. What it removes from tickets:

- **Attachments they sent**, both the ones they uploaded and any attachment on a
  message they wrote. Rows are deleted in the erasure's transaction and the
  objects are queued the same way as a purge.
- **Channel ids of their messages** (`external_message_id`: an email
  `Message-ID` names the sender's mail host). The message bodies stay, under the
  brand's retention.
- **Copies in other tables**: their Telegram chats (chat id and username), their
  WhatsApp, Messenger and Instagram conversations (the platform's id for them,
  their number, profile name and `@username`) with the replies delivered through
  them, the redaction maps of AI calls on their tickets, and the webhook
  deliveries that carry their data.

## Deleting a brand

An install admin deletes a brand; a brand's own Admin cannot, because a brand
is the tenant boundary and deleting one removes everybody's work in it.

In the admin it is **Settings › Brand › Danger zone › Delete this brand**: type the
brand's ticket prefix (`HD` for `HD-1042`) and "Delete brand". The page then
shows "Scheduled for deletion on …" with **Restore** on every tab, and every
tab is read-only until the brand is restored. The brands in their grace are
also listed on **System › Brands pending deletion**, with the days left and
Restore ([operations](https://helpdock.oday-bakkour.com/docs/operations/#the-system-page)).

1. **Asking.** `POST /api/install/brands/:id/deletion` with the brand's prefix
   typed out (`{ "confirmPrefix": "ACME" }`) sets the brand to `deleting` and
   starts a **30-day grace**. From that moment:
   - every public route of the brand answers **410 Gone** — the widget, the
     help center (on its own domain and under `/hc/<brandId>/`), its images and
     the web form — through one guard on every `@Public()` route, so a public
     route added later is covered too;
   - inbound mail stops: IMAP mailboxes are no longer polled, and the
     inbound-parse endpoint answers 410 once the shared secret checks out;
   - the brand's WhatsApp, Messenger and Instagram accounts stop being checked
     by the hourly health job, and their messages are not filed. The Meta
     webhook is the install's one URL, so it answers `200` and passes the
     brand's events over: a `410` would make Meta redeliver every brand's events
     or unsubscribe the app ([Meta channels](https://helpdock.oday-bakkour.com/docs/meta-channels/#how-metas-posts-are-checked));
   - the brand's API keys answer 410 on `/api/v1`, and its webhook deliveries
     are marked `skipped` instead of sent, so nothing leaves the brand through
     an integration. A restore does not replay what was skipped;
   - staff sessions stop naming the brand at their next refresh (at most ten
     minutes), as for any brand that is not active;
   - nothing is deleted yet, which is what makes a restore whole.
2. **Restoring.** `DELETE /api/install/brands/:id/deletion`, any time before the
   grace ends, sets it back to `active`. After the grace it answers 409.
3. **Purging.** At 04:00 UTC every night `brand.purge.schedule` adds a
   `brand.purge` job for each brand whose grace is over. The job removes:
   - **every row the brand owns**, in every table with a `brand_id` column —
     read from the database, not from a list, so a table a later migration adds
     is purged without anybody remembering it — in foreign-key order, in
     batches, as the system principal of that brand alone. Personal rows (a
     saved view, a personal canned response) are deleted in their owner's name,
     since row-level security shows them to nobody else;
   - **every object under `brands/<id>/`** in the bucket: ticket attachments
     and their variants, and the help center's article images, logo and favicon
     (`hc_media`);
   - **every Redis key with the brand's id in its name** — cached help center
     pages, rate-limit counters — except BullMQ's own, which age out on their
     queues' schedules and would corrupt a queue if pulled from under it;
   - **its custom domains**: the `brand_domains` rows Caddy's on-demand TLS
     asks about, so no new certificate is issued for them;
   - its IMAP pollers and its storage reading on the System page.

   The `brands` row stays, as `deleted`, so the **ticket prefix stays taken**:
   a new brand cannot reuse it, and an old ticket number can never name a new
   brand's ticket. Its public routes keep answering 410.

Every step is audited in install scope, where the record outlives the brand:
`brand.deletion_requested` and `brand.deletion_cancelled` name the admin, the
brand's name and prefix; `brand.purged` names the job and carries counts only —
rows per table, objects and Redis keys. A purge that dies halfway is retried and
finishes, since every step deletes what is left.

## API

| Route | Permission | |
|---|---|---|
| `GET /api/brands/:brandId/retention` | `brand:manage` | The windows, the "next purge" counts and the last run |
| `PUT /api/brands/:brandId/retention` | `brand:manage` | The whole form. 400 for a missing field, a window outside its range or an audit log under 90 days |
| `GET /api/install/brands/:id/deletion` | `install:admin` | Where the brand is in its deletion |
| `POST /api/install/brands/:id/deletion` | `install:admin` | Starts the grace. 400 unless `confirmPrefix` is the brand's prefix, 409 if it is already being deleted |
| `DELETE /api/install/brands/:id/deletion` | `install:admin` | Restores the brand. 409 once the grace is over |

The retention routes answer `{ settings, preview, lastRun }`, as
`retentionOverviewSchema` in `@helpdock/schemas` declares; the deletion routes
answer `{ brandId, status, requestedAt, purgeAfter, requestedBy }`
(`brandDeletionSchema`). `requestedBy` is `{ userId, name }` of whoever asked,
read from the install-scope `brand.deletion_requested` audit row (`name` null
for an account that no longer exists), and null for an active brand.

## Known gaps

- Composer uploads that were never sent (`message_id` still null) are not swept.
  They are deleted with their ticket.
- Brand deletion has its api and its job; the Danger zone's "Delete brand"
  button waits for its artboard.
- A CSAT rating link mailed before the deletion still opens during the grace.
  It names no brand in its address, so the 410 guard cannot see one; the purge
  removes the survey it points at.

### Imported contact profiles (M11, in development)

Contact erasure also clears retained imported profile details and linked staged
customer records. Profiles merged into the erased survivor are included. Source
identity pointers remain so another import cannot silently recreate an erased
contact. Company source details remain with the company row and disappear with
brand/account deletion. Import loading is still in development.

### Import staging (M11, local implementation batch)

The fixed staging window is 30 days after a run completes, fails or is cancelled.
Nightly retention removes staged records, confirmed mappings, import logs and
source-file metadata. It queues deletion of private upload, sealed-source and
unfinished preparation objects in the same transaction. Each batch is bounded;
a retry removes only what remains. The `importStaging` count in the retention
audit/last-run summary counts deleted database rows, rather than objects awaiting
the outbox consumer.

Imported article media has a separate 30-day grace measured from candidate or
asset creation. Cleanup protects references in every current working and
published article body and defers while a brand has an active or paused import.
It removes obsolete asset mappings and unreferenced importing media, queues
deletion of their canonical original/WebP keys through the outbox, and leaves
native uploads alone. Media processing and cleanup lock the same media row so
a queued conversion cannot recreate a purged object. These removed rows are
included in `importStaging`; referenced article assets outlive staging cleanup.

Discarding an uploaded file before extraction hides it immediately and revokes
its mapping revision. Cleanup retains its object pointers for 30 days from
discard, so a browser upload already in flight is still known to retention.
Active or paused import staging does not expire. Run summaries, native-ID
receipts and reusable file presets remain after staging cleanup; those receipts
keep repeat/delta identity stable. Imported tickets and contacts follow their
ordinary retention/erasure rules. This implementation awaits the final M11
batch tests.

Native ticket inventories use the same 30-day staging window. Cleanup removes
inventory ID rows in bounded batches before deleting their source-file metadata
and queuing private-object removal. Old mapping revisions and source hashes are
staging too; they do not survive source-file cleanup. Inventory upload/runtime
support is still under development, and these changes await the M11 batch tests.
