import type { AssertAllKeysHandled } from "./ask-origin.js";
import { type A2APeerStateReading, type A2AStateClass, type A2ATaskState, type A2AWaitingFor } from "./a2a-task-state.js";
import { type RekeyConflict, type RekeyDone, type RekeyMode, type RekeyPlan, type ScopeRekeyInput } from "./identity-rekey.js";
import type { AskDestination } from "./mcp-server-spec.js";
import { type MemberKind, type MemberOutcome, type MemberRefusals } from "./member-outcome.js";
import { PEER_TASK_CANCEL_STATES, PEER_TASK_CLOCK_STATES, PEER_TASK_FOLLOW_UPS, PEER_TASK_REMINDER_DISPOSITIONS, PEER_TASK_REMINDER_ROUTES, PEER_TASK_REMINDER_TARGETS, type PeerTaskCancelState, type PeerTaskClockState, type PeerTaskFollowUps, type PeerTaskReminderDisposition, type PeerTaskReminderRoute, type PeerTaskReminderTarget } from "./task-notification.js";
import { type DamagedRowVerdict, type RowContext } from "./row-shape.js";
/** Monotone submission states: recorded before send, sent_unconfirmed before wire dispatch, accepted after peer receipt. */
export declare const PEER_TASK_DELIVERY_STATES: readonly ["recorded", "sent_unconfirmed", "accepted"];
export type PeerTaskDeliveryState = (typeof PEER_TASK_DELIVERY_STATES)[number];
/** Monotone rank table for {@link PeerTaskDeliveryState}; updates may keep or raise the rank and never lower it. */
export declare const PEER_TASK_DELIVERY_RANK: Readonly<{
    readonly recorded: 0;
    readonly sent_unconfirmed: 1;
    readonly accepted: 2;
}>;
export type PeerTaskDeliveryRankCoversEveryState = AssertAllKeysHandled<Exclude<PeerTaskDeliveryState, keyof typeof PEER_TASK_DELIVERY_RANK>>;
/** The words a stored row shares with the `peer_task` notification facade (`TaskNotificationPayload.peerTask`) are that facade's
 *  sets, one each, minted in `task-notification.ts`; a reminder's `routedTo` reads {@link PEER_TASK_REMINDER_ROUTES}. */
export { PEER_TASK_CANCEL_STATES, PEER_TASK_CLOCK_STATES, PEER_TASK_FOLLOW_UPS, PEER_TASK_REMINDER_DISPOSITIONS, PEER_TASK_REMINDER_ROUTES, PEER_TASK_REMINDER_TARGETS, type PeerTaskCancelState, type PeerTaskClockState, type PeerTaskFollowUps, type PeerTaskReminderDisposition, type PeerTaskReminderRoute, type PeerTaskReminderTarget, };
export declare const PEER_TASK_FALLBACKS: readonly ["proceed_without", "substitute_local", "stop_and_report"];
export type PeerTaskFallback = (typeof PEER_TASK_FALLBACKS)[number];
export declare const PEER_TASK_RESCHEDULE_ACTORS: readonly ["peer", "caller"];
export type PeerTaskRescheduleActor = (typeof PEER_TASK_RESCHEDULE_ACTORS)[number];
export declare const PEER_TASK_LIVE_STATUSES: readonly ["running"];
export type PeerTaskLiveStatus = (typeof PEER_TASK_LIVE_STATUSES)[number];
export declare const PEER_TASK_SETTLED_STATUSES: readonly ["completed", "failed", "killed", "cancelled"];
export type PeerTaskSettledStatus = (typeof PEER_TASK_SETTLED_STATUSES)[number];
export declare const PEER_TASK_STATUSES: readonly ["running", "completed", "failed", "killed", "cancelled"];
export type PeerTaskStatus = (typeof PEER_TASK_STATUSES)[number];
/** Whether `status` is a live peer-task status (`running`). */
export declare function isPeerTaskLiveStatus(status: unknown): status is PeerTaskLiveStatus;
/** Whether `status` is a settled peer-task status (`completed`, `failed`, `killed`, or `cancelled`). */
export declare function isPeerTaskSettledStatus(status: unknown): status is PeerTaskSettledStatus;
/**
 * Clock-free unsettled predicate shared by `listUnsettled`, `reap` and the restart settle (peer-task-lane.ts; `deleteBySession` takes
 * a row whatever it reads):
 * true while a row is running or while a settled row still holds an open overdue-observation tail.
 */
export declare function isPeerTaskUnsettled(row: {
    readonly status: unknown;
    readonly overdueTail?: unknown;
}): boolean;
export declare const PEER_TASK_ALREADY_EXISTS_CODE = "peer_task.already_exists";
export declare const PEER_TASK_ROW_MALFORMED_CODE = "peer_task.row_malformed";
export declare const PEER_TASK_DELIVERY_REGRESSION_CODE = "peer_task.delivery_regression";
export declare const PEER_TASK_STORE_ERROR_CODES: readonly ["peer_task.already_exists", "peer_task.row_malformed", "peer_task.delivery_regression"];
export type PeerTaskStoreErrorCode = (typeof PEER_TASK_STORE_ERROR_CODES)[number];
/** Typed error raised across {@link PeerTaskStore} implementations so callers branch on `code`. */
export declare class PeerTaskStoreError extends Error {
    readonly code: PeerTaskStoreErrorCode;
    constructor(code: PeerTaskStoreErrorCode, message: string);
}
/** Compute the 64-character lowercase SHA-256 hex digest of a serialized JSON-RPC `paramsJson` payload. */
export declare function peerTaskRequestDigest(paramsJson: string): string;
/** Re-playable JSON-RPC `params` payload, persisted verbatim so retries send identical bytes. */
export interface PeerTaskRequestRecord {
    readonly paramsJson: string;
}
/** Last observed remote peer task state; absent until the peer answers at least once. */
export interface PeerTaskRemoteState {
    taskId?: string;
    contextId?: string;
    state?: A2ATaskState;
    stateClass?: A2AStateClass;
    waitingOn?: A2APeerStateReading["waitingOn"];
    clock?: PeerTaskClockState;
    stateChangedAt?: number;
}
export interface PeerTaskReschedule {
    readonly by: PeerTaskRescheduleActor;
    readonly at: number;
    readonly from: number;
    readonly to: number;
    readonly why: string;
}
export interface PeerTaskReminder {
    readonly n: number;
    readonly dueAt: number;
    readonly target: PeerTaskReminderTarget;
    readonly disposition: PeerTaskReminderDisposition;
    readonly routedTo?: PeerTaskReminderRoute;
    readonly seq: number;
}
export interface PeerTaskOverdueTail {
    readonly until: number;
}
/** Peer-task ending record; widens `kind` with `"peer_task"` so it collapses into `MemberOutcome` cleanly. */
export type PeerTaskOutcome = Omit<MemberOutcome, "kind"> & {
    readonly kind: MemberKind | "peer_task";
};
/** Durable submission record and lifecycle row for one peer task (`p…` handle). */
export interface PeerTaskRow {
    task_id: string;
    scope: string;
    rev: number;
    owner: string;
    sessionScoped: boolean;
    parentSessionId?: string;
    rootSessionId?: string;
    rootSessionIncarnation?: string;
    rootSessionScope?: string;
    parentTaskId?: string;
    writerId?: string;
    type: "peer_task";
    destination: AskDestination;
    skillId: string;
    peerFingerprint?: string;
    planItem?: string;
    messageId: string;
    request: PeerTaskRequestRecord;
    requestDigest: string;
    submittedAt: number;
    settledAt?: number;
    delivery: PeerTaskDeliveryState;
    remote?: PeerTaskRemoteState;
    waitingFor?: A2AWaitingFor;
    followUps: PeerTaskFollowUps;
    cancel: PeerTaskCancelState;
    ackBy: number;
    finalBy: number;
    approvalWaitMs: number;
    peerFinalBy?: number;
    approvalBy?: number;
    fallback: PeerTaskFallback;
    reschedules?: readonly PeerTaskReschedule[];
    reminders?: readonly PeerTaskReminder[];
    lastSeq: number;
    status: PeerTaskStatus;
    outcome?: PeerTaskOutcome;
    remoteMayContinue?: true;
    overdueTail?: PeerTaskOverdueTail;
}
/** Content-free listing projection: readable summary, or damaged row identity and verdict (`"rowVerdict" in summary`). */
export type PeerTaskRowSummary = ReadablePeerTaskRowSummary | DamagedPeerTaskRowSummary;
export interface DamagedPeerTaskRowSummary {
    readonly rowVerdict: DamagedRowVerdict;
    readonly task_id: string;
}
export interface ReadablePeerTaskRowSummary {
    task_id: string;
    scope: string;
    rev: number;
    owner: string;
    sessionScoped: boolean;
    parentSessionId?: string;
    rootSessionId?: string;
    rootSessionIncarnation?: string;
    rootSessionScope?: string;
    parentTaskId?: string;
    type: "peer_task";
    destination: AskDestination;
    skillId: string;
    peerFingerprint?: string;
    planItem?: string;
    messageId: string;
    requestDigest: string;
    submittedAt: number;
    settledAt?: number;
    delivery: PeerTaskDeliveryState;
    waitingFor?: A2AWaitingFor;
    followUps: PeerTaskFollowUps;
    cancel: PeerTaskCancelState;
    ackBy: number;
    finalBy: number;
    approvalWaitMs: number;
    peerFinalBy?: number;
    approvalBy?: number;
    fallback: PeerTaskFallback;
    lastSeq: number;
    status: PeerTaskStatus;
    remoteMayContinue?: true;
    overdueTail?: PeerTaskOverdueTail;
    refused?: MemberRefusals;
}
export interface PeerTaskUpdateIfExpect {
    rev: number;
    delivery?: PeerTaskDeliveryState;
    status?: PeerTaskStatus;
    cancel?: PeerTaskCancelState;
}
export interface PeerTaskListOptions {
    status?: PeerTaskStatus;
    limit?: number;
}
export interface PeerTaskReapOptions {
    maxAgeMs?: number;
    keep?: number;
}
export declare const PEER_TASK_REAP_KNOBS: readonly ["maxAgeMs", "keep"];
export declare function receivePeerTaskReapOptions(opts: PeerTaskReapOptions | undefined): Readonly<PeerTaskReapOptions>;
/**
 * Handle shape for peer-task rows (`p` followed by 16 lowercase hex digits, matching `TaskRegistry.mintTaskId`).
 * Defined here while the task-registry prefix table on this base does not yet carry `peer_task`.
 */
export declare const PEER_TASK_HANDLE_RE: RegExp;
/** Refuse an off-shape or NUL-bearing peer-task handle loudly with `config.invalid_argument`. */
export declare function assertPeerTaskId(taskId: unknown, entry: string): asserts taskId is string;
/** Refuse an empty, non-string, or NUL-bearing tenant scope loudly with `config.invalid_argument`. */
export declare function assertPeerTaskScope(scope: unknown, entry: string): asserts scope is string;
/** Refuse an empty, non-string, or NUL-bearing session id loudly with `config.invalid_argument`. */
export declare function assertPeerTaskSessionId(sessionId: unknown, entry: string): asserts sessionId is string;
/** Validate list options loudly by name (`status`, `limit`, stray keys) with `config.invalid_argument`. */
export declare function readPeerTaskListOptions(entry: string, opts: PeerTaskListOptions | undefined): Readonly<PeerTaskListOptions>;
/** Check `now` loudly before any retention calculation runs. */
export declare function assertPeerTaskReapNow(now: unknown): asserts now is number;
/** Access predicate over flat ownership fields; delegates directly to {@link canAccessAgentRecord}. */
export declare function canAccessPeerTaskRecord(record: Pick<PeerTaskRow, "scope" | "owner" | "sessionScoped" | "parentSessionId" | "rootSessionId" | "rootSessionIncarnation">, access: {
    owner?: string;
    scope?: string;
    sessionId?: string;
    rootSessionIncarnation?: string;
}): boolean;
/** Member-shape table for {@link PeerTaskRow}; shared by read, listing, and write-gate paths. */
export declare const PEER_TASK_ROW_SHAPE: import("./row-shape.js").RowShapeReader<PeerTaskRow>;
/** Read and validate a stored row, disclosing and throwing {@link PEER_TASK_ROW_MALFORMED_CODE} if damaged. */
export declare function readStoredPeerTask(raw: unknown, ctx: RowContext, disclose?: (sentence: string) => void): PeerTaskRow;
/** Validate a candidate row at the write gate before storing it. */
export declare function admitPeerTask(candidate: PeerTaskRow, ctx: RowContext): PeerTaskRow;
/** Project one stored row into a content-free summary or a damaged summary verdict. */
export declare function summarizeStoredPeerTask(raw: unknown, ctx: RowContext, disclose?: (sentence: string) => void, fallbackTaskId?: string): PeerTaskRowSummary;
interface PeerTaskQueryCut {
    status?: PeerTaskStatus;
    limit?: number;
    unsettledOnly?: boolean;
}
export type PeerTaskQuery = (PeerTaskQueryCut & {
    scope: string;
    sessionId?: string;
    root?: never;
}) | (PeerTaskQueryCut & {
    root: string;
    scope?: never;
    sessionId?: never;
});
/** Pure query projection shared by bundled backends over `[compositeKey, raw]` entries (newest-first by submittedAt). */
export declare function queryPeerTaskEntries(entries: Iterable<readonly [string, unknown]>, query: PeerTaskQuery, disclose?: (sentence: string) => void): PeerTaskRowSummary[];
/** Pure query projection shared by all bundled backends (filter, sort newest-first by submittedAt, slice, summarize). */
export declare function queryPeerTasks(rows: Iterable<PeerTaskRow>, query: PeerTaskQuery, disclose?: (sentence: string) => void): PeerTaskRowSummary[];
/** Select the `task_id` values removable by `deleteBySession`: among the readable rows the session's listing names, every row the
 *  session sent itself (its own anchor — `owner` for a session-scoped row, `parentSessionId` for a task-scoped one — names the session),
 *  in any status, a running row and a settled row with an open overdue tail included (the deletion wins, and nothing is sent to the
 *  peer). A row the listing names only through its delegation root (`rootSessionId`) is never taken: the root id alone does not say
 *  which scope's session it is, so such a row goes with the session that sent it. */
export declare function peerTaskSessionRows(rows: Iterable<PeerTaskRow>, scope: string, sessionId: string, disclose?: (sentence: string) => void): string[];
/** Whether `candidate` preserves every dispatch-time mint-once member of `current`. */
export declare function samePeerTaskMintOnceMembers(current: PeerTaskRow, candidate: PeerTaskRow): boolean;
/** Shared CAS transition judge for `updateIf`: checks guards, stamps key and rev + 1, validates candidate, enforces monotone delivery, preserves mint-once members, and forbids settled->unsettled or settled->other-status moves. */
export declare function nextPeerTaskOnUpdate(live: PeerTaskRow | undefined, key: string, taskId: string, scope: string, row: PeerTaskRow, expect: PeerTaskUpdateIfExpect, disclose?: (sentence: string) => void): PeerTaskRow | null;
export interface PeerTaskReapCandidate {
    readonly key: string;
    readonly submittedAt: number;
    readonly age: number;
}
/** Readable settled rows with no open overdue tail eligible for retention sweeping, newest-first by `submittedAt`. */
export declare function peerTaskReapCandidates(rows: Iterable<readonly [string, PeerTaskRow]>, scope: string, disclose?: (sentence: string) => void): PeerTaskReapCandidate[];
export interface PeerTaskScopeRekeyMove {
    readonly source: PeerTaskRow;
    readonly target: PeerTaskRow | null;
    readonly arrived: boolean;
}
/** Build the arrival copy for `source` under `toScope`, bumping `rev` and moving `rootSessionScope` when it matches `source.scope`. */
export declare function peerTaskScopeRekeyCopyOf(source: PeerTaskRow, toScope: string): PeerTaskRow;
export declare function planPeerTaskScopeRekey(rows: Iterable<PeerTaskRow>, targetOf: (taskId: string) => PeerTaskRow | null, input: ScopeRekeyInput): {
    moves: readonly PeerTaskScopeRekeyMove[];
    answer: RekeyPlan | RekeyDone | RekeyConflict;
};
export declare function readPeerTaskScopeRekeyPlan(stored: ReadonlyMap<string, unknown>, keyOf: (taskId: string, scope: string) => string, input: ScopeRekeyInput, opts?: {
    readonly only?: ReadonlySet<string>;
    readonly disclose?: (sentence: string) => void;
}): ReturnType<typeof planPeerTaskScopeRekey>;
export declare function peerTaskScopeRekeyWritesOf(mode: RekeyMode, plan: ReturnType<typeof planPeerTaskScopeRekey>, toScope: string, keyOf: (taskId: string, scope: string) => string): {
    puts: readonly {
        key: string;
        row: PeerTaskRow;
    }[];
    deletes: readonly {
        key: string;
        rev: number;
    }[];
};
/**
 * Durable submission-record store interface for peer tasks (`p…` handles).
 *
 * Crash-orphaned rows: a row whose writer process is gone stays unsettled in the store until a later leg of the session that sent it
 * runs on a Runner holding the store, which settles it once without asking the peer (peer-task-lane.ts `settleOrphanedPeerRows`);
 * `reap` spares it, and `deleteBySession` deletes it with the session that sent it.
 */
export interface PeerTaskStore {
    /** Create-once insert requiring `rev === 0`; throws `peer_task.already_exists` if `(task_id, scope)` already exists. */
    put(row: PeerTaskRow): Promise<void>;
    /** Fetch one row by `(taskId, scope)` through {@link PEER_TASK_ROW_SHAPE}, or `null` when absent. */
    get(taskId: string, scope: string): Promise<PeerTaskRow | null>;
    /** Guarded CAS matching `rev` plus any supplied `delivery`/`status`/`cancel`; bumps `rev` by 1 and rejects delivery regressions. */
    updateIf(taskId: string, scope: string, row: PeerTaskRow, expect: PeerTaskUpdateIfExpect): Promise<boolean>;
    /** List running rows, settled rows with an open `overdueTail`, and damaged rows in `scope` for restart recovery. */
    listUnsettled(scope: string, opts?: PeerTaskListOptions): Promise<PeerTaskRowSummary[]>;
    /** List rows in `scope` anchored to `sessionId` by `(sessionScoped ? owner : parentSessionId)` or `rootSessionId`, newest-first. */
    listBySession(scope: string, sessionId: string, opts?: PeerTaskListOptions): Promise<PeerTaskRowSummary[]>;
    /** List all rows in `scope`, newest-first, content-free. */
    listByScope(scope: string, opts?: PeerTaskListOptions): Promise<PeerTaskRowSummary[]>;
    /** List every row across scopes whose delegation root equals `rootSessionId` (validated by {@link assertDelegationRoot}). */
    listByRoot(rootSessionId: string, opts?: PeerTaskListOptions): Promise<PeerTaskRowSummary[]>;
    /** Row-precise removal, rev-conditional when `expect` is provided; unconditional deletion also removes damaged rows. */
    delete(taskId: string, scope: string, expect?: {
        rev: number;
    }): Promise<boolean>;
    /** Optional log-compaction hook finishing a batch of `delete` calls on append-log backends. */
    settleErasure?(): Promise<void>;
    /** Delete the readable rows of `scope` whose own anchor (`sessionScoped ? owner : parentSessionId`) names `sessionId`, in any status
     *  (running and open-tail rows included); a row named only through `rootSessionId` is left; returns deleted `task_id`s. */
    deleteBySession(scope: string, sessionId: string): Promise<string[]>;
    /** Optional enumeration of scopes currently holding at least one row, sorted and deduplicated. */
    listScopes?(): Promise<string[]>;
    /** Explicit retention sweep over settled closed rows in `scope` (`maxAgeMs` / `keep`); spares unsettled and damaged rows. */
    reap(scope: string, now: number, opts?: PeerTaskReapOptions): Promise<number>;
    /**
     * Re-file peer-task rows between tenant scopes in the four {@link REKEY_MODES} steps.
     *
     * @contract peer_task.rekey_scope — `PeerTaskStore.rekeyScope({ fromScope, toScope, mode })` moves every peer-task
     * row filed under `(task_id, fromScope)` to `(task_id, toScope)`. `arrive` writes a cloned row with `scope: toScope`,
     * `rev + 1`, and `rootSessionScope` updated when it matched `fromScope`, keeping `request`, `requestDigest`, and
     * `delivery` intact; an occupied target counts as arrived iff it matches that clone verbatim, else `arrive` returns
     * `conflict` with zero writes. `leave` deletes rev-matched sources whose arrival stands; `withdraw` deletes rev-matched
     * arrivals and leaves sources intact. Every inspected source and target passes {@link readStoredPeerTask} first, so any
     * damaged row fails the entire step in {@link PEER_TASK_ROW_MALFORMED_CODE} before writing.
     */
    rekeyScope(input: ScopeRekeyInput & {
        readonly mode: "plan";
    }): Promise<RekeyPlan>;
    rekeyScope(input: ScopeRekeyInput & {
        readonly mode: "arrive";
    }): Promise<RekeyDone | RekeyConflict>;
    rekeyScope(input: ScopeRekeyInput & {
        readonly mode: "leave" | "withdraw";
    }): Promise<RekeyDone>;
}
/**
 * Admit a `put` candidate. The caller's row is read once, into a detached copy; the key, the admission (`rev === 0` loudly,
 * then the full row contract) and the stored body all come from that copy, so a key and a body never disagree.
 */
export declare function admitNewPeerTask(row: PeerTaskRow, keyOf: (taskId: string, scope: string) => string): {
    readonly key: string;
    readonly row: PeerTaskRow;
};
/** The `RunnerDeps.peerTaskStore` seat, judged at `new Runner`: absent, or an object carrying every member the engine calls as a
 *  function — anything else is refused (`config.invalid_argument`) rather than mounted as a store that fails at the first call. */
export declare function assertPeerTaskStoreSeat(value: unknown, field: string): void;
/** Process-local reference implementation of {@link PeerTaskStore} with detached-copy boundaries. */
export declare class InMemoryPeerTaskStore implements PeerTaskStore {
    private rows;
    private key;
    put(row: PeerTaskRow): Promise<void>;
    get(taskId: string, scope: string): Promise<PeerTaskRow | null>;
    updateIf(taskId: string, scope: string, row: PeerTaskRow, expect: PeerTaskUpdateIfExpect): Promise<boolean>;
    listUnsettled(scope: string, opts?: PeerTaskListOptions): Promise<PeerTaskRowSummary[]>;
    listBySession(scope: string, sessionId: string, opts?: PeerTaskListOptions): Promise<PeerTaskRowSummary[]>;
    listByScope(scope: string, opts?: PeerTaskListOptions): Promise<PeerTaskRowSummary[]>;
    listByRoot(rootSessionId: string, opts?: PeerTaskListOptions): Promise<PeerTaskRowSummary[]>;
    delete(taskId: string, scope: string, expect?: {
        rev: number;
    }): Promise<boolean>;
    deleteBySession(scope: string, sessionId: string): Promise<string[]>;
    listScopes(): Promise<string[]>;
    rekeyScope(input: ScopeRekeyInput & {
        readonly mode: "plan";
    }): Promise<RekeyPlan>;
    rekeyScope(input: ScopeRekeyInput & {
        readonly mode: "arrive";
    }): Promise<RekeyDone | RekeyConflict>;
    rekeyScope(input: ScopeRekeyInput & {
        readonly mode: "leave" | "withdraw";
    }): Promise<RekeyDone>;
    reap(scope: string, now: number, opts?: PeerTaskReapOptions): Promise<number>;
}
