# API and types (short reference)

**`runContext`:** [run-context-object.md](./run-context-object.md).

Authoritative detail: [activitix.spec.md](./activitix.spec.md).

## Class: `Activix`

Constructed with **`ActivixOptions`**: either a pre-built **`XronoxStore`** (`store`, optional `skipStoreInit`) **or** connection options (`mongoUri`, `xronox`) plus **`collection`** or **`collections`**. Runtime packages must pass package-owned collection names in code; do not resolve package collection names from `.env`. Database name is resolved from env via `resolveActivixLogsDatabaseName()` (`ACTIVIX_DB_NAME` -> `MONGO_AI_LOGS_DB` -> `MONGO_LOGS_DB` -> `MONGO_DB` -> `"activitix"`). Built-in stores: **`collectionRegistry`** (default on) injects **`activix-collections`** and ensures one legend row per collection after **`init()`** when **`diagnostics.owner`** or **`collectionRegistry.owner`** is set.

### Lifecycle

- `init()` — deduped; respects `skipStoreInit`.
- `close()` — closes the store only if Activix **created** it (`ownedStore`).

### Records

- `startRecord(data?, { collection? })` → `{ activityId, recordId, record }` — **`activityId` is created here**; `recordId` deprecated alias; payload must include root **`outer`** (and optional **`inner`**) per [activity-structure.md](./activity-structure.md)
- `completeRecord(id, updates?, { collection? })` — `id` = `activityId` from `startRecord`
- `failRecord(id, error, updates?, { collection?, upsertIfMissing? })` — default upsert when phase-1 doc is missing
- `markInProgress(id, updates?, { collection? })` — sets `statusValues.inProgress`; optional `progressAtField` → `Date.now()`
- `patchRecord(id, fields, { collection? })` — any fields, **any** current status (incl. completed/failed); nullish PK stripped
- `getRecord` — store **`getByKey`** (per-key cache + tombstone visibility when configured on the collection)
- `findRecords(filter, { collection?, limit?, sort?, mergeCache?, includeHidden? })` — store **`readMany`**; optional **`mergeCache`** / **`includeHidden`** (xronox-store 1.2+)
- `findRecordsByRunContext(criteria, same options as findRecords)` — builds filter on `runContext.*` + optional `status`; type **`FindByRunContextCriteria`**
- `markStaleRecords` / `reconcileAbandonedActivities({ collection?, ttlMs? })` — same: `started` + `startTime` older than TTL → `statusValues.timeout`
- `purgeOldRecords({ collection?, olderThanMs? })` — **soft purge** (marks with `purgedAt`/`purgeAtField` and hides) where `startTimeField` older than threshold; default age from `purgeRecordMaxAgeMs` (default 7d); type **`PurgeOldRecordsOptions`**

### Utilities

- `generateRecordId()` — UUID-style id helper (primary keys use store prefix rules; not used to backfill `runContext.sessionId`)
- `isConnected()` — delegates to store

## Configuration highlights

Per collection: `name`, `primaryKey` (default `activityId`), `primaryKeyPrefix` (default `act-`), `runContextField` (default `runContext`), `progressAtField` (optional; touched by `markInProgress`), `purgeAtField` (default `purgedAt`) + optional `purgeVisibilityMode` → xronox-store **`visibility`** when Activix creates the store, `statusField`, `startTimeField`, `endTimeField`, `durationField`, `statusValues` (incl. optional `inProgress`), `indexes`, `cache` (via **`resolveCacheConfig`** when Activix creates the store). Activity **`outer`** / **`inner`** field names are fixed (not configurable).

Global: `defaultCollection` (**required** when using `collections`), optional `jobsCollection` (default target for job helpers), `staleRecordTTL`, `purgeRecordMaxAgeMs` (default 7 days, for `purgeOldRecords`), `errorHandling`, `logger` (gated by `ENABLE_ACTIVIX_LOGXER=true`), `onPersistenceWarning`, `strictPersistence`.

## Persistence warnings

`onPersistenceWarning?: (warning: ActivixPersistenceWarning) => void` receives structured write-failure metadata before Activix rethrows or swallows the persistence error. Normal lifecycle writes still reject after the warning. `patchRecord` remains non-fatal by default for compatibility; set `strictPersistence: true` to rethrow its persistence failures after the warning.

Events:

- `activix.record.insert_failed`
- `activix.record.update_failed`

Warning payload fields include `collection`, `operation`, `phase`, `primaryKey`, optional `activityId`, and a JSON-safe `error` summary. `phase` is resolved from top-level `kind`, then `outer.metadata.kind`, then `outer.input.kind`, else `activix:record`. If xronox-store provides clone diagnostics, Activix forwards them as `clone.path`, `clone.valueType`, and optional `clone.constructorName`.

## Fixed field on failure

`failRecord` always sets a string field **`error`** (not configurable in v2).

## Cache and tombstones

When Activix constructs `XronoxStore`, each collection uses **`resolveCacheConfig`** from xronox-store (same numeric defaults). Tombstone hiding uses store **`visibility`** derived from `purgeAtField` / `purgeVisibilityMode`. Pre-built stores must define matching **`visibility`** on each collection yourself.
