import { type WorkflowJournalEntry, type WorkflowJournalStore, type WorkflowLaunchRecord, type ResumeClaimArgs, type ResumeClaimAnswer, type StopResumeClaimArgs, type StopResumeClaimAnswer } from "../../core/workflow-journal-store.js";
import { type CorruptReadInfo } from "./corrupt-read-sink.js";
/**
 * RB-242 — how long a resume claim survives WITHOUT an engine release. This is the backstop for an engine that
 * died holding one (crash / kill -9 / box reboot): it never reaches its `finally`, so where its death cannot be
 * proven from here (another host, a start time this host cannot compare, a claim that names no process)
 * nothing but expiry frees the row, and a source run whose resume is wedged forever is a worse failure
 * than the fork this guards. One hour is the balance: comfortably longer than the gap between a resume's admission and its first
 * journal write (the window in which a fork actually duplicates work), and short enough that a crashed box does
 * not lock a run out for a working day. A LIVE engine's own release is the normal path and is prompt — this
 * value is only ever reached by a run that is no longer running.
 */
export declare const RESUME_CLAIM_TTL_MS: number;
/**
 * RB-356② — a release REFRAINS from unlinking its own claim once the claim is this close to (or past) its
 * expiry. Rationale: a peer may legitimately take a claim over the instant it expires, and `release` is a
 * read-then-unlink pair with no compare-and-delete syscall between them — so the one situation where the
 * unlink could destroy a SUCCESSOR's claim is precisely the one where the record we just read is already
 * takeable. Refusing to unlink there is free: an expired claim blocks nobody (the next acquirer takes it over)
 * and the sweep below reaps it. The margin only has to cover the scheduling gap between this method's read and
 * its unlink; seconds is orders of magnitude more than that, and losing the last five seconds of a one-hour
 * lease costs nothing.
 */
export declare const RESUME_CLAIM_RELEASE_GRACE_MS = 5000;
/**
 * RB-356③ — how often (per store instance) an acquisition also SWEEPS the claims directory. The header's
 * "the TTL reaps any orphan" was an aspiration, not a mechanism: nothing ever reaped anything. An expired
 * claim was only removed if a LATER resume off the SAME `(sourceRunId, scope)` came along to take it over —
 * and the normal shape is exactly one resume per source run, so a crash (or any release that could not
 * complete) leaked one small file per source run for the lifetime of the data root. The sweep makes the
 * comment true. Throttled because it is a `readdir` on the claims directory: it is opportunistic hygiene, not
 * a correctness path (takeover, not the sweep, is what unblocks a contended claim promptly).
 */
export declare const RESUME_CLAIM_SWEEP_INTERVAL_MS = 60000;
/**
 * RB-356③ — the sweep only reaps a claim that has been expired for at least this long. A just-expired claim
 * is the exclusive business of whoever is taking it over right now; the sweep has no deadline to meet, so it
 * stays well clear of that handover rather than adding a second unlinker to it.
 */
export declare const RESUME_CLAIM_REAP_GRACE_MS: number;
export interface FileWorkflowJournalStoreOptions {
    /** Disclosure seat for a ledger line that is not one of the run's records (not JSON, not an object, no `scope` /
     *  `ordinal`, another scope) and — with the refusal, carrying the ledger's path — for whatever refused a `load`; and
     *  (`kind: "file"`, the launch file's path) for a launch file `deleteRun` left because it does not read as a kept record.
     *  Never fires on a missing ledger or on a crash's unterminated tail; swallow-guarded. */
    onCorruptRead?: (info: CorruptReadInfo) => void;
}
export declare class FileWorkflowJournalStore implements WorkflowJournalStore {
    private readonly fsyncEnabled;
    private readonly dir;
    /** RB-242: resume claims live in their own subdirectory so a claim file can never be mistaken for a run
     *  ledger by anything that enumerates `workflow-journal/` (GC, the torn-tail replay, an operator's `ls`). */
    private readonly claimsDir;
    private readonly shared;
    private readonly sharedKey;
    /** The journal's {@link HolderLatch}: {@link dispose} closes it, as does the dispose of the backend that built it. */
    private readonly latch;
    /** RB-356③: last {@link sweepExpiredClaims} timestamp — throttles the reap to one `readdir` per interval.
     *  Per INSTANCE, not per directory: the sweep is idempotent hygiene, so a second instance doing its own
     *  first sweep is harmless (unlike the fd/scope caches above, which are authority over the directory). */
    private lastClaimSweepAt;
    /** RB-61: one AppendLog per run (torn-tail truncation at open) — replaces the raw fd map. */
    private get logs();
    /** Per-run committed scope, cached at first touch — the append-path scope guard must NOT re-read the whole
     *  ledger per append (a journaled result can be MBs; a many-agent workflow would go O(n²) on disk). One replay
     *  discovers it; every later append compares against the cache. */
    private get scopes();
    /** The swallow-guarded corrupt-read seat (undefined = the old silent tolerance). */
    private readonly discloseCorrupt;
    constructor(root: string, fsyncEnabled?: boolean, options?: FileWorkflowJournalStoreOptions);
    private pathFor;
    /** CC local form: the run's on-disk journal path for the notification diagnostics line.
     *  Traversal-shaped ids (LLM-controlled on some paths) degrade to undefined, never throw. */
    locator(runId: string): string | undefined;
    /** Replay a run's ledger: last-writer-wins per ordinal, with every line that is not one of the run's records
     *  (`notRecords`) and the scope the first record fixes. Rows come back as written — which arm each one is, and
     *  whether anything refuses, is {@link load}'s question, so the scope lookup `append` makes refuses on nothing. */
    private replay;
    /** A run's launch record: `<dir>/launches/<runId>.json` holding `{ scope, launch }`. Throws on a traversal-shaped id. */
    private launchPathFor;
    /** The kept `{ scope, launch }` of `runId` (the launch as stored, read by the caller), `undefined` (no such file, a traversal-shaped
     *  id), or `"unreadable"` — a file that is there but does not parse, or names no scope. A file that could not be read for any other
     *  reason (permissions, the disk) THROWS that fault: it is neither an absence (a continuation would seat the run on today's settings
     *  in its place) nor a record that reads back wrong — the store's other reads throw a real I/O failure the same way. */
    private readLaunch;
    /** Write once ({@link WorkflowJournalStore.recordLaunch}): published with one atomic link, so the file never exists half
     *  written; a second record for the id (EEXIST) is the same record again (nothing changes) or a conflict (refused, the
     *  first kept). The size rule is the journal's own, judged before the medium is touched. */
    recordLaunch(runId: string, scope: string, launch: WorkflowLaunchRecord): Promise<void>;
    loadLaunch(runId: string, scope: string): Promise<WorkflowLaunchRecord | undefined>;
    /** Erase the run's ledger file when its first record's scope is `scope`, and its launch record when that is kept under `scope`
     *  (interface: {@link WorkflowJournalStore.deleteRun}). A ledger no record attributes to a scope is not erased (nothing says it is
     *  this caller's). The run's open append log is closed first, so the next append to the id starts a new ledger. A traversal-shaped
     *  id has no ledger here: `false`. The two files are erased each on its own: a fault on one (a launch file that cannot be read,
     *  say) never keeps the other, and is thrown once both have been tried. */
    deleteRun(runId: string, scope: string): Promise<boolean>;
    /** {@link deleteRun}'s launch half: erased when kept under `scope`; a file the disk will not read throws (it may be the caller's).
     *  A file that is there but does not read as a kept record names no scope, so whose it is cannot be told: it is left as stored and
     *  told to `onCorruptRead` with its path (#5127 — what deleting it should do is that ticket's). */
    private eraseLaunch;
    /** {@link deleteRun}'s ledger half: erased when its first record's scope is `scope`. */
    private eraseLedger;
    append(runId: string, scope: string, entry: WorkflowJournalEntry): Promise<void>;
    /** The run's entries, ascending by ordinal, each winning line read through {@link readWorkflowJournalEntry}. A
     *  ledger line that is not one of the run's records, or a corrupt row, REFUSES the whole load: dropped, what it
     *  held would look never journaled and a resume would run it again. Only the unterminated tail a crash leaves is
     *  uncommitted. The location goes to `onCorruptRead`, not into the message; a superseded line is not read. */
    load(runId: string, scope: string): Promise<WorkflowJournalEntry[]>;
    /**
     * RB-242 — the claim file for `(sourceRunId, scope)`. Keyed by BOTH: a cross-scope caller already
     * resolves to an empty journal (it cannot fork anything), so letting it share one claim key would only hand
     * any tenant a denial-of-resume lever over another's runs. The scope is folded in as a digest rather than
     * a sanitized literal so two distinct scopes can never collapse onto one filename by sanitization.
     * The run id is the name when it is a path segment with no capital letter (`sanitizePathComponent` takes it — every id the engine
     * mints); any other key — one a volume that folds case would file under another key's name (`Run-A` and `run-a`), or an older tree's
     * root a host named with `:` or a space — is named by its digest behind a `%`, a character no path segment holds, so the two forms
     * never meet, no two keys share a file on any volume, and every key is a claim the store records: the store keys by the id verbatim.
     * A key that is not a string is refused before any of that, loudly and without being read: the digest names a STRING's key, and a
     * value that is no string (a boxed `"run-1"`, a number, a record) would otherwise be digested as its JSON text into a claim of its
     * own — not the claim its string holds, which a release then fails to find and an acquire is granted beside.
     */
    private claimPathFor;
    /**
     * Read a claim file ONCE ({@link ClaimFile}): `undefined` when there is no file — nothing was judged, so nothing may be removed on
     * the strength of this read; otherwise the exact bytes, and the claim they hold when they hold one (a truncated / malformed record
     * holds none: takeable). A path that is there and cannot be read (a directory stands there, no permission, an I/O error) throws: a
     * store failure, never read as "no claim" nor as somebody's.
     *
     * RB-356② — the raw bytes are the record's identity token. POSIX has no compare-and-delete, so the only way
     * this store can check "the file I decided about is still the file on disk" immediately before removing one
     * is to re-read and compare, under the claim's removal gate (see {@link removeIfUnchanged}). Since RB-354 a claim is published whole, so
     * "unparsable" no longer includes "a peer is mid-acquire" — it means external truncation/corruption, which
     * genuinely is not a live claim.
     */
    private readClaimAt;
    /**
     * Remove a claim ONLY if the bytes on disk are still `judged` — the ones the decision to remove it was made on — and only while
     * holding that claim's removal gate: an exclusively published lock named after the claim file and those bytes ({@link gateAt}).
     * The one way any claim file is removed: a takeover, the sweep and a holder's own release all come here.
     *
     * The compare and the unlink are two syscalls; without the gate a remover paused between them would delete the claim a faster
     * remover had just published in place of the same bytes (both then granted). Every remover of one claim judges the same bytes
     * and so contends for the same gate, and the gate is keyed by the bytes rather than one fixed name so a remover that died holding
     * it leaves a gate no later claim is named by. A gate leaves the directory only through its own mechanism — handed back by the
     * removal holding it, or reclaimed (by the next remover of the same bytes, or by the sweep) once its holder is proven gone, or,
     * a holder this host cannot judge, once the gate has stood longer than a claim's lease — never on a look at its age alone.
     * `"contended"`: another process holds the gate (it is removing this claim now); `"done"`: removed, or those bytes are no longer
     * there.
     *
     * A gate that cannot be had at all — it cannot be created (a full volume, no descriptor left), or what stands there is no lock
     * record — is thrown: a store fault, never a guess. Except for `holder`: the holder giving back its own claim while the claim
     * still binds ({@link releaseResumeClaim}). Nobody else removes a claim that binds, so that one compare and unlink need no gate,
     * and a release that could not create one must not leave the claim standing for its lease.
     */
    private removeIfUnchanged;
    /**
     * Atomically replace a claim file IN PLACE with `payload` ONLY if the bytes on disk are still `judged`, under the same
     * removal gate {@link removeIfUnchanged} uses. Unlike unlink + link, `rename` leaves no empty-file window where a concurrent
     * `resumeClaim` could acquire the slot while arm (c)'s local holder is still running before cancel.
     */
    private replaceIfUnchanged;
    /**
     * The removal gate of the claim at `path` judged as `judged` — or, given a gate file's own path, that gate. Its name is a fixed
     * length (a digest of the claim file's name and the bytes, `<digest>.takeover`), never the claim's name with more appended: a
     * claim whose name fits must have a gate whose name, and whose publish temp, fit too. A holder this host cannot judge is reclaimed
     * once the gate has stood longer than a claim's lease (the lock's `reclaimUnjudgedAfterMs`): a gate is held for one
     * compare and one unlink, and one refused for good would refuse the claim's takeover for good.
     */
    private gateAt;
    /**
     * RB-356③ — reap what nobody can be holding any more (see {@link RESUME_CLAIM_SWEEP_INTERVAL_MS}). The claims directory holds
     * three kinds of file, told apart by name, and each is removed only the way it is removed everywhere else:
     *  - a claim (`….json`): judged on one read and removed through {@link removeIfUnchanged} — an expired one past the reap grace,
     *    or bytes that are no claim at all (external damage — this store never writes one) once left for the TTL;
     *  - a publish temp (`….tmp`, {@link writeThenLink}'s scratch, of a claim or of a gate): aged out on the TTL horizon — one
     *    belonging to an in-flight publish is seconds old, and removing a stranded one can only fail its own publish, loudly;
     *  - a removal gate (any other name: `<digest>.takeover`, and the reclaim gates nested in one): only through its own
     *    mechanism ({@link gateAt}) — taken and handed straight back, which removes a gate whose holder is proven gone (or, one this
     *    host cannot judge, whose gate has stood past a claim's lease) and leaves one whose holder runs. Never on a look at its age
     *    alone: the gate that look was about may since have been reclaimed by a live remover, and removing that one lets a second
     *    remover in — the mechanism's reclaim re-reads the holder under its own gate first.
     * Best-effort throughout: a sweep failure must never turn an admission into an error.
     */
    private sweepExpiredClaims;
    /**
     * RB-242 — admission for a resume off `sourceRunId`. The LOCAL (TOC) twin of the SQL-backed
     * `idem_key UNIQUE` + TTL: publishing the claim file is one atomic namespace operation that fails EEXIST
     * against anyone who got there first, so two processes racing on the same box (the shape the in-process
     * `startWorkflow` guards cannot see — a shell restart resuming a run a still-live process is already
     * resuming) produce exactly one winner.
     *
     * Every key is recorded ({@link claimPathFor}): a grant is a claim on disk, and a claim that cannot be recorded (the directory
     * cannot be made, the publish fails, the claim path is there and cannot be read, the removal gate cannot be had) throws — a
     * store failure, never a grant. Both answers say how long the claim has left by this process's clock when the answer is made
     * (`resumeClaimRemainingMember`: none when it cannot be said); a re-claim by its holder does not renew the lease, and answers
     * what is left of it.
     */
    resumeClaim(input: ResumeClaimArgs): Promise<ResumeClaimAnswer>;
    /** RB-242 — release ONLY a claim this `newRunId` still holds in this process ({@link heldHere}). A claim that is already gone
     *  (TTL-reaped and possibly taken over), a tombstone, or one the same run id holds from another process, is a no-op: unlinking
     *  a successor's claim would re-open the very fork this prevents. */
    releaseResumeClaim(input: ResumeClaimArgs): Promise<void>;
    /**
     * #5156 R1 — compare-and-write a permanent stop tombstone on `(sourceRunId, scope)`.
     * Writes no `holderProcess` and sets finite `expiresAt = Number.MAX_SAFE_INTEGER` (never `Infinity`, which serializes to
     * `null`), so pre-tombstone (v7.71.x) readers also refuse, never take over and never reap the tombstone. Arms (b) and (c)
     * replace the existing claim atomically in place under its removal gate, dropping any old `holderProcess` with no empty window.
     */
    stopResumeClaim(input: StopResumeClaimArgs): Promise<StopResumeClaimAnswer>;
    /** Release ledger fds (graceful shutdown; parity with the other file stores' dispose).
     *  Refcounted: the fds are shared with any other instance on the same directory, so the LAST holder
     *  closes them. Idempotent — a second dispose() on the same instance must not decrement twice and pull
     *  the ledger out from under a live peer. */
    dispose(): void;
}
