# Engine Lifecycle

SearchEngine orchestrates the full index lifecycle: initialization, incremental refresh, search, and teardown.

## Four-verb API

| Method             | Purpose                                                   | Call once or many | Concurrent-safe |
| ------------------ | --------------------------------------------------------- | ----------------- | --------------- |
| `init()`           | Cold start — full fetch, build indexes, restore snapshots | Once              | No              |
| `refresh()`        | Incremental update — fetch diff, apply changes            | Many              | Yes (deduped)   |
| `search()`         | Query the index                                           | Many              | Yes             |
| `destroy()`        | Permanent teardown — abort, clear, release                | Once              | No              |
| `waitForRefresh()` | Wait for an in-progress refresh to complete               | Many              | Yes             |

Use `waitForRefresh()` when you need to ensure the latest refresh has completed before proceeding (e.g., after triggering a refresh via webhook).

## Scheduling

SearchEngine does not own polling. The caller decides when to refresh:

- **Timer:** `startPolling(() => engine.refresh(), intervalMs)` (from `@coda/async`)
- **Webhook:** call `engine.refresh()` on notification
- **Manual:** call from an admin endpoint
- **Cron:** schedule externally

## Observability

All lifecycle events flow through the [EventBus](pipeline.md#phase-4-score-fusion). SearchEngine emits typed events — the caller subscribes and logs, alerts, or tracks metrics.

Key events: `ENGINE_INIT_STARTED`, `ENGINE_INIT_COMPLETED`, `ENGINE_DESTROY_STARTED`, `ENGINE_DESTROY_COMPLETED`, `POLL_STARTED`, `POLL_COMPLETED`, `POLL_FAILED`, `EMBED_STARTED`, `EMBED_COMPLETED`, `ENGINE_CAPACITY_WARNING`, `SEARCH_ERROR`.

## Configuration

`SearchEngineConfig<TRaw, TDoc, TContext>` composes the engine from pluggable interfaces:

| Field               | Required | Type                              |
| ------------------- | -------- | --------------------------------- |
| `fetcher`           | Yes      | `SchemaFetcher<TRaw, TContext>`   |
| `transformer`       | Yes      | `DocumentTransformer<TRaw, TDoc>` |
| `embeddingProvider` | Yes      | `EmbeddingProvider \| null`       |
| `snapshotStore`     | Yes      | `SnapshotPersistence`             |
| `graphBuilder`      | No       | `GraphBuilder<TDoc, TContext>`    |
| `glossaryProvider`  | No       | `GlossaryProvider`                |
| `eventBus`          | No       | `EventBus`                        |

See [Pipeline Architecture](pipeline.md) for how queries flow through stages and signals.
See [Extending](extending.md) for custom stages, signals, and adapters.
