/**
 * createDeliverMessageHandler — the owner-side receive handler for the §L4
 * deliverMessage command (Multi-Machine Session Pool). Per "Structure > Willpower"
 * this is a single shared factory imported by BOTH the server boot wiring and its
 * tests, so the production handler and the tested handler can never drift.
 *
 * The handler implements the §L4 ACK protocol's receive side:
 *   - stale-ownership fence: if the session has moved (the owner's epoch advanced
 *     past the router's view at dispatch), reject so the router re-resolves.
 *   - durable-receipt-before-processing with idempotent dedupe on messageId: a
 *     redelivered message already recorded is ACKed `duplicate` and NOT re-processed.
 *   - otherwise record the receipt and ACK `queued`.
 *
 * The ACK confirms receipt into the owner's ledger, NOT reply completion — the
 * router advances the platform offset only on this ACK (exactly-once ingress).
 */
export function createDeliverMessageHandler(deps) {
    return (command) => {
        if (command.type !== 'deliverMessage') {
            // Defensive — the dispatcher only routes deliverMessage here, but be total.
            return { messageId: 'unknown', accepted: 'queued' };
        }
        const ownerEpoch = deps.ownerEpochOf(command.session);
        if (ownerEpoch != null && command.ownershipEpoch < ownerEpoch) {
            return { messageId: command.messageId, accepted: 'stale-ownership' };
        }
        // §3.4 sender re-validation — BEFORE the receipt: a rejected sender's
        // message must never be recorded as received (recording first would dedupe
        // the redelivery's NACK into a 'duplicate' ack).
        const envelope = command.senderEnvelope;
        if (envelope && deps.validateSender && !deps.validateSender(envelope, command.session)) {
            return { messageId: command.messageId, accepted: 'sender-rejected' };
        }
        const firstSeen = deps.recordReceipt(command.messageId, command.session);
        if (!firstSeen)
            return { messageId: command.messageId, accepted: 'duplicate' };
        deps.onAccepted?.(command);
        return { messageId: command.messageId, accepted: 'queued' };
    };
}
//# sourceMappingURL=DeliverMessageHandler.js.map