UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

457 lines (456 loc) • 36.9 kB
import type { WorkflowRun, WorkflowRunStatus } from "../orchestration/workflow.js"; import type { WorkflowScriptStore } from "../orchestration/workflow-script-store.js"; import type { WorkflowJournalStore } from "./workflow-journal-store.js"; import { type DamagedRowVerdict, type RowContext } from "./row-shape.js"; /** * design/97 S1b — the **WorkflowRunStore** persistence seam for the workflow-mode primitive * (`src/orchestration/workflow.ts`, S1a). It is the durable home for a {@link WorkflowRun} so the * `/workflows` observability layer (S1c) can list runs IN PROGRESS *and the history* (completed / failed), * across replicas — the "看之前的" core seam (design/97 §A/§D.1). * * **Distinct from the four load-bearing durable seams** (session / checkpoint / memory / tool-result): those * are the engine's suspend/resume命脉, so core ships PG adapters for them. A WorkflowRunStore is an * **observation layer — opt-in, non-engine-critical** — so per design/97 §D.8 (2026-06-22 拍) core * ships ONLY: this interface + {@link InMemoryWorkflowRunStore} (process-local / default / tests) + * `FileWorkflowRunStore` (zero-dependency, TOC-local persistence — `src/stores/file/workflow-run-store.ts`). * **The PG backend lives in service (TOB), implementing THIS interface** when it needs cross-replica * `/workflows` history. `WorkflowRun` / `WorkflowRunStatus` are imported type-only — this module is purely * the store contract + projection, it does NOT re-home the run model (that stays in `workflow.ts`). * * Mirrors the {@link import("./checkpoint-store.js").CheckpointStore} shape: create-once `put`, `get`, an * **atomic CAS `update`** (scope + `rev` optimistic-concurrency — concurrent agents racing to record progress * on the same run), a `listByScope` returning lightweight {@link WorkflowRunSummary} projections (history * included, NOT pending-only like CheckpointStore.listByScope), and a `reap` retention sweep that only ever * deletes TERMINAL runs (never a running one). The {@link summarizeWorkflowRun} projection is SHARED across * all backends (anti-drift, exactly like `summarizeCheckpoint`). */ /** * A lightweight, read-only projection of one {@link WorkflowRun} returned in bulk by * {@link WorkflowRunStore.listByScope} so the `/workflows` list view (CLI design/92 / client design/90) can * enumerate a scope's runs in ONE call — no N+1 `get`s, no full run payloads. Every field is DERIVED from * the persisted run (nothing here is a new source of truth or a gate input). Built by the shared * {@link summarizeWorkflowRun} so the projection is IDENTICAL across the in-memory, file, and (service) PG * backends. * * A UNION: a run whose stored record reads ({@link WORKFLOW_RUN_ROW_SHAPE}) is listed as {@link ReadableWorkflowRunSummary}; one * whose record does not is still one row of the listing — {@link DamagedWorkflowRunSummary}, its identity and its verdict — never a * failed page. Only the damaged arm carries `rowVerdict`: a consumer narrows with `"rowVerdict" in summary` before reading a member. */ export type WorkflowRunSummary = ReadableWorkflowRunSummary | DamagedWorkflowRunSummary; /** A listed run whose stored record does not read: the key it is filed under, the scope listed, and the verdict (the family's * code, the member that failed first, its form and the fixed engine sentence a `get` of it refuses with). No other member. */ export interface DamagedWorkflowRunSummary { readonly rowVerdict: DamagedRowVerdict; readonly id: string; readonly scope: string; } /** The summary of a run whose record reads. */ export interface ReadableWorkflowRunSummary { /** The run id ({@link WorkflowRun.id}). */ id: string; /** The tenant / grouping key this run lives in ({@link WorkflowRun.scope}). */ scope: string; /** The ORIGINATING session id ({@link WorkflowRun.originatingSessionId}), * projected so a serving layer's LIST face can apply its session acceptance/filter arm without an * N+1 `get` of the full run. Absent for a direct `runWorkflow` call / sessionless deployment. */ originatingSessionId?: string; /** design/99 MF-W: the workflow's display name from the script's `export const meta` ({@link WorkflowRun.name}). * Projected here so the `/workflows` list view labels each row WITHOUT an N+1 `get` of the full run. * Absent for a direct `runWorkflow` call that supplied no name. */ name?: string; /** One-line description from the script's meta ({@link WorkflowRun.description}); absent if none. */ description?: string; /** Lifecycle status ({@link WorkflowRun.status}): running / completed / failed. */ status: WorkflowRunStatus; /** `true` while the run is still `running` AND at least one leg is parked (on any gate; what it waits on is that leg's * checkpoint's gate) — something is being waited on while `status` still says `running` ({@link runParkedOf}). ABSENT * otherwise, never `false`: a run that has since suspended on the park reads `failed` + `errorCode: "workflow.agent_parked"` * (that code is its "a leg is parked" word; a consumer shows both arms the same way), and a settled record never carries it. * DERIVED from the agent rows on every projection — not stored on the run, so no second copy to drift. */ parked?: true; /** The MACHINE code of the failure that ended the run ({@link WorkflowRun.errorCode}) — the same word, * in the same vocabulary, that the full run carries; never re-derived and never a second taxonomy. * The fourth member of the same family as {@link agentFailures} / {@link budgetOvershoot} / * {@link timeoutInterruption}: those three qualify a row that LOOKS clean, and this one says WHY a * `failed` row failed. Nothing else on this projection can answer that — {@link status} is `failed` * for a refused spawn, a blown budget, a stalled run and a body that simply threw alike, so a list * face without this seat must `get` the full run per failed row to say anything at all, which is the * N+1 this projection exists to avoid. * * PRESENT EXACTLY WHEN THE RUN CARRIES ONE, absent otherwise — an absent key reads "no code on the * record", never "the run succeeded" and never a `workflow.unknown` stand-in. A `completed` run never * carries one (per {@link WorkflowRun.errorCode}), and a `failed` run whose body threw a codeless * error with no failed child on the record carries none either. Free of any own attribution rule: the * attribution (thrown code → first failed agent → absent) happens once, where the run is written. */ errorCode?: string; /** Count of agent-runs that ended failed ({@link WorkflowRun.agentFailures}) — present only when > 0. * Lets a list view flag a "completed, with failures" run without an N+1 `get` of the full run. */ agentFailures?: number; /** The run's TERMINAL token-budget overshoot ({@link WorkflowRun.budgetOvershoot}) — present ONLY when the * run actually spent MORE than its ceiling, absent on every run that stayed within one and on every run * that set no budget at all. The list-view twin of {@link agentFailures}: it lets a row be flagged * "completed, and over budget" without an N+1 `get` of the full run — the *other* way a `completed` row is * not the unqualified good news it looks like. It cannot be DERIVED from anything else on this projection: * {@link tokens} is a different axis (see its note), so without this seat an over-budget run reads on the * list face exactly like a clean one. * * Projected as a de-aliased shallow COPY — every other member here is a primitive, so the projection must * not hand a caller a live reference into a stored run (the same anti-aliasing posture the stores' `get` * keeps with `structuredClone`). Read the members per {@link WorkflowRun.budgetOvershoot}: the overshoot is * `spentTokens + unsettledTokens - budgetTokens`, and a run resting entirely on `unsettledTokens` is a * best-effort disclosure rather than a measurement. */ budgetOvershoot?: { budgetTokens: number; spentTokens: number; unsettledTokens?: number; }; /** The run's TERMINAL total-timeout interruption ({@link WorkflowRun.timeoutInterruption}) — present ONLY * when the `totalTimeoutMs` deadline had fired by the time the run reached its terminal. The third member * of the same family as {@link agentFailures} and {@link budgetOvershoot}: it lets a list row separate * "this run was CUT SHORT, and here is what it had achieved" from "this run failed", without an N+1 `get` * of the full run. Nothing else on this projection can answer that — {@link status} is `failed` either * way, and {@link agentCount} counts records regardless of how they ended. * * Projected as a de-aliased shallow COPY (same anti-aliasing posture as {@link budgetOvershoot}: a list * row must not be a mutable window into the stored run). Read the members per * {@link WorkflowRun.timeoutInterruption} — in particular `agentsFailed` is a PRE-abandonment count and is * NOT {@link agentFailures}, and `approvalWaitedMs` (#485, present only when a leg reported one) is the * LARGEST single leg's human-approval wait, a lower bound on how much of the window went on a person * rather than on work — never a sum, and its ABSENCE is "not supplied", never `0`. */ timeoutInterruption?: { timeoutMs: number; agentsCompleted: number; agentsFailed: number; agentsInFlight: number; approvalWaitedMs?: number; }; /** Title of the latest phase recorded ({@link WorkflowRun.phases}`.at(-1).title`) — what the run is on RIGHT * NOW for a `running` row (so the `/workflows` list shows the live phase without subscribing to the event * stream). Absent when no phase has started yet. */ currentPhase?: string; /** Number of phases recorded so far ({@link WorkflowRun.phases}`.length`). */ phaseCount: number; /** Number of agent-runs recorded so far ({@link WorkflowRun.agents}`.length`). */ agentCount: number; /** Total tokens spent = own + nested (`stats.tokens + stats.nested.tokens`) — the figure a triage view * sorts/compares by. own/nested stay SEPARATE on the full run (R-5); the summary folds them for display. * ⚠️ NOT the budget axis's figure: run stats also count REPLAYED work, which the budget deliberately never * charges, so comparing this against a ceiling proves nothing in either direction — whether a run overran * its budget is read off {@link budgetOvershoot}, never inferred from here. */ tokens: number; /** When the run started ({@link WorkflowRun.startedAt}, epoch ms). */ startedAt: number; /** When the run finished ({@link WorkflowRun.endedAt}, epoch ms) — absent while still running. */ endedAt?: number; /** When the run record was created ({@link WorkflowRun.createdAt}, epoch ms) — the `listByScope` sort key. */ createdAt: number; /** The run this one resumed ({@link WorkflowRun.resume}`.fromRunId`) — present on a resume's record, and only there. A list * row is the stored record's projection ({@link summarizeWorkflowRun}), so a resume's row carries it on every store: the * walk down a workflow's tree takes a row without it for a run that resumed nothing (it never reads that run's record to * ask). An edge on the newer record alone (the older one never gains it: the one write a later continuation makes on a * finished record sets a park entry's `passedTo`, the store bumping `rev`); whether a park still waits on a run is * `workflowParkWaitOf`'s (#5146), never this. */ resumedFrom?: string; } /** * design/97 S1b: project a {@link WorkflowRun} to its lightweight {@link WorkflowRunSummary}. SHARED by every * {@link WorkflowRunStore} impl so the projection is IDENTICAL across the in-memory, file, and (service) PG * backends (the anti-drift guard — exactly like `summarizeCheckpoint`). Pure; reads no clock/random. Total * spend folds own + nested (`stats.tokens + stats.nested.tokens`), the one place the two are summed. * * A list row does not answer "does this line still wait for an approval" — that question is asked only of `workflowParkWaitOf` * (#5146). The row says what the record says: a run that ended on a park reads `failed` with `workflow.agent_parked`, whatever has * happened to the card since. */ export declare function summarizeWorkflowRun(run: WorkflowRun): ReadableWorkflowRunSummary; /** The run a stored record says it resumed: its `resume.fromRunId` when that reads as a string, else nothing. */ export declare function resumedFromOf(run: WorkflowRun): string | undefined; /** The table as a host reads it in a refusal. */ export declare const WORKFLOW_RUN_ID_CHARACTERS = "1 to 64 of A-Z a-z 0-9 _ . -, and not \".\" or \"..\" alone"; /** Whether `id` is a workflow run id ({@link WORKFLOW_RUN_ID_CHARACTERS}). */ export declare function isWorkflowRunId(id: unknown): id is string; /** The refusal code of a workflow run whose stored record (or a write's candidate) does not read as {@link WORKFLOW_RUN_ROW_SHAPE}. */ export declare const WORKFLOW_RUN_ROW_MALFORMED_CODE = "workflow_run.row_malformed"; /** * THE WORKFLOW RUN'S MEMBER-SHAPE TABLE (`rowShapeReader`, row-shape.ts). `rowKey` is the file ledger's row predicate (the run id is * a string). `members` is what the readers reach for: the key it is filed under (a stored `id` that is not it contradicts the key), * the scope, the status word, the phase and agent rows the projection and the parked derivation read, the token stats, the stamps, * the optional display members and the terminal qualifiers, and the revision (a SQL twin gives it as an authoritative column). * Exit `list-damaged`: a listing answers such a run by its identity, a `get` and an `update` refuse it in * {@link WORKFLOW_RUN_ROW_MALFORMED_CODE}, and deletion by its session goes on. */ export declare const WORKFLOW_RUN_ROW_SHAPE: import("./row-shape.js").RowShapeReader<WorkflowRun>; /** * A stored run as every reader reads it — the run, or the refusal ({@link WORKFLOW_RUN_ROW_MALFORMED_CODE}) of one that does not read. * `ctx.key` is the id the store files it under; a SQL twin passes its authoritative columns (`id`, `scope`, `rev`). A backend's * `get` and the CAS's read of the live row go through this; a refusal is told to `disclose` first, naming the run by its key. */ export declare function readStoredWorkflowRun(raw: unknown, ctx: RowContext, disclose?: (sentence: string) => void): WorkflowRun; /** A write's candidate — its id and revision already placed by the backend's rule — held to {@link WORKFLOW_RUN_ROW_SHAPE}: the run to * store, or the refusal ({@link WORKFLOW_RUN_ROW_MALFORMED_CODE}) before anything is written. */ export declare function admitWorkflowRun(candidate: WorkflowRun, id: string): WorkflowRun; /** One stored run as a listing answers it: its summary, or — a record that does not read — its identity and verdict. */ export declare function summarizeStoredWorkflowRun(raw: unknown, ctx: RowContext, scope: string): WorkflowRunSummary; /** Whether a run is in a TERMINAL state (every word of {@link WORKFLOW_RUN_STATUSES} but `running`) — the ONLY states * {@link WorkflowRunStore.reap} may delete (a `running` run is never reaped). A word outside the closed set is not terminal. */ export declare function isTerminalWorkflowStatus(status: WorkflowRunStatus): boolean; /** A typed workflow-run-store error so callers branch on `code` (mirrors `CheckpointError`). */ export declare class WorkflowRunStoreError extends Error { readonly code: "workflow_run.already_exists" | typeof WORKFLOW_RUN_ROW_MALFORMED_CODE; constructor(code: "workflow_run.already_exists" | typeof WORKFLOW_RUN_ROW_MALFORMED_CODE, message: string); } /** REF-D18: `listByScope`'s query options — the SINGLE shape the interface method and both the * In-Memory and File implementations reference. */ export interface WorkflowRunListByScopeOptions { status?: WorkflowRunStatus; limit?: number; session?: string; /** Only the runs that resumed this run id (their summary's `resumedFrom`, strict equality) — a run's direct successors. * Applied before `limit`, like `session`. A store that ignores it answers the scope unfiltered, each row still the record's * projection: the reader takes a row as a successor only when its `resumedFrom` names the run (a row without the member is * none), so such a store costs every listing a scan of the scope and never a read per row. Implementing the filter (with an * index on the edge) makes each listing answer the successors alone. */ resumedFrom?: string; } /** * The words a {@link WorkflowRunStore.update} call can state about itself ({@link WorkflowRunUpdateOptions.cause}) when it is not the * owner recording its own run. Three words, each a write of a FINISHED run's record by another party — the whole record as `get` returned * it with one member added, compared on `rev` (and the creation read): * - `park_pass` — a later continuation of the run's chain takes over a park that run holds: one park entry's `passedTo` added (#4455); * at most three calls per write, of which at most one lands. * - `park_decision_settled` — the engine's continuation records a host's decision for a park that run holds as one it will never use: * entries added to park entries' `settledDecisions`; at most three calls per write, of which at most one lands. * - `tree_id_stamp` — a record an older engine wrote is given its tree id (`treeId`, as `workflowTreeIdStampOf` answers it): a pass * over a store's finished rows, the bundled file store's at its open. * A store may read the word (one that wraps another and tells its own observers "this run's state changed" can tell these writes from * the owner's: any word present means the run's own state did not change), but what it persists never depends on it: the row written * is the same with the word and without it. */ export declare const WORKFLOW_RUN_UPDATE_CAUSES: readonly ["park_pass", "park_decision_settled", "tree_id_stamp"]; export type WorkflowRunUpdateCause = (typeof WORKFLOW_RUN_UPDATE_CAUSES)[number]; /** * What a {@link WorkflowRunStore.update} call read of the row it writes — the SINGLE shape the interface method, the shared guard * ({@link nextWorkflowRunOnUpdate}) and both bundled implementations reference. A write wins only on the row it read: * - `rev` — the live row's revision must be this one (an intervening write bumped it); * - `creationId` — which creation of the run id the row is ({@link WorkflowRun.creationId}): a string ⇒ the live row's member must be * that same string; `null` ⇒ the live row's member must not be a string (absent and a stored JSON null alike: a row an older engine * created); absent ⇒ not compared. The rev never stands in for it, nor it for the rev: both must hold. * The engine gives `creationId` on every write it makes (`null` when the row it read carried none), so a row created again under a * reused id is never written with what was meant for the earlier one. */ export interface WorkflowRunUpdateExpect { rev: number; creationId?: string | null; } /** The creation id a stored run carries ({@link WorkflowRun.creationId}): the member when it is a string, else `null` — absent, a JSON * null and any other value alike read as none. The one reading of the member, as {@link WorkflowRunUpdateExpect.creationId} takes it. */ export declare function workflowRunCreationIdOf(run: WorkflowRun): string | null; /** {@link WorkflowRunStore.update}'s options — the SINGLE shape the interface method and both the In-Memory and File implementations reference. */ export interface WorkflowRunUpdateOptions { /** The kind of write, when it is not the owner recording its own run ({@link WORKFLOW_RUN_UPDATE_CAUSES}). PRESENT EXACTLY on such a * write and absent on every write the owner makes of its own record (its progress and its terminal), so an absent `cause` reads "the * run's own state changed" and any word present reads "it did not". Never a gate and never persisted. */ cause?: WorkflowRunUpdateCause; } /** * The pluggable persistence seam for workflow runs (design/97 S1b). Symmetric with `CheckpointStore`: * create-once `put`, `get`, an atomic CAS `update`, a `listByScope` query (history included), and a `reap` * retention sweep. A durable backend (service's PG) makes `/workflows` history cross-replica; the default * {@link InMemoryWorkflowRunStore} is process-only (single instance / tests). */ export interface WorkflowRunStore { /** Create-once. Throws {@link WorkflowRunStoreError} `already_exists` on a token collision (never a silent * overwrite — a reused id would clobber a live run's record). */ put(id: string, run: WorkflowRun): Promise<void>; get(id: string): Promise<WorkflowRun | null>; /** * Atomic CAS update of an EXISTING run (`UPDATE … SET … WHERE id=? AND scope=?` [`AND rev=?`] [`AND` the creation id]). Returns * `true` for the winner, `false` when the row is missing, the `scope` does not match (multi-tenant * isolation — a wrong-scope update must not win), `expect.rev` does not match the live row's `rev` * (an intervening update bumped it), `expect.creationId` is given and the live row is another creation of the id * ({@link WorkflowRunUpdateExpect}: a string must equal the row's member, `null` matches only a row whose member is not a string — * a SQL twin compares "is the extracted value a string", never "IS NULL", since a stored JSON null reads differently per dialect), * or the live row is terminal (`completed` / `failed`) and the candidate would move it back to `running` (a finished run never moves * back to running; updates that keep a terminal row terminal — `park_pass`, `park_decision_settled`, `tree_id_stamp` — still apply). * A write that loses changes nothing. On success the store bumps the row's `rev` (monotonic) and persists * the new `run`. The workflow owner writes its record while it runs (best-effort progress recording — design/97 §F); * once the run has finished, a later continuation of its chain may write it again to take over a park it holds * (`WorkflowRun.parks[].passedTo`), and the engine's continuation may write it again to record a decision for a park it holds as * one it will never use (`WorkflowRun.parks[].settledDecisions`) — each the whole record as `get` returned it, with `expect.rev`. * `expect.rev` lets each writer detect a lost write rather than silently clobber; a store must apply such a write to a finished * run like any other. `opts.cause` (additive) names those other writes ({@link WORKFLOW_RUN_UPDATE_CAUSES}) and is absent on every * write the owner makes of its own record, so a store that wraps another and reacts to "a run's state changed" can tell them apart * (any word present: the run's own state did not change). It never changes what is persisted: the CAS and the row written are the * same with it and without it, and a store that does not read it is correct. */ update(id: string, scope: string, run: WorkflowRun, expect?: WorkflowRunUpdateExpect, opts?: WorkflowRunUpdateOptions): Promise<boolean>; /** * List lightweight {@link WorkflowRunSummary} projections for runs in `scope` — **history included** (the * completed / failed runs, NOT pending-only like `CheckpointStore.listByScope`), so this is the "看之前的" * core query. Newest first (`createdAt` DESC). `opts.status` filters to one lifecycle state; `opts.limit` * caps the result count (applied AFTER the sort, so it keeps the newest N). An empty scope returns `[]`. */ /** `opts.session`: STORE-side push-down filter on * `originatingSessionId` — strict equality, rows WITHOUT the field excluded (filter semantics, * deliberately unlike the per-id acceptance arm's absent-pass). Applied BEFORE limit, so the * serving layer's "this session's workflows" is FULL-history, not page-window (cli note). */ listByScope(scope: string, opts?: WorkflowRunListByScopeOptions): Promise<WorkflowRunSummary[]>; /** * Retention sweep: delete OLD **terminal** runs in `scope` (a `running` run is NEVER deleted — design/97 * §D.1/§F). Returns the count deleted (for metrics). Retention is by either policy (apply BOTH when both * given — a run is reaped if it fails either bound): * - `opts.maxAgeMs`: delete a terminal run whose `endedAt` (else `createdAt`) is older than `now - * maxAgeMs`. * - `opts.keep`: keep only the newest `keep` terminal runs (by `createdAt` DESC); delete the rest. * With NEITHER option set, nothing is deleted (a no-op `0`) — retention is always an explicit policy. * It deletes ROWS: a run's journal and persisted script are found through its row, so a deployment that wires a journal or a * script store retains its runs with {@link reapWorkflowRuns} (the same selection, each run's journal and script erased before * its row), and keeps this sweep for a deployment that wires neither. A sweep is a deletion batch: it ends as * {@link settleErasure} does (once per call; a failure throws after the rows are deleted, and the next sweep settles them). */ reap(scope: string, now: number, opts?: { maxAgeMs?: number; keep?: number; }): Promise<number>; /** * Delete the run `runId` of `scope` when it is TERMINAL — {@link reapWorkflowRuns}' row step, after the run's journal and script. * `true` = this call deleted it; `false` = no such run in the scope, or it is running (a running run is never deleted). One row * of a deletion batch: a store that keeps a log of its writes does NOT take the row's earlier entries off its medium here — the * batch's end does ({@link settleErasure}; {@link reapWorkflowRuns} ends with it). Idempotent; a store fault throws. OPTIONAL: * absent ⇒ {@link reapWorkflowRuns} refuses this store. */ deleteRun?(runId: string, scope: string): Promise<boolean>; /** * The end of a deletion batch made of {@link deleteRun} calls — the background-agent store's member of the same name, read there * ({@link import("./background-agent-store.js").BackgroundAgentStore.settleErasure}); this store's own batch verbs ({@link reap}, * {@link deleteBySession}) end this way inside. OPTIONAL: a store whose `deleteRun` leaves nothing of the row on its medium (the * in-memory twin) omits it. */ settleErasure?(): Promise<void>; /** * Delete the TERMINAL runs in `scope` whose `originatingSessionId` is `sessionId` (strict equality, the * {@link listByScope} `session` filter's) — the session-tree cascade's leg ({@link import("./retention.js").RETENTION_CASCADE}). * A running run is never deleted (it is a live reference: the cascade does not delete its session's tree). Answers the ids it * deleted; idempotent (a repeat answers `[]`); a store fault throws. OPTIONAL: absent ⇒ this store's runs outlive the session * that started them, and the deployment owns that gap. */ deleteBySession?(sessionId: string, scope: string): Promise<string[]>; } /** * REF-A5 — THE optimistic-concurrency guard for {@link WorkflowRunStore.update}, shared by every backend: * scope in the WHERE (multi-tenant isolation — a wrong-scope update never wins), row must exist, an * `expect.rev` that no longer matches the LIVE row loses (an intervening update bumped it), an `expect.creationId` the live row is * not loses ({@link WorkflowRunUpdateExpect}), and a terminal row never moves back to a non-terminal state. Returns the * row to persist, or `null` when the CAS lost; PURE — it neither reads nor writes any store state, so * each backend keeps its own persistence mechanism (in-memory `Map.set` vs ledger commit) around it. * RB-59 (a cross-instance CAS both instances won) landed on this predicate. */ export declare function nextWorkflowRunOnUpdate(cur: WorkflowRun | undefined, id: string, scope: string, run: WorkflowRun, expect?: WorkflowRunUpdateExpect, disclose?: (sentence: string) => void): WorkflowRun | null; /** * REF-A5 — THE `listByScope` query projection, shared by every backend: scope/status/session filter → * newest-first by `createdAt` → truncate → one summary per row. Pure over the store's `[key, row]` entries. A filter excludes * on the member it reads: a member that does not read equals no filter value, so a run whose record does not read is listed * — by its identity and verdict ({@link DamagedWorkflowRunSummary}), and told to `disclose` — only where no filter excludes it. */ export declare function queryWorkflowRuns(runs: Iterable<readonly [string, WorkflowRun]>, scope: string, opts?: WorkflowRunListByScopeOptions, disclose?: (sentence: string) => void): WorkflowRunSummary[]; /** A reap candidate: a terminal run of the scope whose stamps read — its key, creation and end (else creation). */ export interface WorkflowRunReapCandidate { readonly id: string; readonly createdAt: number; readonly age: number; } /** The members a retention sweep reads of a run — a stored run and its listing summary alike carry them. */ type WorkflowRunReapRow = Pick<WorkflowRun, "scope" | "status" | "createdAt" | "endedAt">; /** * The runs of `scope` a retention sweep may consider, newest first — every backend's one reading of the members a sweep reads: a * terminal status word, a finite `createdAt` and an `endedAt` absent or finite. A run of the scope whose status or stamps do not * read is never reaped (a sweep cannot place it); it is told to `disclose`. A running run is not a candidate. Read over a store's * rows, or over a listing's summaries ({@link reapWorkflowRuns}). */ export declare function workflowRunReapCandidates(runs: Iterable<readonly [string, WorkflowRunReapRow]>, scope: string, disclose?: (sentence: string) => void): WorkflowRunReapCandidate[]; /** * The candidates a retention policy deletes — every reap's one rule: a run older than `maxAgeMs` (its end, else its creation, before * `now - maxAgeMs`) or past the newest `keep` terminal runs; either bound dooms it. `byAge` says the age bound ALONE doomed it — the * one doom a live row can undo (it ended since); a run the keep bound dooms stays doomed whatever its age (the keep bound is * set-relative, decided on the candidates as listed). */ export declare function workflowRunsDoomed(candidates: readonly WorkflowRunReapCandidate[], now: number, policy: { readonly maxAgeMs?: number; readonly keep?: number; }): Array<{ readonly id: string; readonly byAge: boolean; }>; /** The stores a workflow run's tree lives in — its row, its journal, its persisted script — as a deployment wires them * (`RunnerDeps.workflowRunStore` / `workflowJournalStore` / `workflowScriptStore`). */ export interface WorkflowRunTreeStores { readonly workflowRunStore: WorkflowRunStore; readonly workflowJournalStore?: WorkflowJournalStore; readonly workflowScriptStore?: WorkflowScriptStore; } /** A part of a run {@link reapWorkflowRuns} selected and could not erase: the store whose leg threw and what it threw. Its part stays * in that store; when that store is the run store the run's row stays too and the next sweep finds the run again, otherwise the row * is gone and nothing finds the part again (`runId` and `store` name it for a by-hand `deleteRun`). */ export interface WorkflowRunReapFault { readonly runId: string; readonly store: keyof WorkflowRunTreeStores; readonly cause: unknown; } /** * Retention for workflow runs, a run's tree at a time: the runs of `scope` a policy dooms ({@link workflowRunReapCandidates} over * the scope's listing, {@link workflowRunsDoomed} — the rule every store's `reap` applies), each erased the way a session's deletion * erases its runs ({@link import("./retention.js").RETENTION_CASCADE}): its journal, then its persisted script, then its row * ({@link WorkflowRunStore.deleteRun}) — so nothing a run id keys outlives the row it is found through. Before a run's first leg its * record is read again and the selection re-judged on it (gone, no longer a terminal run of the scope, or — doomed by age — ended * since: skipped, nothing of it erased). A run's three parts are all there or its row is gone (a conforming store refuses moving a * terminal row back to running; only an id deleted and recreated as running between that re-judgment and the row step leaves the * new running row in `kept`). Once its first leg has run, every * leg runs, the row's last, whatever the ones before it answered — a row left beside an erased journal is a run a resume would run * again from its start. A leg that throws is one entry of `kept` (its part stays in that store; a run whose row's own leg threw keeps * its row, and the next sweep finds it again); a row that is no longer a terminal run when its own turn comes is reported the same * way. The runs go newest first (by creation): of the runs one sweep dooms, a continuation is erased before the run it continues, so * a tree goes from its leaves up — the resume claim is keyed by a tree's root, read up the records, and a root erased first would * re-key the runs below it. That holds within one sweep only: each run is doomed on its own (its age, the runs kept), so a root that * ended long before its continuation is erased while the continuation stays (KL-4019-b). A fault ends the sweep once that run's legs have run (a record that cannot * be read again ends it before any): one fault leaves at most one run's part behind, and the runs after it keep all three parts for * the next sweep. Answers the runs whose rows * it deleted and the parts kept by a fault. A deletion batch, so it ends with the run store's * {@link WorkflowRunStore.settleErasure} (once; a failure throws with the runs already deleted, and the next sweep settles them). * Refused before anything is read (`TypeError`) when a store it is handed carries no `deleteRun` — that store's part of a run could * not be erased with the run (a deployment that keeps journals or scripts past their runs does not hand that store to the sweep). * A running run is never selected; a keep bound is decided on the listing as read (a soft * bound, as every reap's). A run whose record does not read is listed without its status or stamps, so this sweep neither selects * it nor counts it toward `keep` (a store's own `reap`, reading the raw members, may do both): it goes with its session. */ export declare function reapWorkflowRuns(stores: WorkflowRunTreeStores, scope: string, now: number, opts?: { maxAgeMs?: number; keep?: number; }): Promise<{ readonly deleted: readonly string[]; readonly kept: readonly WorkflowRunReapFault[]; }>; /** * Default in-process {@link WorkflowRunStore}. Single-instance / tests only — it does NOT survive a restart * or span replicas. Single-threaded JS already serializes `update`, so the CAS is trivially atomic here; * `structuredClone` on the boundaries prevents aliasing (a later mutation of the caller's object — the live * `WorkflowRun` the workflow keeps mutating — must not corrupt the stored row, and a returned run must not * be a live reference the caller can mutate back into the store). */ /** The retention knobs a workflow-run `reap` takes: an age bound and a keep-newest-N bound over the terminal runs. */ export declare const WORKFLOW_RUN_REAP_KNOBS: readonly ["maxAgeMs", "keep"]; export declare class InMemoryWorkflowRunStore implements WorkflowRunStore { private runs; put(id: string, run: WorkflowRun): Promise<void>; get(id: string): Promise<WorkflowRun | null>; update(id: string, scope: string, run: WorkflowRun, expect?: WorkflowRunUpdateExpect, _opts?: WorkflowRunUpdateOptions): Promise<boolean>; listByScope(scope: string, opts?: WorkflowRunListByScopeOptions): Promise<WorkflowRunSummary[]>; reap(scope: string, now: number, opts?: { maxAgeMs?: number; keep?: number; }): Promise<number>; deleteRun(runId: string, scope: string): Promise<boolean>; deleteBySession(sessionId: string, scope: string): Promise<string[]>; /** Test/inspection helper: number of stored runs. */ get size(): number; } export {};