import { ActivixPlaygroundStore } from './ActivixPlaygroundStore.js'; import type { ActivixCollectionLegendRecord, ActivixExportResult, ActivixJobRecord, ActivixOptions, ActivixStorageBackend, CleanKeepLastHoursOptions, ExportRecordsToDirectoryOptions, FindByRunContextCriteria, GetJobActivitiesInput, GetJobActivitiesResult, MarkStaleOptions, PurgeOldRecordsOptions, StartRecordResult } from './types.js'; import { type ActivixCollectionTrackingState } from '@x12i/activix-contracts'; export declare class Activix { private store; private readonly ownedStore; private readonly collections; private readonly defaultCollectionName; /** Default jobs collection from constructor; job APIs require this or per-call `{ collection }`. */ private readonly jobsCollectionName; private readonly staleRecordTTL; private readonly purgeRecordMaxAgeMs; private readonly logger; private readonly skipStoreInit; private readonly rootOptions; private readonly collectionInputsForStore; private readonly deferredAutomatic; private readonly diagnosticsMeta; private readonly activixInstanceId; /** Resolved legend Mongo collection name (`activix-collections` default). */ private readonly legendCollectionResolvedName; /** When false, skip injecting registry collection and post-init legend sync. */ private readonly collectionRegistryEnabled; /** Whether host passed a configured `@x12i/xronox` engine for Mongo-backed stores. */ private readonly xronoxConfigured; /** Cached `activix-collections` tracking state per collection name (TTL-gated). */ private readonly collectionTrackingStateCache; /** How long cached legend `state` remains valid before re-reading storage. */ private readonly collectionTrackingStateTtlMs; /** In-memory activity rows when collection tracking state is `off`. */ private readonly ephemeralActivityRecords; private initialized; private initPromise; private initCallCount; private costCalculator; private _storageBackend; /** * `pending` until **`await init()`** when **`storageMode: 'automatic'`**; otherwise `database` or `local` at construction. */ get storageBackend(): ActivixStorageBackend; constructor(options: ActivixOptions); private buildMongoStore; private buildPlaygroundStore; private resolveAutomaticStore; private _requireStore; private emitPersistenceWarning; private insertWithPersistenceWarning; private updateWithPersistenceWarning; /** * Constructs an instance and **`await`s `init()`** — same as `new Activix(options)` followed by **`await ax.init()`**. */ static create(options: ActivixOptions): Promise; private _resolveCollection; /** Jobs helpers: per-call `collection` overrides constructor `jobsCollection`. */ private _resolveJobsCollectionName; private resolveCollectionRegistryOwner; private registryAboutTemplate; private shouldSkipAutoLegendInsert; private ephemeralRecordKey; private storeEphemeralRecord; private getEphemeralRecord; private isCollectionTrackingStateCacheFresh; private rememberCollectionTrackingState; private invalidateCollectionTrackingStateCache; private collectionNamesForTrackingStateRefresh; private fetchCollectionTrackingState; private resolveCollectionTrackingState; private shouldPersistToCollection; /** * After store init: ensure one legend row per configured collection in the registry (insert-only if missing). */ private syncCollectionRegistryIfNeeded; /** Collection names for bulk ops: one name or every configured collection. */ private _collectionNamesForBulk; init(): Promise; private getAutoCostApplyOptions; private getCostCalculatorForAutoCost; private maybeApplyAutoCost; /** Merge routing/config mirrors and optional auto-cost before validation and persistence. */ private finalizeRecordBeforePersist; /** * Create a new activity: generates **`activityId`** (unless you supply a non-empty primary key), persists, and returns it. * Use that **`activityId`** for every later call (`completeRecord`, `failRecord`, `markInProgress`, `patchRecord`, `getRecord`). */ startRecord = Record>(data?: Partial, options?: { collection?: string; }): Promise>; /** * Mark a record completed. `id` is the primary key value (default field `activityId`). */ completeRecord = Record>(id: string, updates?: Partial, options?: { collection?: string; }): Promise; /** * Mark a record failed. `id` is the primary key value (default field `activityId`). */ failRecord = Record>(id: string, error: string | Error, updates?: Partial, options?: { collection?: string; upsertIfMissing?: boolean; }): Promise; /** * Partial update by primary key (`activityId` by default). Allowed **regardless** of current status * (`started`, `in_progress`, `completed`, `failed`, `timeout`, …) — use for arbitrary fields; * use `completeRecord` / `failRecord` / `markInProgress` when you want lifecycle semantics. */ patchRecord = Record>(id: string, fields: Partial, options?: { collection?: string; }): Promise; /** * Mark an activity as still running (between `startRecord` and terminal `completeRecord` / `failRecord`). * Sets `status` to `statusValues.inProgress` and optionally updates `progressAtField` (if configured) to `Date.now()`. * `id` is the **`activityId`** returned from `startRecord`. */ markInProgress = Record>(id: string, updates?: Partial, options?: { collection?: string; }): Promise; /** * Load one record by primary key. Uses xronox-store per-key cache when the key was recently written. * `id` is the primary key value (default field `activityId`). */ getRecord = Record>(id: string, options?: { collection?: string; }): Promise; /** * Query by filter (Mongo query shape). Uses store `readMany`. Tombstoned docs are excluded when the collection * defines xronox-store **`visibility`** (Activix sets it when it creates the store). Pass **`mergeCache: true`** * to union matching in-memory PK cache entries with DB results (xronox-store 1.2+). */ findRecords = Record>(filter: Record, options?: { collection?: string; limit?: number; sort?: Record; mergeCache?: boolean; includeHidden?: boolean; }): Promise; /** * Query by **`sessionId`** and/or other **`runContext`** subfields, optionally with **`status`**. * Builds a Mongo filter on `.…` (default `runContext.sessionId`, etc.). * Uses **`readMany`** (database) — not the in-memory per-key write cache; rows only in cache may be omitted until persisted. */ findRecordsByRunContext = Record>(criteria: FindByRunContextCriteria, options?: { collection?: string; limit?: number; sort?: Record; mergeCache?: boolean; includeHidden?: boolean; }): Promise; /** * Official runtime-observability query for package-owned Activix clients. * * The configured store remains the source of truth: Mongo/xronox-store in database mode, * or the local playground store when this instance is running locally. `mergeCache: true` * asks the backing store to include hot in-process cache rows where supported. */ getJobActivities(input: GetJobActivitiesInput): Promise; /** * Create (insert) a job record in a dedicated collection (configure `jobsCollection` or pass `{ collection }`). * * This is intentionally separate from `startRecord()` which writes activity records with lifecycle semantics. */ startJob(input: Omit, options?: { collection?: string; }): Promise; /** * End (patch) a job record by jobId in a dedicated collection (configure `jobsCollection` or pass `{ collection }`). */ endJob(input: { jobId: string; endedAt?: number; }, options?: { collection?: string; }): Promise; /** * Fetch one job record by `jobId` from a dedicated collection (configure `jobsCollection` or pass `{ collection }`). */ getJob(jobId: string, options?: { collection?: string; }): Promise; /** * Fetch job metadata + activities across all configured collections. * `job` comes from the jobs collection; `activities` are from `getJobActivities()`. */ getJobBundle(input: GetJobActivitiesInput, options?: { jobsCollection?: string; }): Promise<{ job: ActivixJobRecord | null; graphRun?: unknown; activities: unknown[]; }>; /** * List recent jobs from the jobs collection (configure `jobsCollection` or pass `{ collection }`). * Optional case-insensitive substring search over `description`. */ listJobs(input?: { limit?: number; searchText?: string; }, options?: { collection?: string; }): Promise; /** * Insert a “legend” record describing a collection (purpose + owner). * If the record already exists for that `collectionName`, this method does nothing. * * Default legend collection name: `activix-collections` (primary key must be `collectionName`). */ initializeCollection(input: Omit & { createdAt?: number; runContext?: Record; }, options?: { legendCollection?: string; }): Promise; /** * List the collections configured on this Activix instance (constructor `collection` / `collections`). * This is in-memory metadata; it does not query MongoDB. */ listConfiguredCollections(): Array<{ name: string; primaryKey: string; }>; /** * Collection names that participate in per-collection tracking state * (excludes the legend registry when it uses `collectionName` as primary key). */ listTrackingManagedCollections(): string[]; /** * Fetch one legend record by `collectionName`. */ getCollectionLegend(collectionName: string, options?: { legendCollection?: string; }): Promise; /** * Toggle whether Activix persists activity rows for a collection (`track` vs `off`). * Requires an existing legend row (see `initializeCollection` / post-`init()` registry sync). */ setCollectionTrackingState(collectionName: string, state: ActivixCollectionTrackingState, options?: { legendCollection?: string; }): Promise; /** * Re-read legend **`state`** from storage and refresh the in-process cache. * Call after external changes to **`activix-collections`** (e.g. ops toggles in Mongo) * instead of waiting for the tracking-state TTL. * * When **`collection`** is omitted, refreshes every configured collection except the legend registry itself. */ refreshCollectionTrackingStates(options?: { collection?: string; legendCollection?: string; }): Promise>; /** * List legend records, newest first (best-effort). */ listCollectionLegends(input?: { limit?: number; /** Case-insensitive search within `about` and `friendlyName` (best-effort in local mode). */ searchText?: string; /** Filter by one or more tags (default matching mode: any). */ tags?: string[]; /** When true, require all requested tags to be present (instead of any). */ requireAllTags?: boolean; }, options?: { legendCollection?: string; }): Promise; /** * Convenience helper for Activities callers: return collection names that should be queried. * - Default: legends with `kind: 'activities'` * - Optional: filter by tags (any by default; set requireAllTags for all) */ listActivityCollections(input?: { tags?: string[]; requireAllTags?: boolean; searchText?: string; limit?: number; }, options?: { legendCollection?: string; }): Promise>; /** * Mark **`started`** records whose **`startTime`** is older than the TTL as **`timeout`** * (name from `statusValues.timeout`). Default TTL: constructor `staleRecordTTL`, overridable per call via `ttlMs`. */ markStaleRecords(options?: MarkStaleOptions): Promise; /** * **Client process:** run on a schedule (or after idle periods) to find activities that **never left `started`** * within the configured window. Same behavior as `markStaleRecords()` — prefer this name when documenting ops jobs. */ reconcileAbandonedActivities(options?: MarkStaleOptions): Promise; /** * Soft purge old records: marks records as purged (hidden from `getRecord` and `findRecords`) * when their `startTimeField` is older than `Date.now() - olderThanMs` (default: `purgeRecordMaxAgeMs`, * itself default 7 days). * * Uses store `updateMany` (no direct DB delete API is exposed via xronox/xronox-store). */ purgeOldRecords(options?: PurgeOldRecordsOptions): Promise; /** * Soft-purge every record **outside** the **keep-last** window: `startTimeField < Date.now() - keepLastHours` * (fractional hours allowed, e.g. `0.5` → 30 minutes). Same as `purgeOldRecords({ olderThanMs })` with * `olderThanMs` derived from hours. **`keepLastHours: 0`** purges all rows with `startTime` strictly before now * (use this for **clean-all** via `cleanAll()`). */ cleanKeepLastHours(keepLastHours: number, options?: CleanKeepLastHoursOptions): Promise; /** Soft-purge all records with `startTimeField < Date.now()` (same as `cleanKeepLastHours(0)`). */ cleanAll(options?: CleanKeepLastHoursOptions): Promise; /** * Write JSON snapshots under `targetDir`, mirroring playground layout: * `collections//records/.json`, plus `export-manifest.json`. * Uses `findRecords` with `includeHidden` so tombstoned rows are included by default. */ exportRecordsToDirectory(targetDir: string, options?: ExportRecordsToDirectoryOptions): Promise; /** Export all rows (no time filter). See `exportRecordsToDirectory()`. */ exportAllRecordsToDirectory(targetDir: string, options?: Omit): Promise; /** Export only rows whose `startTimeField` falls within the last `keepLastHours` (fractional hours OK). */ exportRecordsWithinKeepLastHoursToDirectory(targetDir: string, keepLastHours: number, options?: Omit): Promise; generateRecordId(): string; private baseLogMeta; isConnected(): boolean; /** * Optional legend registry reads require a ready backend. Playground/memory stores always qualify. * Built-in `XronoxStore` creates its xronox engine during `init()` — treat a connected store as ready * even when the host did not pass `options.xronox`. Custom `ActivixStore` implementations that * report connected without an engine must pass `options.xronox` (avoids xronox-store * "getByKey without xronox" noise during simulate/dev runs). */ private canReadLegendRegistry; /** When using playground local storage, returns the store; otherwise `null`. */ getPlaygroundStore(): ActivixPlaygroundStore | null; /** Markdown activity timeline from the playground store, or `null` if not in local playground mode. */ getPlaygroundMarkdown(): string | null; /** * Writes **`report.md`** (default: under the playground root). No-op when not using playground storage. * @returns Absolute path written, or `null` */ writePlaygroundReport(targetPath?: string): Promise; close(): Promise; } //# sourceMappingURL=Activix.d.ts.map