import { type RetentionDeclaration } from "../../core/retention.js";
import { type ExecutionOutcomeRecordWord } from "../../core/checkpoint-execution-record.js";
import { type HolderJudge, type StoreHolderFence } from "../../core/checkpoint-generation.js";
import type { CheckpointWriteOptions } from "../../core/checkpoint-store.js";
import { type Checkpoint, type PendingSteerEntry, type PendingSteerInput, type CheckpointFaultMode, type CheckpointStore, type CheckpointSummary, type CheckpointToken, type ReopenReason, type ResolveExpectation, type ResumeOutcome } from "../../core/checkpoint-store.js";
import type { GateOutcome } from "../../core/gate-outcome.js";
import { type CheckpointDeleteGuard, type CheckpointOverdueCursor, type CheckpointOverdueQuery, type CheckpointPage, type CheckpointRowRead, type CheckpointSessionCursor, type CheckpointSessionQuery } from "../../core/checkpoint-queries.js";
import type { AssertAllKeysHandled } from "../../core/ask-origin.js";
import { type IdentityRekeyInput, type IdentityRekeyPlan, type RekeyDone } from "../../core/identity-rekey.js";
import { type LedgerSpec } from "./shared-ledger.js";
import { type CorruptReadInfo } from "./corrupt-read-sink.js";
/**
 * design/80 §2.4 — THE LOAD-BEARING file store: a {@link CheckpointStore} whose once-only CAS is
 * behaviorally IDENTICAL to {@link import("../../core/checkpoint-store.js").InMemoryCheckpointStore}.
 *
 * **The decisive simplification (§2.4): the local binary is ONE process, one Node event loop.** So the
 * multi-process file-locking literature (per-op `flock`, `O_EXCL` lockfiles) buys nothing — there is NO
 * per-operation lock. Correctness instead rests on three things, exactly mirroring the in-memory store:
 *
 *  1. **In-process async mutex per token** — a `Map<token, Promise>` serialization chain (the SAME shape as
 *     `TtlSessionStore.pending`): `resolve`/`reopen`/`expire`/`setPendingSteer`/`put` on a given token chain
 *     behind one another, so no two interleaved async tasks can both read `pending` and both commit.
 *  2. **Authoritative state = an in-memory `Map<token, Checkpoint>`**, rebuilt by replaying
 *     `checkpoints.jsonl` (+ a compacted `snapshot`) at boot, last-writer-wins by event order (the latest
 *     event's status / resolvedOutcome / reopenReason / rev win — the "authoritative fields outside the blob"
 *     rule Pg implements with columns).
 *  3. **Commit ordering = appendLine the event + fsync BEFORE flipping the in-memory map** — so a crash can
 *     never leave "memory says resolved, disk says pending". A crash *before* the fsync'd append replays as
 *     `pending` (a retry can still win); a crash *after* replays as `resolved` (a retry is a no-op `false`).
 *     This matches the `testInjectFault` `resolve-before-commit` / `resolve-after-commit` contract exactly.
 *  4. **A line the replay cannot read refuses the store** — anything but an unfinished last append (read as not having happened,
 *     the crash *before* above). Folding past it is how a card whose `resolve` or `expire` line was damaged read as `pending` again
 *     and a second approval executed its tool a second time; the refusal (`FileLedgerDamagedError`, `store.ledger_damaged`, in
 *     `shared-ledger.ts`) is the closed direction, and `setAsideLedgerDamage(root, "checkpoints")` — the way out — sets every card
 *     the damage can have moved aside, so its resume finds no row and a person starts over. `FileStorageBackend` builds this store,
 *     so its refusal is the backend's too; `inspectFileLedgers(root)` reads the ledger without opening it.
 *
 * The CAS predicate is byte-for-byte the in-memory one: `row && row.scope === scope && row.status ===
 * 'pending'` plus the `expect.rev` OCC; `setPendingSteer` runs {@link validatePendingSteer} FIRST (before
 * the row lookup); the winner comes from {@link winnerFromOutcome}. NO per-operation flock.
 *
 * **What makes premise 1 true (and what used to only assume it):** the CONSTRUCTOR takes a coarse
 * cross-process writer fence on the ledger directory (`root/checkpoints/LOCK`, via
 * {@link import("./fs-atomic.js").acquireStoreDirLock}) — a second OS process over the same data root is
 * refused loudly ({@link import("./fs-atomic.js").FileStoreLockError}, code `store.dir_in_use`) instead
 * of quietly replaying a private view. Instances INSIDE this process share that fence exactly as they
 * share the authority (refcounted; the last {@link FileCheckpointStore.close} drops it), and a lock left
 * by a dead pid is pruned as stale, so a crash never needs manual cleanup. Before this the doc named a
 * fence this class never took — `FileStorageBackend`'s `root/LOCK` — which meant nothing at all for the
 * direct construction the root export invites: two processes each won the once-only CAS on the same
 * token (approval AND refusal both reported as the winner), and the process that had never loaded the
 * other's rows erased them at its next compaction, with no error on either side.
 */
/** One persisted ledger event. The replay folds these in order into the authoritative map. */
type LedgerEvent = 
/** The token's row is this value. Two writers: `put` (the row is created, once — the create-once judgment is the method's,
 *  not the event's) and the identity re-key (the row as re-filed in place, written under the token's lock). */
{
    t: "put";
    token: string;
    cp: Checkpoint;
} | {
    t: "resolve";
    token: string;
    rev: number;
    resolvedOutcome?: Checkpoint["resolvedOutcome"];
} | {
    t: "reopen";
    token: string;
    rev: number;
    reason: ReopenReason;
}
/** The execution-outcome record (CheckpointRow.executionOutcome): written once per row by
 *  `recordExecutionOutcome`; the replay sets both columns together. A binary released before this kind
 *  refuses the replay at the discriminator fence below while the event is still in the live ledger;
 *  once compaction has folded it into a snapshot row, that older binary reads the row with a field it
 *  does not know and its `reopen` (the pre-record predicate) ignores it — the same rollback shape the
 *  queue event above documents, disclosed in the release notes rather than fenced here. */
 | {
    t: "execution";
    token: string;
    gate: GateOutcome;
    atMs: number;
} | {
    t: "expire";
    token: string;
}
/** The row is gone (`deleteSessionCheckpoints`): the replay removes it from the map, and the next compaction writes no line for it. A
 *  binary released before this kind refuses the replay at the discriminator fence while the event is in the live ledger; once a
 *  compaction has folded it away the directory reads on that binary again — the store-format note the release carries. */
 | {
    t: "delete";
    token: string;
}
/** design/171 §5.3 — one APPENDED queue entry, carrying the `seq` the append minted so the replay is
 *  deterministic and never re-runs the bound checks an already-committed append passed.
 *  `rev` — the generation the append gave the row (one above the row's when the entry was added). Absent on an event written before
 *  the member existed: its replay adds the entry and leaves the generation where it was. */
 | {
    t: "steer_append";
    token: string;
    entry: PendingSteerEntry;
    rev?: number;
};
export interface FileCheckpointStoreOptions {
    /** This store's half of {@link import("./shared-ledger.js").LedgerPaths.onCorruptRead}. */
    onCorruptRead?: (info: CorruptReadInfo) => void;
    /** When false, an `appendLine` for a state transition is NOT fsync'd. The checkpoint COMMIT POINT always
     *  fsyncs regardless (its crash-safety depends on it); this governs the `put` and `setPendingSteer`
     *  (steer-append) commits only — `resolve`/`reopen`/`expire` fsync unconditionally. Default true. */
    fsync?: boolean;
    /** Compact the ledger into a snapshot once it exceeds this many events (then truncate). Default 1000. */
    compactEvery?: number;
    /** The session head read (a session store's `headOf`) {@link FileCheckpointStore.deleteSessionCheckpoints} judges its guard by and
     *  `deleteUnreadableSessionCheckpoints` judges unreadability by; without it the store has neither member. */
    sessionHeadOf?: (sessionId: string) => Promise<{
        readonly owner: string | null;
    } | undefined>;
    /** The deployment's grant judge ({@link HolderJudge}), asked on every write that carries a holder (`put`, `setPendingSteer`,
     *  `expire`, `resolve`); with it the store declares `fence = { holder: "writes" }`. It belongs to the directory's shared ledger: a
     *  second store over the same directory built with another judge (or with one beside none) is refused (`config.invalid_checkpoint_store`). */
    holderIsCurrent?: HolderJudge;
    /** The store's managed-retention declaration ({@link import("../../core/checkpoint-store.js").CheckpointStore.retention}), stated by
     *  the party that runs the sweep; default `"none"`, a third word refused (`config.retention_capability`). */
    retention?: RetentionDeclaration;
}
/**
 * Every event kind this reader understands — the ledger's CLOSED SET, exported so a program that reads a `checkpoints.jsonl` itself judges
 * a line against the words the store folds, not a copy of them. Kept as a VALUE (not just the type union) because the fence below judges
 * DECODED JSON, which no compile-time union can vouch for.
 *
 * Total BOTH ways at compile time ({@link CheckpointLedgerKindsAreTheEventUnion}): a plain `Set<LedgerEvent["t"]>` would have accepted a list
 * that silently forgot a member, and the failure shape of that drift is worse than the bug the fence fixes — a future release adding a
 * supported kind (union arm, switch case, writer) but not this list would DURABLY append the event and only then have the replay refuse
 * it: the write is on disk, memory is stale, and every later replay of that directory refuses the store. Forgetting a word, or listing
 * one the union does not have, fails to compile.
 */
export declare const CHECKPOINT_LEDGER_EVENT_KINDS: readonly ["put", "resolve", "reopen", "execution", "expire", "delete", "steer_append"];
export type CheckpointLedgerEventKind = (typeof CHECKPOINT_LEDGER_EVENT_KINDS)[number];
/** The fence over {@link CHECKPOINT_LEDGER_EVENT_KINDS}: `never` while the list and the event union name the same words. */
export type CheckpointLedgerKindsAreTheEventUnion = AssertAllKeysHandled<Exclude<LedgerEvent["t"], CheckpointLedgerEventKind> | Exclude<CheckpointLedgerEventKind, LedgerEvent["t"]>>;
/** The checkpoint ledger's files under a data root, and its fold ({@link import("./shared-ledger.js").LedgerSpec}). */
export declare const CHECKPOINT_LEDGER: LedgerSpec<Checkpoint, LedgerEvent>;
export interface ReadCheckpointLedgerOptions {
    /** This reader's half of {@link FileCheckpointStoreOptions.onCorruptRead}: told of every snapshot row / ledger event dropped as damage. */
    onCorruptRead?: (info: CorruptReadInfo) => void;
}
/** What {@link readCheckpointLedger} answers: the rows the ledger folds to, or no reading at all. */
export type CheckpointLedgerReading = {
    /** The directory held still for one whole read. */
    readonly settled: true;
    /** token → row, folded exactly as a store would fold it: fresh objects, owned by the caller, shared with no store. */
    readonly rows: ReadonlyMap<string, Checkpoint>;
    /** Ledger events folded over the snapshot (zero right after a compaction). */
    readonly events: number;
} | {
    /** The snapshot kept being replaced under the read (a writer compacting, three reads running): no verdict — the last read is not offered in its place. */
    readonly settled: false;
};
/**
 * Read a data root's checkpoint ledger WITHOUT opening the store — for a program that must know what the ledger holds beside (or instead of) a
 * running worker: a drain check asking whether a parked row still needs this engine's rows, an operator tool. It takes no writer fence
 * (`checkpoints/LOCK` is neither created nor consulted, so it neither contends with a live store nor is refused by one), opens no append
 * handle, and creates nothing — not the directory either: a root with no ledger reads as no rows. The fold is the store's own
 * (`applyCheckpointEvent` through the same discriminator fence), so a ledger event kind this binary does not know refuses the read exactly as
 * it refuses the store's replay (`checkpoint.unsupported_version`, `detail.reason` `ledger_event_unknown`); {@link CHECKPOINT_LEDGER_EVENT_KINDS}
 * is the word list that fence judges by; a pair holding a damaged line refuses the read as it refuses the store (`FileLedgerDamagedError`,
 * `store.ledger_damaged`). A root whose adoption is in flight is refused as the store refuses it. Beside a compacting writer
 * the read is bracketed (see {@link readLedgerSettled}) and is `settled: false` rather than a view that never existed.
 */
export declare function readCheckpointLedger(root: string, opts?: ReadCheckpointLedgerOptions): CheckpointLedgerReading;
/**
 * The checkpoint seat's identity re-key over a data root's ledger (`<root>/checkpoints`), without a store — what the data root's
 * adoption runs while its marker refuses every store constructor. It joins the directory's live authority when this process holds
 * one, else replays the directory under its writer fence (a writer in another process, or a damaged line, refuses it as it refuses
 * a store), and runs the store member's own implementation with the default ledger tuning; a root with no ledger directory holds no
 * rows and is not given one.
 */
export declare function rekeyCheckpointDirectory(root: string, input: IdentityRekeyInput, onUnrekeyable?: (name: string) => void): Promise<IdentityRekeyPlan | RekeyDone>;
export declare class FileCheckpointStore implements CheckpointStore {
    /** design/173 §2.3 — honest declaration on the restart-survival axis the vocabulary claims: rows
     *  live on disk (fsync'd append log) and survive a process restart. Multi-replica coordination is
     *  NOT claimed by this axis (see {@link StoreDurability}) — this backend is deliberately
     *  single-instance-per-data-dir, and now SELF-ENFORCING about it: the constructor takes the ledger
     *  directory's writer fence and refuses a second OS process by name (see the class header). Serving
     *  many writers at once remains Pg/TiDB's job — this refuses the second one, it does not coordinate it. */
    readonly durability: "durable";
    /** {@link FileCheckpointStoreOptions.retention}, as read at construction. */
    readonly retention: RetentionDeclaration;
    /** Honest declaration on the fidelity axis: the ledger is JSONL, so what this backend holds is the JSON
     *  PROJECTION of the row — a `Date` reads as its ISO string, a `Map`/`Set` as `{}`, `NaN` as `null`, an
     *  `undefined`-valued key not at all — before a restart and after it alike (the live map is filled from the
     *  same JSON reading as the ledger line); the declaration is what makes the loss visible to the mint BEFORE the
     *  row is filed. */
    readonly fidelity: "json";
    /** `{ holder: "writes" }`, declared exactly when the store was built with a `holderIsCurrent` judge. */
    readonly fence?: StoreHolderFence;
    private readonly holderIsCurrent;
    private readonly fsyncEnabled;
    private readonly compactEvery;
    /** RB-134: the directory's ONE authority (map + token mutex + append log), joined not rebuilt. */
    private readonly ledger;
    /** The checkpoint store's {@link HolderLatch}: {@link close} closes it, as does the dispose of the backend that built it. */
    private readonly latch;
    private get cps();
    /** The listing's memo of each replayed row object's verdict: a put or a replay holds a new object, so a replaced row is judged again. */
    private readonly rowVerdicts;
    /** One-shot crash fault (mirrors `InMemoryCheckpointStore.testInjectFault`). */
    private fault;
    /** The guarded {@link FileCheckpointStoreOptions.onCorruptRead} seat (the ledger's replay and this store's projection share it). */
    private readonly discloseCorrupt;
    private readonly ledgerPath;
    /** Present exactly when the store was built with a session head read (`FileCheckpointStoreOptions.sessionHeadOf`). */
    readonly deleteSessionCheckpoints?: (sessionId: string, guard: CheckpointDeleteGuard) => Promise<number>;
    /** Present exactly when {@link deleteSessionCheckpoints} is. */
    readonly deleteUnreadableSessionCheckpoints?: (sessionId: string) => Promise<number>;
    constructor(root: string, options?: FileCheckpointStoreOptions);
    /** Serialize an op behind any in-flight op on the same token (the in-process per-token async mutex). */
    private withLock;
    /**
     * Commit one ledger event (append + fsync) THEN flip the in-memory map (crash-safe ordering, §2.4).
     *
     * RB-150 (2026-07-25, cross-backend differential): the compaction that may follow is HOUSEKEEPING and
     * runs AFTER the operation is durable and the memory flip has happened — so its failure must never be
     * reported as the operation's failure. It was: a snapshot write hitting EACCES made `resolve()` REJECT
     * while the row was already `resolved` and the winner recorded, i.e. a consumed approval presented to
     * the caller as "this did not happen" — the worst possible direction for a once-only gate, and something
     * the in-memory reference cannot do because it has no I/O here. Both halves are now in the base.
     */
    private commit;
    put(token: CheckpointToken, cp: Checkpoint, opts?: CheckpointWriteOptions): Promise<void>;
    get(token: CheckpointToken): Promise<Checkpoint | null>;
    resolve(token: CheckpointToken, scope: string, outcome: ResumeOutcome, given?: ResolveExpectation): Promise<boolean>;
    recordExecutionOutcome(token: CheckpointToken, scope: string, gate: GateOutcome): Promise<ExecutionOutcomeRecordWord>;
    reopen(token: CheckpointToken, scope: string, reason: ReopenReason, expect?: Pick<ResolveExpectation, "rev">): Promise<boolean>;
    setPendingSteer(token: CheckpointToken, scope: string, steer: PendingSteerInput, opts?: CheckpointWriteOptions): Promise<boolean>;
    expire(token: CheckpointToken, scope: string, opts?: CheckpointWriteOptions): Promise<boolean>;
    reap(scope: string, cutoff: number): Promise<number>;
    listByScope(scope: string): Promise<CheckpointSummary[]>;
    listScopes(): Promise<string[]>;
    /** The listing faces' disclosure: a row read past a damage is reported through the corrupt-read seat, named by its non-secret
     *  identity (never its token). */
    private listingDisclose;
    listOverdue(query: CheckpointOverdueQuery): Promise<CheckpointPage<CheckpointSummary, CheckpointOverdueCursor>>;
    listBySession(query: CheckpointSessionQuery): Promise<CheckpointPage<CheckpointRowRead, CheckpointSessionCursor>>;
    rekeyIdentity(input: IdentityRekeyInput & {
        readonly mode: "plan";
    }): Promise<IdentityRekeyPlan>;
    rekeyIdentity(input: IdentityRekeyInput & {
        readonly mode: "leave";
    }): Promise<RekeyDone>;
    /** Force a compaction now (test/inspection). The snapshot rewrite + RB-167 closeForSwap swap that
     *  makes `replay` read the full state from the snapshot alone is the base's {@link LedgerCore.compact}. */
    compactNow(): void;
    /** Arm a one-shot fault on the next `resolve` (mirrors InMemory `testInjectFault`, council #5). */
    testInjectFault(mode: CheckpointFaultMode | null): void;
    /** Test/inspection helper: number of stored checkpoints. */
    get size(): number;
    /**
     * Release the append handle (best-effort). The LAST holder over the directory also drops its
     * cross-process writer fence, so a successor process can open the same data root; the data-dir-wide
     * `root/LOCK` (a different fence) stays the backend factory's to release.
     *
     * RB-134: refcounted, and the LAST holder REVOKES the directory's authority. Adding the shared table
     * without this would have repeated RB-73's mistake exactly — a cache with no invalidation: after a
     * `close()` the next `new FileCheckpointStore(sameRoot)` joined a table whose log was already closed and
     * every write threw `log_closed`, instead of replaying the on-disk truth into a fresh authority. Idempotent:
     * a second `close()` on the same instance must not decrement someone else's share.
     */
    close(): void;
}
export {};
