import { type MailboxPeerMeta, type MailboxDecisionOutcome, type MailboxDecision } from "../core/mailbox-store.js";
import type { CrossSessionHoldCause, CrossSessionInboundVerdict } from "./cross-session-judge.js";
import { type PeerDeliveryReceiptState, type PeerReleaseCause } from "./peer-notices.js";
/** The `cause` vocabulary of a `peer.inbound_disposition{disposition:"held"}` notice: the parity
 *  judge's causes plus the drain-stage gate's TRANSIENT `rate_limited` (a bucket-wait, not a review
 *  hold — it never enters the held queue; the drain stops at that seq and re-judges next pass). */
export type PeerInboundHoldCause = CrossSessionHoldCause | "rate_limited";
/** The decisions a card can stand for: held, approved, or handed over but not yet injected. */
export type PeerCardDecision = Extract<MailboxDecision, "held" | "approved" | "delivered">;
export interface PeerHeldEntry {
    /** The recipient box seq of the held record (its identity for the review face). */
    readonly seq: number;
    /** The recipient's box handle. */
    readonly box: string;
    /** The stored body (`[summary] message`, the canonical stored form). */
    readonly content: string;
    /** The sender's display name as the record carried it (display only). */
    readonly from?: string;
    readonly sentAt: number;
    readonly hopChain?: readonly string[];
    /** The typed record — reply routing (`fromSession`) and the attestation the re-judgment reads. */
    readonly peerMeta?: MailboxPeerMeta;
    readonly heldAt: number;
    /** The cause last announced for this entry (re-judgment may move it). */
    cause: CrossSessionHoldCause;
    /** The record's decision as this queue last read or wrote it: `held`; `approved` (deliverable,
     *  waiting for a lease-holding pass — a re-judgment that now refuses still wins); `delivered` (this
     *  queue took the hand-over move and the injection is still owed; a policy that now refuses ends it as `dropped`). */
    decision: PeerCardDecision;
    /** When this hold resolves to `expired` unless someone answers it first (ms epoch) — present exactly while
     *  its expiry timer is armed: a cause in `PEER_HELD_REVIEW_CAUSES`, a finite `dialogExpiry`, the card still
     *  `held`. A cause move re-arms or clears it; an approval, a hand-over, the deadline itself or the card leaving clears it. */
    deadlineAt?: number;
}
/** How an entry left this queue. `retired` — the CARD left this process but no decision was taken: the
 *  record stays held in its box for the next consumer (a queue-local event no receipt announced,
 *  or a record another consumer settled). Every other word is the record's own final fate. */
export type PeerHeldSettlement = "expired" | "delivered" | "refused" | "denied" | "dropped" | "retired";
export type PeerHeldSettleReason = "evicted" | "deadline" | "shutdown" | "rejudge" | "approved" | "denied" | "cancelled" | "inject_failed" | "superseded" | "decided_elsewhere";
/** The clock/timer seam (tests inject a virtual one). Handles are opaque. */
export interface PeerClock {
    now(): number;
    setTimeout(fn: () => void, ms: number): unknown;
    clearTimeout(handle: unknown): void;
}
export declare const realPeerClock: PeerClock;
/** The clock a seat (a held queue, an idle half) arms its timers on: `clock`, with every timer armed outside any run. A timer
 *  keeps the async context it was armed in until it fires or is cleared, and with it the stores of the run whose code armed it
 *  (the run's whole state); a seat outlives every run (an idle ask waits 12 h), so its timers are armed, and fire, outside any. */
export declare function peerSeatClock(clock?: PeerClock): PeerClock;
/** The live seats a bound run gives the queue. `inject` is the ONLY member that is run-scoped (a run's
 *  own injection lane); the others survive the run (the receipt route rides the mailbox, the judge
 *  reads the deployment's settings getter, the decision seat is the store) and are what a headless
 *  deadline settles through — so what the queue keeps after the run closes over nothing of it (the
 *  queue is process-lived: the session-box drain hands its sinks through the run's end). */
export interface PeerHeldQueueSink {
    /** Re-judge an entry against the recipient's CURRENT settings and mode class (CC `M`). */
    judge: (entry: PeerHeldEntry) => CrossSessionInboundVerdict;
    /** Deliver a deliverable entry into the live run's model context. Absent ⇒ no run is live. Throws ⇒
     *  the lane refused the frame. Returns `"deferred"` ⇒ the run is live but this pass's delivery budget
     *  is spent: the entry stays deliverable and goes at the next pass's flush (unless the policy refuses it first).
     *  May answer a promise (awaited): a sink that must record something durably before the frame goes out (the
     *  session's external-content exposure) answers once that is done, `"deferred"` when it could not be. */
    inject?: (entry: PeerHeldEntry) => void | "deferred" | Promise<void | "deferred">;
    /** Would {@link inject} take this entry NOW (a live pass that holds this box's lease, with budget left)?
     *  Asked BEFORE the hand-over move (and before a refusal ends a handed-over card), so a process that cannot
     *  deliver never takes a move out of `delivered`. Absent ⇒
     *  the presence of `inject` decides. */
    canInject?: (entry: PeerHeldEntry) => boolean;
    /** The receipt to the sender (the binding routes it into the sender's box). Resolves once the receipt is in
     *  that box (or has no reader there); rejects when it could not be written. Only {@link PeerHeldQueue.shutdown}
     *  waits on it — every other path sends and goes on. */
    receipt: (entry: PeerHeldEntry, state: PeerDeliveryReceiptState, releasedBy?: PeerReleaseCause) => Promise<void>;
    /** Does a receipt about this entry reach a sender? A queue-local event (eviction, shutdown, a refused
     *  release) is a decision about the record exactly when it does — the sender is told it is final. */
    tellsSender: (entry: PeerHeldEntry) => boolean;
    /** THE decision seat: the store's compare-and-set of this entry's record (`MailboxStore.moveDecision`). The seat names the lease
     *  owner its consumer claims the box with, so the store refuses an edge out of `delivered` once the box's lease is another's
     *  (answered `delivered`: the card loses the move and the box's holder settles the record). */
    decide: (entry: PeerHeldEntry, expect: MailboxDecision | undefined, next: MailboxDecision) => Promise<MailboxDecisionOutcome>;
    /** Announce an entry entering the queue (or its cause changing on re-judgment). */
    onHeld?: (entry: PeerHeldEntry, heldCount: number, cause: CrossSessionHoldCause, reannounce: boolean) => void;
    /** Announce an entry leaving the queue. `approvedByPerson`: a person approved this card before it left — the settle's own
     *  approval (`reason` `approved`), a card already `approved`, or one a person's approval handed over (`delivered`, released by
     *  `approved`) — so a refusal or a drop it ends in is an approval not honoured. */
    onSettled?: (entry: PeerHeldEntry, settlement: PeerHeldSettlement, reason: PeerHeldSettleReason, heldCount: number, approvedByPerson: boolean) => void;
    /** A decision move the store could not take (it threw): the card stays as it was and is tried again later. */
    onFault?: (entry: PeerHeldEntry, error: unknown) => void;
}
export interface PeerHeldQueueConfig {
    sink: PeerHeldQueueSink;
    /** The resolved `dialogExpiry`: ms before a REVIEW-cause hold expires; `null` = never. */
    dialogExpiryMs: number | null;
}
/** The approval face's answer. `decided_elsewhere` — another consumer's move won the record first (the
 *  card now shows that state, or left the queue when it was final); `released_pending` — approved, and a
 *  lease-holding pass delivers it. */
export type PeerHeldSettleOutcome = "gone" | "delivered" | "released_pending" | "dropped" | "dropped_by_policy" | "denied" | "expired" | "decided_elsewhere";
/** What {@link PeerHeldQueue.hold} did with a record the judgment holds: `held` — this call held it
 *  (card + hold receipt, `held` / `held_by_policy` by its cause); `adopted` — it was already held (or deliverable) and this queue now shows it
 *  without a receipt; `uncarded` — held, but this queue's capacity for unanswered cards is full and no unanswered card it carries can be settled to
 *  make room (none would tell its sender) — the record stays held in its box and shows when a card frees. A record already `approved` or
 *  handed over is never `uncarded`: an answered card needs no room; a final word — another consumer settled it; `gone` —
 *  no such record any more; `fault` — the store refused the move, or answered a decision word outside the card table (either way reported through `onFault`). */
export type PeerHoldOutcome = "held" | "adopted" | "uncarded" | "denied" | "expired" | "refused" | "dropped" | "gone" | "fault";
export interface PeerHeldQueue {
    /** The registry key (scope + box). */
    readonly key: string;
    /** Bind (or re-bind) the live seats. Idempotent per run; a later bind replaces an earlier one. */
    configure(cfg: PeerHeldQueueConfig): void;
    /** The bound run ended: approvals now wait as `approved`; deadlines and receipts keep working. */
    detachLeg(): void;
    /** `true` once {@link configure} ran at least once (the queue can route receipts). */
    configured(): boolean;
    /**
     * Hold a record (CC `v` hold arm). `decision` is the record's decision in the snapshot the caller judged:
     * absent ⇒ the move absent → `held` is taken (its winner sends the hold receipt its cause reads as); `held` / `approved` ⇒
     * the record is already held elsewhere and this queue only shows it (an approved card is not announced).
     * At the cap (of UNANSWERED cards — {@link CARD_CAPACITY}), settles the oldest held card that tells its sender (it is then a
     * decision); an `approved` / handed-over record always gets its card; arms the deadline for a hold cause a person could answer.
     */
    hold(entry: Omit<PeerHeldEntry, "heldAt" | "decision" | "deadlineAt">, decision?: PeerCardDecision): Promise<PeerHoldOutcome>;
    /** Re-judge every entry against current settings (CC `D`): deliverable ⇒ handed over (or kept with no
     *  live run), refused ⇒ refused with a receipt, still held ⇒ re-announced only when the cause moved.
     *  Every move goes through the decision seat. */
    rejudge(): Promise<{
        released: number;
        refused: number;
        held: number;
    }>;
    /**
     * Bring the cards in line with the box a lease-holding drain just read, seq → the record's decision
     * (every unacked record of the box is in it, so absence is absence): a card whose record is gone was
     * settled by whoever held the lease meanwhile — it leaves as `retired` / `superseded`, with no receipt;
     * a card whose record another consumer settled leaves as that final state / `decided_elsewhere`, with no
     * receipt (the winner sent it); a card whose record another consumer approved now shows `approved`.
     * Returns how many cards left.
     */
    reconcile(snapshot: ReadonlyMap<number, MailboxDecision | undefined>): number;
    /** The review face (CC `l0e`): approve re-judges then delivers (or answers `released_pending` with no
     *  live run), deny/cancel settle with the matching receipt. `"gone"` when nothing is held under that
     *  seq. The answer is the store's: a move another consumer won answers `decided_elsewhere`. */
    settle(seq: number, decision: "approve" | "deny" | "cancel"): Promise<PeerHeldSettleOutcome>;
    /** Is a card for this seq in the queue? */
    has(seq: number): boolean;
    list(): readonly PeerHeldEntry[];
    size(): number;
    /** CC `HBe` — a graceful shutdown settles everything still held as `expired` with receipts (where a
     *  receipt reaches a sender; elsewhere the cards just leave this process). Resolves once every receipt it
     *  sent has landed; rejects naming the seqs whose receipt did not (every card is settled either way). */
    shutdown(): Promise<void>;
}
export declare function createPeerHeldQueue(key: string, opts?: {
    cap?: number;
    clock?: PeerClock;
}): PeerHeldQueue;
/** A session's held-queue key: (scope, the session's box) — and, for a queue of ANOTHER box that session
 *  drains (its scope's principal inbox), that box's handle as a third member: the approval face addresses
 *  entries by seq, and seqs are minted per box, so one queue never mixes two boxes. */
export declare function peerHeldQueueKey(scope: string, sessionId: string, box?: string): string;
/** The held queue of a session (created on first use) — of its own box, or of `box` (the principal inbox it
 *  also drains). `clock` is honored only at creation. `occupant` = the occupant of the session the queue is opened for
 *  (`SessionMetadata.incarnation`; absent = the store mints no token): a queue the registry holds for ANOTHER occupant of the id
 *  (`sameOccupant` judges, as everywhere) is replaced, and the old one stops in the crash form — its cards leave this process
 *  with nothing decided and nothing sent, and the records they showed stay in the box, where the new occupant's drain discards
 *  every one addressed to an earlier occupant. So the approval face of a session never shows an earlier occupant's cards, and no
 *  deadline of theirs settles a record under this one. */
export declare function peerHeldQueueFor(scope: string, sessionId: string, opts?: {
    cap?: number;
    clock?: PeerClock;
    box?: string;
    occupant?: string;
}): PeerHeldQueue;
/** The held queue of a session if one exists in this process (a host review face reads through this
 *  without creating state for sessions that never held anything); `box` as in {@link peerHeldQueueFor}. */
export declare function peerHeldQueueIfAny(scope: string, sessionId: string, box?: string): PeerHeldQueue | undefined;
/** One held queue of this process as {@link listPeerHeldQueues} shows it. */
export interface PeerHeldQueueSnapshot {
    readonly scope: string;
    /** The session that opened the queue (the spelling it first used; the key folds case). */
    readonly sessionId: string;
    /** The box its cards come from: the session's own, or the principal inbox it also drains. */
    readonly box: string;
    readonly size: number;
    /** The cards as {@link PeerHeldQueue.list} shows them, at the same moment as `size`. */
    readonly entries: readonly PeerHeldEntry[];
}
/** Every held queue of this process's registry (opened through {@link peerHeldQueueFor}, as every drain opens its
 *  queues; a bare {@link createPeerHeldQueue} is not in it), as a read-only snapshot that opens none: a host approval face lists
 *  the held cards of all its sessions without keeping its own table of (session, box) coordinates. A row's
 *  (scope, sessionId, box) handed to {@link peerHeldQueueIfAny} reaches that queue for its settle face. */
export declare function listPeerHeldQueues(): readonly PeerHeldQueueSnapshot[];
/** Test seam: drop every queue (timers cleared, NO receipts — the crash form). Never called by production code. */
export declare function resetPeerHeldQueuesForTests(): void;
