import { isDeliveryFailureCause, type DeliveryFailureCause } from "./delivery-failure.ts"; import { isReviewObserverExcluded } from "./memory-policy.ts"; import { remoteEnvelope, appendNote, DIGEST, frame, HUB, USER, isInvocationKind, keepNotes, MAX_HOP, mergePrefaces, newEnvelope, noteLine, parseMarker, quoteNotes, replyAudience, uniqueMemoryLines, type Envelope, type EnvelopeOpts, type PeerId, type PeerState, type Priority } from "./envelope.ts"; import type { PeerAdapter, DeliveryReceipt } from "./peers.ts"; import type { DoingKind } from "./peer-doing.ts"; import type { QueuePressure } from "./queue-backpressure.ts"; import { ACCEPTED_SETTLE_TIMEOUT_REASON, DeliveryJournal, MAX_ENVELOPE_BODY, type JournalDelivery, type JournalDeliveryState, type JournalResolution } from "./delivery-journal.ts"; import { DELIVERY_RETRY_WARNING } from "./delivery-hints.ts"; import { MAX_DEFERRED_HUB, RecoveryDeferredHubError, validateDeferredHub } from "./deferred-hub.ts"; import { parseRemotePeerId } from "../rooms/application.ts"; import { PreEffectToolRefusal } from "./tool-refusal.ts"; import { stripRecordLines } from "../memory/records.ts"; export type { DeliveryReceipt } from "./peers.ts"; export interface PublishResult { targets: PeerId[]; dropped?: "hop" | "fyi"; } export interface AcceptedDeliveryExpiry { id: string; peer: PeerId; revision: number; notifyConductor: boolean } export class ReviewInputHandoffError extends Error { constructor() { super("review input provenance unavailable; the message remains queued. Reconnect the peer, check ahub status for journal health, then retry hub_inbox."); this.name = "ReviewInputHandoffError"; } } export type BusEvent = | { t: "envelope"; env: Envelope; dropped?: "hop" | "fyi" } | { t: "overflow"; env: Envelope; peer: PeerId } | { t: "undeliverable"; env: Envelope; peer: PeerId; reason?: string } | { t: "stale"; env: Envelope; peer: PeerId; reason: string } | { t: "quiet"; env: Envelope; peers: PeerId[]; reason: string } | { t: "off_roster"; env: Envelope; peers: PeerId[] } | { t: "remote_delivery_settled"; peer: PeerId; deliveryId: string; outcome: "completed" | "failed_safe" } | { t: "state"; peer: PeerId; state: PeerState }; export interface BusOptions { /** Durable host-only comment provenance; no peer-supplied marker or task authority. */ reviewObserverScope?: (peer: PeerId) => string | undefined; /** Host task/input screening for observer-memory hooks; receives originals, never rendered output. */ reviewObserverInputExcluded?: (peer: PeerId, originals: Envelope[]) => boolean; /** Required durable provenance before a review-scoped input crosses a native handoff boundary; throws to refuse handoff. */ beforeReviewInputHandoff?: (peer: PeerId, originals: Envelope[]) => void; /** Durable application outbox ids; the bus combines them with its own pending ids without recursion. */ remotePending?: (room: string) => readonly string[]; /** Host provenance at enqueue, never a body screen; unknown/throw marks the original private. */ remotePrivate?: (env: Readonly) => boolean | undefined; /** Live project membership; absent preserves the existing audience and delivery behaviour. */ rostered?: (peer: PeerId) => boolean; /** Transient owner lifecycle fence: retain new work without changing console/budget pauses. */ deliveryHeld?: (peer: PeerId) => boolean; /** Observe original envelopes immediately before a transport starts its turn. */ onDeliver?: (peer: PeerId, originals: Envelope[]) => void; retryMs: number; /** A queue this long is delivered without waiting for the batch window. */ batchMax: number; /** How long a status envelope may wait for company before it is delivered on its own. */ batchMs: number; queueCap: number; /** Accepted live operational settings; read only at the next matching delivery/note operation. */ maxAttempts?: () => number; /** Maximum age of an accepted explicit-channel delivery before it needs review. */ acceptedSettleMs?: () => number; digestMax?: () => number; pullBudgetBytes?: () => number; notesKept?: () => number; /** Optional: rewrite a delivery before it goes out (M6 digest condensation). Must return its input on any failure. */ condense?: (envs: Envelope[]) => Promise; journal?: DeliveryJournal; /** Host-owned opt-in; no delivery body or timestamp is a routing-policy authority. */ trackQueuePressure?: () => boolean; /** * Optional: may an agent send this envelope now (issue #38)? `parent` is the id of what it answers. A reason refuses * it, and the sender hears it on its next delivery. */ admit?: (env: Envelope, parent?: string) => string | undefined; /** * Optional: does a queued envelope still matter to this recipient (issue #106)? Asked per recipient when a delivery is * built and again right before it is handed over, after condensation. False drops it unsent: the journal records it * as discarded and taps see a `stale` event. A string is false with its own reason (#223, a review-only peer). */ relevant?: (peer: PeerId, env: Envelope) => boolean | string; /** * Optional: why this recipient does not get this envelope (issue #107, a turn-free cohort). Asked per recipient once * the audience is final (implicit replies and `digest` resolved), so the other recipients still get it, unchanged; * the console and the log see it as published. */ silence?: (env: Envelope, peer: PeerId) => string | undefined; /** * Optional: an `important` envelope was just queued for a pull-only peer (issue #398). Advisory only: nothing was * dequeued, steered or journaled for it, and the queue still waits for `Bus.pull`; a throw is swallowed. */ onImportantQueued?: (peer: PeerId, counts: { queued: number; important: number }) => void; /** Optional (#878): an attached adapter observed its session title or current plan item. Never published, journaled or tapped. */ doing?: (peer: PeerId, kind: DoingKind, text?: unknown) => void; } /** Serializable delivery state used by the controlled restart coordinator. Bodies stay in the private daemon file. */ export interface BusSnapshot { schemaVersion: 1; queues: Record; prefaces: Record; seen: Envelope[]; attempts: Record; withdrawn: string[]; manualPaused?: string[]; /** Host enqueue provenance only. null means an age lost to a legacy/restored writer. */ queuedAt?: Record>; /** Hub notices accepted during recovery, durable but outside the carried delivery queues. */ deferredHub?: Envelope[]; /** Local enqueue deadlines; absent old metadata is unknown, never a fresh TTL. */ remoteQueueExpires?: Record>; /** Host room binding for retained queues, never reconstructed from a remote label. */ remoteQueueRooms?: Record; /** Original verified target identity; a reused room label cannot inherit queued text. */ remoteQueueMembers?: Record; journal?: ReturnType; } export const DEFAULT_BUS: BusOptions = { retryMs: 1000, batchMax: 3, batchMs: 15_000, queueCap: 200 }; /** * What a peer may claim for its own message. A hub-native peer writes `[IMPORTANT]` on routine status reports * (issue #29), and `important` interrupts every recipient at once, so it only keeps it when answering an * `important` request that was addressed to it. `fyi` and `status` are never capped. */ function capPriority(peer: PeerAdapter, priority: Priority, parent: EnvelopeOpts["inReplyTo"], delivery: Envelope[] | undefined): Priority { if (!peer.hubNative || priority !== "important") return priority; if (!parent) return "status"; // nothing was asked: an unsolicited report is never urgent enough to interrupt // The whole delivery, not just `replyParent`: an important request addressed to the peer can share a hop with a // later status item, and then the parent is that status item. const asked = delivery ?? [parent]; return asked.some((e) => e.priority === "important" && !!e.to?.includes(peer.id)) ? "important" : "status"; } /** `digest` is not a peer. A reply to a condensed delivery is for the senders that condensation replaced. */ function resolveTo(to: PeerId[], originals: Envelope[] | undefined): PeerId[] { if (!to.includes(DIGEST)) return to; const senders = originals ? replyAudience(originals) : []; return [...new Set(to.flatMap((id) => (id === DIGEST ? senders : [id])))]; } const SEEN_CAP = 2048; export const MAX_ATTEMPTS = 3; // ponytail: provenance is capped at 2048 ids/peer, 4096 peers, 100000 ids total and 256 KiB per snapshot. // Omitted metadata means unknown age only; use a measured per-envelope store if larger queues need provenance. const QUEUE_TIME_CAP = 2048, QUEUE_TIME_PEERS_CAP = 4096, QUEUE_TIME_TOTAL_CAP = 100_000, QUEUE_TIME_SNAPSHOT_BYTES = 256 * 1024; const REMOTE_ROOM_CAP = 200, REMOTE_QUEUE_TTL_MS = 24 * 60 * 60 * 1000; const remoteId = (id: string): boolean => id.includes("@"); const remoteFingerprint = (value: unknown): value is string => typeof value === "string" && /^[0-9a-f]{64}$/.test(value); // ponytail: one digest carries at most ten originals; larger supervision windows split into bounded deliveries. // Revisit this ceiling after measuring native supervision cost, rather than bypassing the delivery limit. export const DIGEST_MAX = 10; // #713: a pull-only peer reads between steps, often minutes apart, so one pull drains its queue up to this many bytes of rendered text instead of ten items. // Bounded, not unbounded: a queue larger than the budget takes more than one pull, and the reply says how many are still waiting. Push peers keep DIGEST_MAX. export const PULL_BUDGET_BYTES = 64 * 1024; export const NOTES_KEPT = 10; /** * N-peer fan-out. Never delivers back to `from`, caps hops, dedupes by id. Each peer has one queue, * delivered as a whole (one envelope, or a digest) when the peer is idle and the queue is ready: * it holds an `important` envelope, or `batchMax` envelopes, or its oldest one has waited `batchMs`. */ export const ROOM_PROOF_UNAVAILABLE_REASON = "room delivery proof unavailable; inspect ahub queue show"; export const ROOM_EPOCH_ROTATED_REASON = "room epoch rotated; inspect ahub queue show"; export class Bus { readonly peers = new Map(); private readonly opts: BusOptions; private readonly journal?: DeliveryJournal; private readonly queues = new Map(); private readonly queueTimes = new Map>(); private queueTimeEntries = 0; private queuePressureWasTracked = false; private readonly prefaces = new Map(); private readonly remoteQueueMembers = new Map(); private readonly remoteQueueRooms = new Map(); private readonly remoteQueueExpires = new Map>(); private readonly remoteReservations = new Map>(); private readonly remoteTransport = new Map(); private readonly paused = new Set(); private readonly manualPaused = new Set(); private readonly timers = new Map>(); private readonly draining = new Set(); /** Still pending while an asynchronous condensation runs; never includes native dispatches. */ private readonly preparing = new Map(); private readonly seen = new Map(); private readonly taps = new Set<(e: BusEvent) => void>(); private readonly withdrawn = new Set(); /** What each peer was last handed, next to what it stands for: an adapter that reports a failure later hands back the former. */ private readonly reviewParents = new Map>(); private readonly reviewResponses = new Map(); private reviewScopeRevision = -1; private readonly reviewScopeCache = new Map(); private readonly lastDelivery = new Map(); /** Latest inbox handout; kept separately so it cannot replace a pushed invocation's answer parent. */ private readonly lastPulled = new Map(); private readonly failureStreak = new Map(); private readonly lastFailure = new Map(); private readonly attempts = new Map(); // `${peer}:${envelope id}` -> failed deliveries /** Correlates each native receipt independently; a peer can have a steer and a delivery in flight. */ private readonly activeDeliveries = new Map(); private readonly pendingOutcomes: Omit[] = []; private suppressDrain = false; private readonly recoveryHeldPeers = new Set(); /** * The queue lengths changed. `publish` emits its envelope event *before* it enqueues, and a delivery emits * nothing at all, so anything that renders `queued` off a bus event records the count from before the change * and is never corrected once the queue empties (measured: status.json kept `queued 4` on an empty queue). */ onQueues?: () => void; /** Host-only registration observation; never changes delivery or peer state. */ onPeerAdded?: (peer: PeerId) => void; /** * #445 C2: a peer's answer to a delivery, offered BEFORE anything is built from it. The host returns true when the answer belongs to an invocation it * took over: the bus then publishes nothing, stores nothing, emits no event and lets no tap, queue, digest or memory path see it. `answers` is what the * peer was handed (the request is in it, never condensed), so a reply that answers an invocation is found by identity, not by addressing. */ onAnswer?: (peer: PeerId, text: string, answers: readonly Envelope[]) => boolean; /** Completed adapter answers only, under the same public-input observer ceiling as memory delivery. */ onFinalAnswer?: (peer: PeerId, text: string, context: { out: readonly Envelope[]; originals: readonly Envelope[] }) => void; /** Count-only forwarding telemetry; never emitted for a private, review-scoped or unbound answer. */ onFinalAnswerBytes?: (peer: PeerId, counts: { before: number; after: number }) => void; /** Host ledger authority; absent or unknown never permits invocation replay. */ canRetryInvocation?: (id: string) => boolean; onInvocationUncertain?: (id: string) => void; /** Validated transport receipts, ids only; application admission is not a capability result. */ onInvocationReceipt?: (id: string, state: "completed" | "failed_safe" | "needs_review") => void; hasInvocationTurn(peer: PeerId): boolean { return this.invocationTurnOpen(peer); } private readonly invocationDeliveries = new Map(); releaseInvocation(id: string): void { this.invocationDeliveries.delete(id); } invocationUncertain(id: string): boolean { const delivery = this.invocationDeliveries.get(id), row = delivery && this.journal?.get(delivery); return !!row && (row.state === "needs_review" || ["dispatching", "accepted"].includes(row.state) && !this.activeDeliveries.has(row.id)); } /** Hold the existing delivery rather than cancelling native work or replaying an uncertain effect. */ holdInvocation(id: string, reason: string, target?: PeerId, failureCause?: DeliveryFailureCause): void { const delivery = this.invocationDeliveries.get(id), row = delivery && this.journal?.get(delivery); if (!row || !this.journal) { this.storageError = "uncertain invocation delivery evidence unavailable; inspect the invocation ledger before recovery"; if (target) this.recoveryHeldPeers.add(target); this.onQueues?.(); return; } this.journal.transition(row.id, "needs_review", reason, undefined, failureCause ?? row.failureCause ?? "turn aborted"); this.activeDeliveries.delete(row.id); this.recoveryHeldPeers.add(row.peer); this.onQueues?.(); } /** Actual transport admission, using originals even when a digest was condensed. Never an enqueue metric. */ onDelivered?: (peer: PeerId, originals: Envelope[], deliveryId?: string) => void; /** Metadata-only current-input observation after a successful inbox handout; never a transport ACK. */ onPulled?: (peer: PeerId, originals: Envelope[]) => void; /** Metadata-only observation when an important message actually begins a steer; never a transport ACK. */ onSteering?: (peer: PeerId, originals: Envelope[]) => void; /** Before deliver's synchronous busy transition, with originals rather than a condensed digest. */ onDeliver?: (peer: PeerId, originals: Envelope[]) => void; /** Final rendered journal payload, and its first positive acknowledgement. Observation cannot alter settlement. */ onMemoryDelivery?: (peer: PeerId, deliveryId: string, out: Envelope[], field: "rendered" | "delivered") => void; /** Synchronous native failure observation, before queue callbacks can finish turn metrics. */ onDeliveryFailed?: (peer: PeerId) => void; private recoveryHeld = false; private deferHub = false; private readonly deferredHub = new Map(); private flushingHub = false; private replayingHub = false; private deferredEvents: BusEvent[] = []; private deferredNudges: (() => void)[] = []; private steering = 0; private condensing = 0; private closed = false; storageError?: string; /** Verified durable-write recovery edge; observation never changes settlement. */ onStorageRecovered?: () => void; constructor(opts: Partial = {}) { this.opts = { ...DEFAULT_BUS, ...opts }; this.onDeliver = opts.onDeliver; this.journal = opts.journal; this.trackingQueuePressure(); if (this.journal) { const state = this.journal.transportSnapshot(); const bus = state.bus as BusSnapshot; if (state.revision > 0 && bus && bus.schemaVersion === 1) this.loadSnapshot(bus); for (const id of state.manualPaused) { this.manualPaused.add(id); this.paused.add(id); } for (const row of this.journal.list()) { for (const env of row.originals) if (env.kind === "invocation") this.invocationDeliveries.set(env.id, row.id); if (row.state === "dispatching" || row.state === "accepted" || row.state === "needs_review" && (!remoteId(row.peer) || row.originals.some(isInvocationKind))) this.recoveryHeldPeers.add(row.peer); } } } /** Apply future batching and admission limits without disturbing queued work or its existing deadline. */ configureScheduling(config: Pick): void { const { batchMax, batchMs, queueCap } = config; if (!Number.isSafeInteger(batchMax) || batchMax < 1 || batchMax > 2_147_483_647 || !Number.isFinite(batchMs) || batchMs < 0 || batchMs > 2_147_483_647 || !Number.isSafeInteger(queueCap) || queueCap < 1 || queueCap > 2_147_483_647) { throw new Error("invalid bus scheduling configuration"); } Object.assign(this.opts, { batchMax, batchMs, queueCap }); } add(peer: PeerAdapter): void { const newAttachment = this.peers.get(peer.id) !== peer; if (peer.remoteRoom !== undefined && (!parseRemotePeerId(peer.id) || typeof peer.remoteRoom !== "string" || !peer.remoteRoom || peer.remoteRoom.length > 256 || !remoteFingerprint(peer.remoteMember))) throw new Error("invalid remote peer binding"); const pendingRemote = peer.remoteRoom !== undefined && this.hasRemoteWork(peer.id); if (peer.remoteRoom !== undefined && pendingRemote) { const room = this.remoteQueueRooms.get(peer.id), member = this.remoteQueueMembers.get(peer.id); if (room === undefined || member === undefined) { this.expireRemoteQueues(); if (this.hasRemoteWork(peer.id)) throw new Error("remote queued identity binding unavailable"); } else if (room !== peer.remoteRoom) throw new Error("remote queued room binding changed"); else if (member !== peer.remoteMember) throw new Error("remote queued member binding changed"); } if (peer.remoteRoom !== undefined && !pendingRemote) { this.remoteQueueRooms.delete(peer.id); this.remoteQueueMembers.delete(peer.id); } this.clearReviewProvenance(peer.id); this.peers.set(peer.id, peer); if (!this.queues.has(peer.id)) this.queues.set(peer.id, []); peer.onDelivery = (receipt) => { if (this.peers.get(peer.id) === peer) this.deliveryReceipt(peer.id, receipt); }; peer.onDoing = (kind, text) => { if (kind === "reset") this.clearReviewProvenance(peer.id); if (!this.closed && this.peers.get(peer.id) === peer) this.opts.doing?.(peer.id, kind, text); }; this.opts.doing?.(peer.id, "reset"); // a new adapter never shows what the one it replaces was doing // A final still traverses the current onMessage observer exactly once. This one-shot // marker is host-local, never a caller-supplied envelope or wire field. let finalMessage: { body: string; options: EnvelopeOpts | undefined; complete: boolean } | undefined; const receive = (text: string, opts?: EnvelopeOpts, final = false, complete = true) => { if (!this.isRostered(peer.id)) return `off roster: ${peer.id}`; // #445 C2: an answer to an invocation is found by what the peer was handed, never by how the answer is addressed, so a headless agent whose final answer is // normally shared with every peer cannot leak it. It is the invocation's answer when it names the request itself (an adapter may report its delivery complete before // it answers, so the receipt cannot decide), or when it names nothing while that invocation's own pushed delivery is still the peer's open turn. A pull updates // current-input provenance separately, so it never replaces this answer parent; after the invocation turn ends, a later unnamed message is ordinary. const pushed = this.lastDelivery.get(peer.id), pulled = this.lastPulled.get(peer.id), parentId = opts?.inReplyTo?.id; const namedPush = parentId !== undefined && pushed?.out.some(e => e.id === parentId); const namedPull = parentId !== undefined && pulled?.out.some(e => e.id === parentId); const pushedInvocation = pushed?.out.some(e => e.kind === "invocation") === true; const pulledInvocation = pulled?.out.some(e => e.kind === "invocation") === true; const answerParent = namedPush && pushedInvocation ? pushed : namedPull && pulledInvocation ? pulled : parentId === undefined && this.invocationTurnOpen(peer.id) ? pushedInvocation ? pushed : pulledInvocation ? pulled : undefined : undefined; let finalPriority: Priority | undefined; if (final) { const context = parentId === undefined ? pulled ?? pushed : namedPush ? pushed : namedPull ? pulled : undefined; const raw = text; finalPriority = parseMarker(raw).priority; // Strip before invocation routing, publication, journaling, digests or the console event tap. text = stripRecordLines(raw); let observable = !this.closed && this.peers.get(peer.id) === peer && !!context && opts?.private !== true && !remoteId(peer.id) && !opts?.to?.some(remoteId) && !answerParent; try { observable &&= this.opts.reviewObserverInputExcluded?.(peer.id, context!.originals) !== true && ![...context!.out, ...context!.originals].some(env => env.private || isReviewObserverExcluded(env) || isInvocationKind(env) || remoteId(env.from) || env.to?.some(remoteId)); } catch { observable = false; } if (observable) { if (complete) try { this.onFinalAnswer?.(peer.id, raw, context!); } catch { /* capture is optional and never changes answer routing */ } try { this.onFinalAnswerBytes?.(peer.id, { before: Buffer.byteLength(parseMarker(raw).body), after: Buffer.byteLength(parseMarker(text).body) }); } catch { /* count-only observer */ } } } if (this.onAnswer && answerParent && (namedPush || namedPull || parentId === undefined && this.invocationTurnOpen(peer.id))) { let taken = false; try { taken = this.onAnswer(peer.id, text, answerParent.out) === true; } catch { taken = true; } // a throwing host never turns a callee's answer into a broadcast if (taken) return; } const parsed = parseMarker(text), priority = finalPriority ?? parsed.priority, body = parsed.body; if (!body) return; // What the peer was handed differs from what it stands for once a delivery was condensed; both the audience // and the priority ceiling are about what it stands for. const last = (parentId !== undefined && namedPush ? pushed : parentId !== undefined && namedPull ? pulled : pulled ?? pushed); const answers = opts?.inReplyTo?.id !== undefined && last?.out.some((e) => e.id === opts.inReplyTo!.id); const originals = answers ? last!.originals : undefined; // `digest` in the audience stands for the condensed delivery even when a steer, not the digest, is the parent. const condensed = !!last?.out.some((e) => e.from === DIGEST); const audienceOriginals = originals ?? (opts?.to?.includes(DIGEST) && condensed ? last?.originals : undefined); const to = opts?.to?.length ? resolveTo(opts.to, audienceOriginals) : undefined; let env = newEnvelope(peer.id, body, { ...opts, ...(to ? { to } : {}), priority: opts?.priority ?? capPriority(peer, priority, opts?.inReplyTo, originals) }); env = this.reviewResponse(env, opts?.inReplyTo?.id); try { this.checkRemotePublication(env); } catch (error) { if (!(error instanceof PreEffectToolRefusal)) throw error; this.note(peer.id, noteLine(HUB, "decision", `your message was not delivered: ${error.message}`)); return error.message; } const offRoster = this.offRosterRecipients(env); if (offRoster.length && offRoster.length === new Set(env.to?.filter(id => id !== env.from)).size) { const reason = `off roster: ${offRoster.join(", ")}`; this.note(peer.id, noteLine(HUB, "decision", `your message was not delivered: ${reason}`)); return reason; // no publication and no limiter spend for an entirely refused audience } const admittedEnv = offRoster.length ? { ...env, to: env.to!.filter(id => !offRoster.includes(id)) } : env; // Limits count what is sent: the envelope as built (a reply goes to its parent's sender, `digest` is resolved, // the priority is capped), never the raw `to`. const parent = opts?.inReplyTo?.id; // Held back from every recipient (issue #107): nothing goes out, so nothing counts against the sender's limits. const hushed = this.hushed(env); const heldBack = hushed.length > 0 && hushed.length === this.audience(env).length; let refused = heldBack ? undefined : this.opts.admit?.(admittedEnv, parent); // A turn answer has no caller to refuse: over its important budget it goes out as status, not at all. if (refused && env.priority === "important" && !this.opts.admit?.({ ...admittedEnv, priority: "status" }, parent)) { // It went out, so the advice on how to send it does not apply. this.note(peer.id, noteLine(HUB, "decision", `your [IMPORTANT] message went out as status: ${refused.replace(/[;:] (retry after \d+ s, or )?send it without \[IMPORTANT\]$/, "")}`)); env = { ...env, priority: "status" }; refused = undefined; } if (refused) { this.note(peer.id, noteLine(HUB, "decision", `your message was not delivered: ${refused}`)); return refused; } let published: PublishResult; try { published = this.publishResult(env); } catch (error) { if (!(error instanceof PreEffectToolRefusal)) throw error; this.note(peer.id, noteLine(HUB, "decision", `your message was not delivered: ${error.message}`)); return error.message; } if (offRoster.length && published.dropped !== "hop") this.note(peer.id, noteLine(HUB, "decision", `your message is retained off roster for ${offRoster.join(", ")}; delivered to the other recipients`)); // The sender's result (issue #107): a turn answer has no caller, so it hears it on its next delivery. It counts as // not sent only when nobody got it. if (hushed.length) this.note(peer.id, noteLine(HUB, "decision", `your message was not delivered to ${hushed.map((h) => h.peer).join(", ")}: ${hushed[0]!.reason}`)); return heldBack ? hushed[0]!.reason : published.dropped === "hop" ? published : undefined; }; peer.onMessage = (text, opts) => { if (this.peers.get(peer.id) !== peer) return; const marker = finalMessage?.body === text && finalMessage.options === opts ? finalMessage : undefined; if (marker) finalMessage = undefined; // Consume before observers can emit nested diagnostics. return receive(text, opts, marker !== undefined, marker?.complete ?? true); }; peer.onFinalAnswer = (text, opts, complete = true) => { if (this.closed || this.peers.get(peer.id) !== peer) return; const previous = finalMessage; finalMessage = { body: text, options: opts, complete }; try { return peer.onMessage?.(text, opts); } finally { finalMessage = previous; } }; peer.onFailed = (envs, failure) => { // The adapter got the condensed list; what has to come back is what that list replaced. const last = this.lastDelivery.get(peer.id); const same = !!last && envs.length === last.out.length && envs.every((e, i) => e.id === last.out[i]!.id); if (this.journal) { for (const [deliveryId, owner] of this.activeDeliveries) { if (owner !== peer.id) continue; const row = this.journal.get(deliveryId); if (row && row.originals.some((e) => envs.some((incoming) => incoming.id === e.id))) { this.deliveryReceipt(peer.id, { id: deliveryId, state: "needs_review", reason: "adapter reported delivery failure without safe-failure evidence", failureCause: failure?.failureCause ?? "turn aborted" }); } } } else if (!remoteId(peer.id) && envs.some(env => env.kind === "invocation")) { this.recoveryHeldPeers.add(peer.id); for (const env of envs) if (env.kind === "invocation") this.onInvocationUncertain?.(env.id); } else this.failed(peer.id, same ? last.originals : envs, undefined, failure?.quota === true); }; peer.onState = () => { if (peer.state === "offline") this.clearReviewProvenance(peer.id); if (this.closed) return; if (this.peers.get(peer.id) !== peer) return; if (peer.state === "offline" && this.journal) { for (const [id, owner] of [...this.activeDeliveries]) if (owner === peer.id) this.uncertain(peer.id, id, "peer disconnected before delivery settlement", "peer offline"); } this.emit({ t: "state", peer: peer.id, state: this.stateOf(peer.id) }); void this.drain(peer.id); }; if (newAttachment) try { this.onPeerAdded?.(peer.id); } catch { /* observers cannot undo a registered peer */ } } private persist(): void { if (!this.journal) return; const tracking = this.trackingQueuePressure(); const wasUnavailable = this.storageError !== undefined; try { this.journal.transaction(() => { for (const outcome of this.pendingOutcomes) this.journal!.createDelivery(outcome); this.journal!.persistBus(this.snapshotWithoutJournal(), [...this.manualPaused], tracking); }); this.pendingOutcomes.length = 0; this.storageError = undefined; if (wasUnavailable) queueMicrotask(() => { if (this.closed || this.storageError) return; try { this.onStorageRecovered?.(); } catch { /* Recovery observers cannot undo the durable write. */ } }); } catch { this.storageError = "delivery journal unavailable"; throw new Error("delivery journal unavailable"); } } private durableHandoff(peer: PeerId, deliveryId: string, originals: Envelope[], out: Envelope[], observe = true): void { if (!this.journal) return; const delivery = { id: deliveryId, peer, state: "dispatching" as const, createdAt: Date.now(), originals, out }; this.journal.checkpointDelivery(this.snapshotWithoutJournal(), delivery, this.trackingQueuePressure()); if (observe) this.memoryDelivery(peer, deliveryId, out, "rendered", originals); } private snapshotWithoutJournal(): BusSnapshot { return this.snapshot(false); } /** Stop new deliveries while a coordinator takes a stable snapshot. Existing adapter turns are left alone. */ setRecoveryHold(held: boolean, deferHub = false): void { if (this.replayingHub) throw new RecoveryDeferredHubError("recovery notice release is already in progress"); if (held) { this.recoveryHeld = true; this.deferHub = deferHub; // An older target cannot carry this additive field: materialize before commit's expected integrity. if (!deferHub) this.flushDeferredHub(); return; } // Persist each deferred -> queued transition while deliveries are still fenced. A failed checkpoint // leaves the hold and the original pending head intact; a crash after it resumes from the journal. this.flushDeferredHub(); this.deferHub = false; this.recoveryHeld = false; this.onQueues?.(); for (const id of this.peers.keys()) void this.drain(id); } private flushDeferredHub(): void { if (this.flushingHub) return; if (this.storageError) this.persist(); this.replayingHub = true; try { while (this.deferredHub.size) { const env = this.deferredHub.values().next().value!; const beforeDeferred = [...this.deferredHub], beforeSeen = [...this.seen], beforeWithdrawn = [...this.withdrawn]; const affected = new Map(this.audience(env).map(peer => { const queue = this.queues.get(peer); return [peer, queue ? { queue, contents: [...queue] } : undefined] as const; })); const outcomes = this.pendingOutcomes.length; this.flushingHub = true; this.deferredEvents = []; this.deferredNudges = []; try { this.deferredHub.delete(env.id); this.publishNow(env); } catch { // Only publication state is transactional. A live peer's preface, pauses, attempts and // recovery mode are independent state, not something a failed checkpoint may reload. this.deferredHub.clear(); for (const [id, pending] of beforeDeferred) this.deferredHub.set(id, pending); this.seen.clear(); for (const [id, seen] of beforeSeen) this.seen.set(id, seen); this.withdrawn.clear(); for (const id of beforeWithdrawn) this.withdrawn.add(id); for (const [peer, queue] of affected) { if (queue) { queue.queue.splice(0, queue.queue.length, ...queue.contents); this.queues.set(peer, queue.queue); } else this.queues.delete(peer); } this.pendingOutcomes.length = outcomes; this.deferredEvents = []; this.deferredNudges = []; throw new RecoveryDeferredHubError("deferred hub notice checkpoint failed; recovery remains held; restore delivery storage, then retry release or abort"); } finally { this.flushingHub = false; } // Publication observers run only after the durable transition. Reentrant notices join the FIFO tail. const events = this.deferredEvents; this.deferredEvents = []; for (const event of events) this.emit(event); const nudges = this.deferredNudges; this.deferredNudges = []; for (const nudge of nudges) nudge(); this.onQueues?.(); } } finally { this.replayingHub = false; } } get isRecoveryHeld(): boolean { return this.recoveryHeld; } /** * Wait until a hold has fenced condensation, steering and queue drains already in flight. * A drain stuck on a peer that never settles must not spin a core forever (issue #56): * the wait backs off and gives up, leaving queues, in-flight deliveries and a hold the * caller did not set exactly as they were. */ async fenceRecovery(timeoutMs = 5_000): Promise { const heldBefore = this.recoveryHeld; this.recoveryHeld = true; const deadline = Date.now() + timeoutMs; let delay = 1; while (this.draining.size || this.steering || this.condensing) { if (Date.now() >= deadline) { if (!heldBefore) this.setRecoveryHold(false); throw new Error(`recovery fence timed out after ${timeoutMs} ms with ${this.draining.size + this.steering + this.condensing} deliveries still in flight; retry the operation`); } await Bun.sleep(delay); delay = Math.min(delay * 2, 50); } } /** A bounded, JSON-safe representation of queued work and retry/dedupe state. */ snapshot(includeJournal = true): BusSnapshot { const rooms = this.remoteRoomSnapshot(), members = this.remoteMemberSnapshot(); const queues = Object.fromEntries([...this.queues].map(([id, queue]) => [id, queue.map((e) => ({ ...e, ...(e.to ? { to: [...e.to] } : {}) }))])); for (const peer of new Set([...Object.keys(rooms), ...Object.keys(members)])) queues[peer] ??= []; const out: BusSnapshot = { schemaVersion: 1, queues, prefaces: Object.fromEntries([...this.prefaces].map(([id, e]) => [id, { ...e, ...(e.to ? { to: [...e.to] } : {}) }])), seen: [...this.seen.values()].map((e) => ({ ...e, ...(e.to ? { to: [...e.to] } : {}) })), attempts: Object.fromEntries(this.attempts), withdrawn: [...this.withdrawn], manualPaused: [...this.manualPaused], ...(this.deferredHub.size ? { deferredHub: structuredClone([...this.deferredHub.values()]) } : {}), ...(this.remoteQueueExpires.size ? { remoteQueueExpires: this.remoteExpirySnapshot() } : {}), ...(Object.keys(rooms).length ? { remoteQueueRooms: rooms } : {}), ...(Object.keys(members).length ? { remoteQueueMembers: members } : {}), }; if (this.trackingQueuePressure()) { // Metadata is advisory: omit capped or unknown entries rather than enlarge a delivery without bound. const queuedAt = Object.create(null) as NonNullable; let bytes = 32; for (const [peer, queue] of this.queues) { const times = Object.create(null) as Record; const peerBytes = Buffer.byteLength(JSON.stringify(peer)) + 4; for (const env of queue) { const at = this.queueTimes.get(peer)?.get(env.id); const entryBytes = Buffer.byteLength(JSON.stringify(env.id)) + 20; if (typeof at !== "number" || bytes + peerBytes + entryBytes > QUEUE_TIME_SNAPSHOT_BYTES) continue; times[env.id] = at; bytes += entryBytes; } if (Object.keys(times).length) { queuedAt[peer] = times; bytes += peerBytes; } } if (Object.keys(queuedAt).length) out.queuedAt = queuedAt; } if (includeJournal && this.journal) out.journal = this.journal.snapshot(); return out; } /** Restore state before peers attach. Queues remain held until the coordinator calls setRecoveryHold(false). */ restore(snapshot: BusSnapshot, _operationId?: string): void { if (snapshot.schemaVersion !== 1) throw new Error("unsupported bus recovery snapshot"); if (_operationId && this.journal) { const current = this.journal.snapshot(); if (current.revision === 0) { this.journal.importSnapshot(snapshot.journal ?? { schemaVersion: 1, revision: 1, instanceId: this.journal.instanceId, bus: snapshot, deliveries: [], manualPaused: snapshot.manualPaused ?? [] }, _operationId, this.trackingQueuePressure()); } const committedQueues = snapshot.queues; snapshot = this.journal.snapshot().bus; // Offline peers need not reattach. Their empty queue keys still belong to the // committed integrity view, even when no delivery ever persisted those keys (#234). // The journal remains authoritative for work: never resurrect a non-empty queue. for (const [id, queue] of Object.entries(committedQueues)) { if (queue.length === 0 && !Object.hasOwn(snapshot.queues, id)) snapshot.queues[id] = []; } } this.loadSnapshot(snapshot); if (this.journal) for (const row of this.journal.list()) for (const env of row.originals) if (env.kind === "invocation") this.invocationDeliveries.set(env.id, row.id); this.persist(); } private loadSnapshot(snapshot: BusSnapshot): void { const deferred = validateDeferredHub(snapshot.deferredHub, undefined, new Set([...snapshot.seen.map(e => e.id), ...Object.values(snapshot.queues).flat().map(e => e.id)])); if (deferred.length) { this.recoveryHeld = true; this.deferHub = true; } this.deferredHub.clear(); for (const env of deferred) this.deferredHub.set(env.id, structuredClone(env)); this.queues.clear(); for (const [id, queue] of Object.entries(snapshot.queues ?? {})) this.queues.set(id, queue.map((e) => ({ ...e, ...(e.to ? { to: [...e.to] } : {}) }))); this.queueTimes.clear(); this.queueTimeEntries = 0; if (this.trackingQueuePressure()) for (const [peer, queue] of this.queues) { const provenance = snapshot.queuedAt; const times = provenance && typeof provenance === "object" && !Array.isArray(provenance) && Object.hasOwn(provenance, peer) ? provenance[peer] : undefined; for (const env of queue) { const at = times && typeof times === "object" && !Array.isArray(times) && Object.hasOwn(times, env.id) ? times[env.id] : null; this.recordQueueTime(peer, env.id, typeof at === "number" && Number.isSafeInteger(at) && at > 0 ? at : null); } } this.remoteQueueMembers.clear(); for (const [peer, member] of Object.entries(snapshot.remoteQueueMembers ?? {})) if (parseRemotePeerId(peer) && remoteFingerprint(member)) this.remoteQueueMembers.set(peer, member); this.remoteQueueRooms.clear(); for (const [peer, room] of Object.entries(snapshot.remoteQueueRooms ?? {})) if (parseRemotePeerId(peer) && typeof room === "string" && room.length > 0 && room.length <= 256) this.remoteQueueRooms.set(peer, room); this.remoteQueueExpires.clear(); for (const [peer, values] of Object.entries(snapshot.remoteQueueExpires ?? {})) { if (!remoteId(peer)) continue; this.remoteQueueExpires.set(peer, new Map(Object.entries(values).filter(([, expiry]) => Number.isSafeInteger(expiry) && expiry >= 0))); } this.prefaces.clear(); for (const [id, e] of Object.entries(snapshot.prefaces ?? {})) this.prefaces.set(id, { ...e, body: uniqueMemoryLines(e.body), ...(e.to ? { to: [...e.to] } : {}) }); this.seen.clear(); for (const e of snapshot.seen ?? []) this.seen.set(e.id, { ...e, ...(e.to ? { to: [...e.to] } : {}) }); this.attempts.clear(); for (const [key, n] of Object.entries(snapshot.attempts ?? {})) if (Number.isInteger(n) && n > 0) this.attempts.set(key, n); this.withdrawn.clear(); for (const id of snapshot.withdrawn ?? []) this.withdrawn.add(id); if (snapshot.manualPaused) { this.manualPaused.clear(); this.paused.clear(); for (const id of snapshot.manualPaused) { this.manualPaused.add(id); this.paused.add(id); } } } knownPeers(): string[] { const pending = this.storageError ? [] : this.journal?.pendingPeers() ?? []; return [...new Set([...this.peers.keys(), ...[...this.queues].filter(([, queue]) => queue.length).map(([id]) => id), ...pending])].sort(); } /** Declare an already-rostered local destination whose adapter is not instantiated yet. */ ensureKnownRecipientQueue(peer: PeerId): void { if (this.closed || this.recoveryHeld || this.storageError) throw new Error("delivery recipient queue unavailable"); if (typeof peer !== "string" || !/^[a-z][a-z0-9-]{0,31}$/.test(peer) || peer === HUB || peer === USER || peer === DIGEST || remoteId(peer) || !this.isRostered(peer)) throw new Error("invalid configured local recipient"); if (!this.queues.has(peer)) this.queues.set(peer, []); } queueList(peer?: string, unresolvedOnly = false): JournalDelivery[] { if (this.journal) { const rows = (unresolvedOnly ? this.journal.unresolved(peer) : this.journal.list(peer)).filter((row) => !row.reason?.startsWith("grouped into delivery ")); const revision = this.journal.revision(); const recorded = new Set(rows.filter((r) => ["queued", "dispatching", "accepted", "needs_review"].includes(r.state)).flatMap((r) => (r.originals as Envelope[]).map((e) => `${r.peer}:${e.id}`))); const ids = peer ? [peer] : [...this.queues.keys()]; for (const p of ids) for (const e of this.queues.get(p) ?? []) if (!recorded.has(`${p}:${e.id}`)) rows.push({ id: `q:${p}:${e.id}`, peer: p, state: "queued", revision, createdAt: e.ts, updatedAt: e.ts, originals: [e], out: [e] }); return rows.sort((a, b) => a.createdAt - b.createdAt || a.id.localeCompare(b.id)); } const ids = peer ? [peer] : [...this.queues.keys()]; return ids.flatMap((p) => (this.queues.get(p) ?? []).map((e) => ({ id: e.id, peer: p, state: "queued" as const, revision: 0, createdAt: e.ts, updatedAt: e.ts, originals: [e], out: [e] }))); } /** Metadata only: status must not hydrate or sort retained delivery payloads. */ failedDeliveryCounts(): Record | undefined { if (this.closed || this.storageError || !this.journal) return undefined; try { return this.journal.unresolvedFailedCounts(); } catch { this.storageError = "delivery journal unavailable"; return undefined; } } queueShow(id: string): JournalDelivery | undefined { return this.journal?.get(id) ?? this.queueList().find((d) => d.id === id); } heldDeliveryHints(peer: string, includeAccepted = false) { const adapter = this.peers.get(peer); const canExposeAccepted = includeAccepted && adapter?.acceptedSettlement === "explicit"; return this.storageError ? undefined : this.journal?.heldDeliveryHints(peer, canExposeAccepted); } /** Read held originals without changing transport, retry or task evidence. */ heldInbox(peer: PeerId) { if (this.closed || this.storageError || !this.journal) throw new Error("held inbox unavailable"); return this.journal.heldInbox(peer, this.peers.get(peer)?.acceptedSettlement === "explicit", this.opts.pullBudgetBytes?.() ?? PULL_BUDGET_BYTES); } hasHeldReviewScope(peer: PeerId): boolean { if (this.closed || this.storageError) return true; try { return this.journal?.hasHeldReviewScope(peer, this.peers.get(peer)?.acceptedSettlement === "explicit", this.opts.pullBudgetBytes?.() ?? PULL_BUDGET_BYTES) ?? false; } catch { return true; } // Unknown provenance excludes observers without failing the caller. } /** Whether timeout-originated holds still protect the recovery cause from supersession. */ hasAcceptedTimeoutHolds(): boolean { if (this.closed || this.storageError || !this.journal) throw new Error("delivery timeout hold state unavailable"); return this.journal.hasAcceptedTimeoutHolds(); } /** Expire only accepted channel notifications, without replaying or settling their effects. */ expireAcceptedDeliveries(now = Date.now()): AcceptedDeliveryExpiry[] { if (this.closed || this.recoveryHeld || !this.journal || this.storageError) return []; const settleMs = this.opts.acceptedSettleMs?.(); if (!Number.isSafeInteger(settleMs) || settleMs! < 1) return []; if (!Number.isSafeInteger(now) || now < 0) return []; if (now < settleMs!) return []; const expired: AcceptedDeliveryExpiry[] = []; const notify = () => { try { this.onQueues?.(); } catch { /* observers cannot consume a durable timeout notice */ } }; const eligiblePeers = [...this.peers.values()].filter(peer => peer.acceptedSettlement === "explicit").map(peer => peer.id); try { for (const row of this.journal.expiredAccepted(now - settleMs!, eligiblePeers)) { // The synchronous read/transition pair is revision fenced; no await allows a confirmation to interleave. const current = this.journal.get(row.id); if (!current || current.peer !== row.peer || current.state !== "accepted" || current.revision !== row.revision) continue; let updated: JournalDelivery; try { updated = this.journal.transition(row.id, "needs_review", ACCEPTED_SETTLE_TIMEOUT_REASON, row.revision, "timeout"); } catch (error) { if (error instanceof Error && /stale delivery revision/.test(error.message)) continue; this.storageError = "delivery journal unavailable"; notify(); return expired; } this.activeDeliveries.delete(row.id); if (!remoteId(row.peer)) this.recoveryHeldPeers.add(row.peer); expired.push({ id: row.id, peer: row.peer, revision: updated.revision, notifyConductor: row.notifyConductor }); this.deliveryFailed(current.peer); for (const env of current.originals) if (isInvocationKind(env)) { try { this.onInvocationReceipt?.(env.id, "needs_review"); } catch { /* an observer cannot suppress timeout metadata */ } if (env.kind === "invocation") try { this.onInvocationUncertain?.(env.id); } catch { /* preserve uncertain invocation handling for other ids */ } } } } catch { this.storageError = "delivery journal unavailable"; notify(); return expired; } if (expired.length) notify(); return expired; } /** Consent is for this peer's held row only, never authority to complete/discard or release a pause. */ retryDelivery(peer: string, id: string): void { const refuse = () => { throw new PreEffectToolRefusal("recipient retry unavailable; inspect the held delivery or ask the person"); }; if (this.closed || this.recoveryHeld || this.storageError || peer === "user" || peer === HUB) return refuse(); const row = this.queueShow(id); if (!row || row.peer !== peer || row.state !== "needs_review" || !this.journal || this.journal.retryEvidence(peer, row.originals) !== "unused") return refuse(); if (row.originals.some(env => env.kind === "invocation")) return refuse(); this.resolveDelivery(id, row.revision, "retry", "recipient requested one uncertain redelivery", `peer:${peer}`); } /** Settle only this peer's own uncertain receipt; this never replays its originals or changes task state. */ resolveOwnDelivery(peer: string, id: string, revision: number, action: "completed" | "discard", reason: string): void { const refuse = (message: string): never => { throw new PreEffectToolRefusal(message); }; // One message per cause class, each naming its next step. An unknown id, another peer's row and a row that is not needs_review share one message so a refusal never confirms another peer's row. if (peer === USER || peer === HUB || remoteId(peer)) return refuse(`hub_delivery_resolve settles a local agent's own held delivery; the person settles any other row with ahub queue resolve (ahub queue show ${id} prints the full command)`); if (this.closed || this.recoveryHeld || this.storageError || !this.journal) return refuse("the hub is not accepting delivery changes now (recovery, shutdown or delivery storage); run ahub status, then call hub_delivery_resolve again after it recovers"); if (this.paused.has(peer) || this.opts.deliveryHeld?.(peer) === true) return refuse("your deliveries are paused or held, so this row cannot be settled now; run ahub status to see which, and call hub_delivery_resolve again once it is released"); if (!Number.isSafeInteger(revision) || revision < 0 || (action !== "completed" && action !== "discard") || typeof reason !== "string" || !reason.trim() || reason.trim().length > 1000) return refuse("hub_delivery_resolve needs the revision hub_inbox showed (a whole number), action completed or discard, and a reason of 1 to 1000 characters"); const row = this.queueShow(id), actor = `peer:${peer}`, cleanReason = reason.trim(); const notYours = "no needs_review delivery with this id is held for you; call hub_inbox to list your held deliveries and their revisions"; if (!row || row.peer !== peer) return refuse(notYours); if (this.activeDeliveries.has(id) && this.activeDeliveries.get(id) !== peer) return refuse(notYours); // An uncertain invocation may still be running: a peer claiming it completed would make the caller wait for a result that may never come. Only the person settles it. if (row.originals.some(env => isInvocationKind(env))) return refuse(`delivery ${id} carries an invocation whose outcome is uncertain; only the person settles it (ahub queue show ${id} prints the full ahub queue resolve ${id} command; pass it on as printed)`); if (row.state === "accepted") { if (this.peers.get(peer)?.acceptedSettlement !== "explicit") return refuse("only an explicit push channel session can settle its accepted delivery; ask the person to resolve it"); if (row.revision !== revision) return refuse("held delivery revision changed; read hub_inbox again for the current revision"); try { this.resolveDelivery(id, revision, action, cleanReason, actor); } catch (error) { if (error instanceof Error && /stale delivery revision/.test(error.message)) return refuse("held delivery revision changed; read hub_inbox again for the current revision"); return refuse("delivery storage refused this disposition; inspect ahub status and ask the person to resolve it"); } return; } const previous = this.journal.resolution(id); if (previous) { if (previous.actor !== actor || previous.action !== action || previous.reason !== cleanReason) return refuse(`delivery ${id} was already settled with a different action or reason; the person can inspect it with ahub queue show ${id}`); if (revision !== previous.observedRevision && revision !== row.revision) return refuse("held delivery revision changed; read hub_inbox again for the current revision"); this.resolveDelivery(id, revision, action, cleanReason, actor); return; } if (row.state !== "needs_review") return refuse(notYours); if (row.revision !== revision) return refuse("held delivery revision changed; read hub_inbox again for the current revision"); this.resolveDelivery(id, revision, action, cleanReason, actor); } private retryOut(peer: string, originals: Envelope[], out: Envelope[]): Envelope[] { if (remoteId(peer)) return out; if (!out.length || !this.journal || !this.journal.retryWarning(peer, originals)) return out; return out.map((env, index) => { if (index !== 0) return env; const prefix = `${DELIVERY_RETRY_WARNING}\n\n`, marker = "\n[cut: rendered body exceeds delivery limit]"; if (prefix.length + env.body.length <= MAX_ENVELOPE_BODY) return { ...env, body: prefix + env.body }; let end = MAX_ENVELOPE_BODY - prefix.length - marker.length; // The journal cap uses UTF-16 length; never cut between a Unicode surrogate pair. if (Array.from(env.body.slice(end - 1, end + 1))[0]?.length === 2) end--; return { ...env, body: prefix + env.body.slice(0, end) + marker }; }); } /** #1096: the operator action that settled this delivery, when one did (`queue show` reads it to say what is left to do). */ deliveryResolution(id: string): JournalResolution | undefined { return this.journal && !this.storageError ? this.journal.resolution(id)?.action : undefined; } /** #1096: ids of the deliveries an operator action already settled, in one read; empty without a journal. `queue list` hides them unless asked for all. */ settledIds(): Set { return this.journal && !this.storageError ? this.journal.resolvedIds() : new Set(); } resolveDelivery(id: string, revision: number, action: "completed" | "retry" | "discard", reason: string, actor: string = "user"): void { if (!this.journal || this.storageError) throw new Error("delivery journal unavailable"); this.trackingQueuePressure(); const record = this.queueShow(id); if (!record) throw new Error("unknown delivery"); const previous = this.journal.resolution(id); if (previous) { // #1096: a row that already carries a resolution is settled. The same request again is idempotent (the journal verifies it); any other request is not a // stale read, and `retry` in particular leaves its parent in `failed` for good, because the redelivery is a new row. Say so instead of "stale revision". try { this.journal.resolve(id, revision, action, reason, revision, actor); } catch (error) { if (/stale delivery revision or conflicting operator resolution/.test(error instanceof Error ? error.message : "")) throw new Error(`delivery already resolved by ${previous.action}`); throw error; } return; } if (action === "retry" && remoteId(record.peer)) { const peer = this.peers.get(record.peer), room = this.remoteQueueRooms.get(record.peer), member = this.remoteQueueMembers.get(record.peer); if (record.state !== "needs_review" || record.originals.length !== 1 || !room || !remoteFingerprint(member) || peer?.remoteRoom !== room || peer.remoteMember !== member) throw new Error("remote original identity unavailable or changed; discard it or send a new message explicitly"); const deadline = this.remoteQueueExpires.get(record.peer)?.get(record.originals[0]!.id); if (!Number.isSafeInteger(deadline) || deadline! <= Date.now()) throw new PreEffectToolRefusal("remote original deadline unavailable or expired; discard it or send a new message explicitly"); this.checkRemotePublication(record.originals[0]!); } const explicitAcceptedDisposition = actor === `peer:${record.peer}` && record.state === "accepted" && this.peers.get(record.peer)?.acceptedSettlement === "explicit" && (action === "completed" || action === "discard"); const recipientConsent = actor === `peer:${record.peer}` && (record.state === "needs_review" && (action === "retry" || action === "completed" || action === "discard") || explicitAcceptedDisposition); // #713: a `queued` delivery was never handed to the peer, so nothing is in flight and a busy peer (a pull-only TUI is busy most of the time) does not block // discarding it. `dispatching` stays refused; `accepted` permits only its explicit channel owner's completed/discard disposition. if (record.state === "dispatching" || record.state === "accepted" && !explicitAcceptedDisposition) throw new Error("active delivery cannot be resolved"); const queuedDiscard = record.state === "queued" && action === "discard"; // #1096: a `failed` row was refused before it ran and discarding it touches no queue, so a busy peer has nothing in flight to protect either. const failedDiscard = record.state === "failed" && action === "discard"; if (this.peers.get(record.peer)?.state === "busy" && !recipientConsent && !queuedDiscard && !failedDiscard) throw new Error("peer busy: its delivery cannot be resolved while it works"); if (record.revision !== revision) throw new Error("stale delivery revision"); if (record.state === "queued" && action === "retry") throw new Error("queued delivery is already scheduled"); if (action === "retry" && !remoteId(record.peer) && (this.queues.get(record.peer)?.length ?? 0) + record.originals.length > this.opts.queueCap) throw new Error("recipient queue is full"); const queue = this.queues.get(record.peer) ?? []; const hadQueue = this.queues.has(record.peer); const before = [...queue]; const preface = this.prefaces.get(record.peer); try { this.journal.transaction(() => { if (!this.journal!.get(id)) this.journal!.createDelivery({ ...record }); const current = this.journal!.get(id)!; this.journal!.resolve(id, current.revision, action, reason, revision, actor, explicitAcceptedDisposition); if (record.state === "queued") { const ids = new Set(record.originals.map((env) => env.id)); queue.splice(0, queue.length, ...queue.filter((env) => !ids.has(env.id))); } if (action === "retry" || action === "completed" && actor === "hub") { for (const env of record.originals) { if (env.from === HUB && env.kind === "presence") this.restorePreface(record.peer, env); else if (action === "retry" && !queue.some((old) => old.id === env.id)) queue.push(env); } if (action === "retry") this.queues.set(record.peer, queue); } this.persist(); }); } catch (error) { queue.splice(0, queue.length, ...before); if (!hadQueue) this.queues.delete(record.peer); if (preface) this.prefaces.set(record.peer, preface); else this.prefaces.delete(record.peer); throw error; } if (explicitAcceptedDisposition) this.activeDeliveries.delete(id); this.refreshRecoveryHold(record.peer); this.onQueues?.(); void this.drain(record.peer); } queueSummary(peer: string): { needsReview: number; heldBy?: string; liveAccepted?: string[]; oldestQueuedAt?: number } { const rows = this.storageError ? [] : this.queueList(peer, true); const queued = this.queues.get(peer) ?? []; const review = rows.filter((r) => r.state === "needs_review"); const needsReview = review.length; const blocked = rows.find((r) => (r.state === "needs_review" && (!remoteId(peer) || r.originals.some(isInvocationKind))) || (["dispatching", "accepted"].includes(r.state) && !this.activeDeliveries.has(r.id))); const liveAccepted = rows.filter((r) => r.state === "accepted" && this.activeDeliveries.get(r.id) === peer).map((r) => r.id); const hold = { ...(blocked ? { heldBy: blocked.id } : {}), ...(liveAccepted.length ? { liveAccepted } : {}) }; const oldest = queued.reduce((a, r) => a === undefined ? r.ts : Math.min(a, r.ts), undefined); return oldest === undefined ? { needsReview, ...hold } : { needsReview, ...hold, oldestQueuedAt: oldest }; } manualPausedPeers(): string[] { return [...this.manualPaused].sort(); } setManualPaused(ids: string[]): void { this.manualPaused.clear(); for (const id of ids) this.manualPaused.add(id); this.persist(); } closeJournal(): void { this.reviewParents.clear(); this.reviewResponses.clear(); this.closed = true; this.recoveryHeld = true; for (const timer of this.timers.values()) clearTimeout(timer); this.journal?.close(); } deliveryReceipt(peer: PeerId, receipt: DeliveryReceipt): void { if (this.closed) return; const owner = this.activeDeliveries.get(receipt.id); if (!owner || owner !== peer || !this.journal) return; this.trackingQueuePressure(); const id = receipt.id; const before = this.journal.get(id); if (this.peers.get(peer)?.remoteRoom !== undefined && receipt.state === "failed_safe") { // A signed recipient NACK is a terminal known refusal, not a failed native // turn eligible for poison retries. It records no recipient read evidence. this.journal.transition(id, "failed", receipt.reason ?? "remote recipient refused safely", undefined, "adapter refused"); this.activeDeliveries.delete(id); if (this.remoteTransport.get(id)?.peer === peer) this.remoteTransport.delete(id); for (const env of before?.originals ?? []) { this.attempts.delete(`${peer}:${env.id}`); this.remoteQueueExpires.get(peer)?.delete(env.id); } const last = this.lastDelivery.get(peer); if (before && last && last.out.length === before.out.length && last.out.every((env, index) => env.id === before.out[index]!.id)) this.lastDelivery.delete(peer); this.refreshRecoveryHold(peer); for (const env of before?.originals ?? []) if (isInvocationKind(env)) { try { this.onInvocationReceipt?.(env.id, "failed_safe"); } catch { /* a ledger observer cannot undo a durable signed refusal */ } } this.onQueues?.(); void this.drain(peer); return; } const state: JournalDeliveryState = receipt.state === "accepted" ? "accepted" : receipt.state === "completed" ? "completed" : receipt.state === "failed_safe" ? "failed" : "needs_review"; if (!remoteId(peer) && (state === "failed" || state === "needs_review")) this.deliveryFailed(peer); if (state === "completed" && !remoteId(peer)) this.journal.completeDelivered(id, peer, "adapter", receipt.reason); else { let cause: DeliveryFailureCause | undefined; if (state === "failed" || state === "needs_review") { cause = isDeliveryFailureCause(receipt.failureCause) ? receipt.failureCause : undefined; if (!cause && state === "failed") cause = this.stateOf(peer) === "offline" ? "peer offline" : "adapter refused"; if (!cause) cause = "turn aborted"; } this.journal.transition(id, state, receipt.reason, undefined, cause); } if (!remoteId(peer) && before?.state === "dispatching" && (state === "accepted" || state === "completed")) { this.memoryDelivery(peer, id, before.out, "delivered", before.originals); this.delivered(peer, before.originals, id); } if (state === "failed") { if (before) this.failed(peer, before.originals, before.originals.some((e) => e.private) ? "private delivery failed" : receipt.reason, receipt.quota === true && before.state === "dispatching"); } if (state === "completed") { this.failureStreak.delete(peer); this.lastFailure.delete(peer); } if (state === "completed" || state === "failed" || state === "needs_review") { this.activeDeliveries.delete(id); if (remoteId(peer) && this.remoteTransport.get(id)?.peer === peer) this.remoteTransport.delete(id); } for (const env of before?.originals ?? []) if (isInvocationKind(env) && (receipt.state === "completed" || receipt.state === "needs_review")) { try { this.onInvocationReceipt?.(env.id, receipt.state); } catch { /* a ledger observer cannot undo a durable transport receipt */ } } if (state === "needs_review" && (!remoteId(peer) || before?.originals.some(isInvocationKind))) { this.recoveryHeldPeers.add(peer); for (const env of before?.originals ?? []) if (env.kind === "invocation") { try { this.onInvocationUncertain?.(env.id); } catch { /* uncertainty hold remains durable */ } } } if (state === "completed" || state === "failed" || state === "needs_review" && remoteId(peer)) { this.refreshRecoveryHold(peer); void this.drain(peer); } this.onQueues?.(); } private refreshRecoveryHold(peer: PeerId): void { if (!this.journal) return; // Live accepted notifications are awaiting explicit correlation, not crash recovery. const blocked = this.journal.list(peer).some((r) => (r.state === "needs_review" && (!remoteId(peer) || r.originals.some(isInvocationKind))) || (["dispatching", "accepted"].includes(r.state) && this.activeDeliveries.get(r.id) !== peer)); if (blocked) this.recoveryHeldPeers.add(peer); else this.recoveryHeldPeers.delete(peer); } completeReply(peer: PeerId, envelopeId: string): void { if (!this.journal) return; this.trackingQueuePressure(); for (const [id, owner] of this.activeDeliveries) { if (owner !== peer) continue; const row = this.journal.get(id); if (row?.peer === peer && ["dispatching", "accepted"].includes(row.state) && row.out.some((e) => e.id === envelopeId)) { this.journal.completeDelivered(id, peer, "reply", "correlated reply"); if (row.state === "dispatching") this.memoryDelivery(peer, id, row.out, "delivered", row.originals); this.activeDeliveries.delete(id); this.refreshRecoveryHold(peer); this.onQueues?.(); void this.drain(peer); break; } } } /** Explicit completion never resolves recovered, unrelated or already uncertain work. */ completeDelivery(peer: PeerId, deliveryId: string): boolean { const row = this.journal?.get(deliveryId); // The bridge separately fences socket/generation/handed IDs. Retrying a completed // acknowledgement (or acknowledging after a correlated reply) changes nothing. if (row?.peer === peer && row.state === "completed") return true; if (this.activeDeliveries.get(deliveryId) !== peer || row?.state !== "accepted") return false; this.deliveryReceipt(peer, { id: deliveryId, state: "completed", reason: "explicit correlated completion" }); return true; } queueIds(id: PeerId): string[] { return (this.queues.get(id) ?? []).map((e) => e.id); } queuedBacklogIds(id: PeerId): Set { const ids = new Set(); const retained = [...this.pendingEnvelopes(id), ...(this.journal?.unresolved(id).filter(row => row.state !== "queued").flatMap(row => row.originals) ?? [])]; for (const env of retained) { const backlog = env.refs?.backlog; if (env.from !== HUB || env.kind !== "task" || !Array.isArray(backlog) || backlog.length > 64) continue; for (const task of backlog) if (Number.isSafeInteger(task) && task > 0) ids.add(task); } return ids; } attemptState(): Record { return Object.fromEntries(this.attempts); } tap(fn: (e: BusEvent) => void): () => void { this.taps.add(fn); return () => this.taps.delete(fn); } /** Paused by the console or the budget relay, whatever the adapter's own state. */ isPaused(id: PeerId): boolean { return this.paused.has(id); } /** The adapter's state, or `paused` while the peer is held by `pause()`. */ stateOf(id: PeerId): PeerState { const state = this.peers.get(id)?.state ?? "offline"; return this.paused.has(id) && state !== "offline" ? "paused" : state; } pause(id: PeerId): void { // Transient holds are not in BusSnapshot; their owners persist durable policy. this.paused.add(id); this.emit({ t: "state", peer: id, state: this.stateOf(id) }); } resume(id: PeerId): void { if (!this.paused.delete(id)) return; this.emit({ t: "state", peer: id, state: this.stateOf(id) }); void this.drain(id); } /** Context the hub wants the peer to see once: it rides in front of the next delivery instead of costing a turn of its own. */ preface(id: PeerId, text: string): void { if (remoteId(id)) return; const body = uniqueMemoryLines(quoteNotes(text)); const existing = this.prefaces.get(id); if (existing) { // A fresh daemon recalls again after restoring queued context. Merge repeated blocks, // retain distinct context and keep the original envelope id/hop for retry bookkeeping. this.prefaces.set(id, { ...existing, body: mergePrefaces(existing.body, body) }); this.persist(); return; } this.prefaces.set(id, newEnvelope(HUB, body, { to: [id], kind: "presence" })); this.persist(); } /** Another peer's shared note: rides in the preface like recall. The newest NOTES_KEPT stay; older ones remain in amem. */ note(id: PeerId, line: string): void { if (remoteId(id)) return; const existing = this.prefaces.get(id); this.prefaces.set(id, existing ? { ...existing, body: keepNotes(uniqueMemoryLines(appendNote(existing.body, line)), this.opts.notesKept?.() ?? NOTES_KEPT) } : newEnvelope(HUB, uniqueMemoryLines(line), { to: [id], kind: "presence" })); this.persist(); } /** A preface that went out with a failed delivery comes back ahead of whatever was prefaced meanwhile, instead of replacing it. */ private restorePreface(id: PeerId, env: Envelope): void { if (remoteId(id)) return; const now = this.prefaces.get(id); this.prefaces.set(id, !now ? { ...env, body: uniqueMemoryLines(env.body) } : now.id === env.id ? { ...now, body: uniqueMemoryLines(now.body) } : { ...env, body: keepNotes(mergePrefaces(env.body, now.body), this.opts.notesKept?.() ?? NOTES_KEPT) }); } /** * Reset only: audit every deferred recipient without publishing or releasing work. The guard below is what it * checks: no attached peers, no flush or replay in progress and a readable journal. It cannot see a running * daemon, so the caller (`resetRuntime`) must hold the stopped-hub proof; a bare Bus has none. */ discardDeferredHub(reason: string): string[] { if (this.peers.size || this.flushingHub || this.replayingHub || !this.journal || this.storageError) throw new Error("deferred reset requires a stopped, readable delivery journal"); this.trackingQueuePressure(); const pending = [...this.deferredHub]; const settled: string[] = []; try { this.journal.transaction(() => { for (const [, env] of pending) for (const peer of new Set(env.to ?? [])) { const id = `q:${peer}:${env.id}`; this.journal!.createDelivery({ id, peer, state: "queued", createdAt: env.ts, originals: [env], out: [env] }); const row = this.journal!.get(id)!; this.journal!.resolve(id, row.revision, "discard", reason, row.revision, "user"); settled.push(id); } this.deferredHub.clear(); this.persist(); }); } catch (error) { this.deferredHub.clear(); for (const [id, env] of pending) this.deferredHub.set(id, env); throw error; } return settled; } /** Accepted pending work, including notices withheld from the recovery integrity view. */ pendingEnvelopes(peer: PeerId): Envelope[] { return [...(this.queues.get(peer) ?? []), ...[...this.deferredHub.values()].filter(e => e.to?.includes(peer))]; } /** Own accepted queue/preparation/active ids, without consulting the host callback. */ remotePendingIds(room: string): string[] { const ids = new Set(); for (const [peer, queue] of this.queues) if ((this.remoteQueueRooms.get(peer) ?? this.peers.get(peer)?.remoteRoom) === room) for (const env of queue) ids.add(env.id); for (const [peer, batch] of this.preparing) if ((this.remoteQueueRooms.get(peer) ?? this.peers.get(peer)?.remoteRoom) === room) for (const env of batch) ids.add(env.id); for (const { peer, originals } of this.remoteTransport.values()) if ((this.remoteQueueRooms.get(peer) ?? this.peers.get(peer)?.remoteRoom) === room) for (const env of originals) ids.add(env.id); for (const [id, peer] of this.activeDeliveries) if ((this.remoteQueueRooms.get(peer) ?? this.peers.get(peer)?.remoteRoom) === room) for (const env of this.journal?.get(id)?.originals ?? []) ids.add(env.id); return [...ids]; } /** Remote preflight precedes limiter admission; publication rechecks before effects. */ checkRemotePublication(env: Envelope): string[] { if (env.to?.some(remoteId) && this.opts.remotePrivate) { try { if (this.opts.remotePrivate(env) !== false) env.private = true; } catch { env.private = true; } } const rooms = new Set(), targets = [...new Set((env.to ?? []).filter(remoteId))]; if (remoteId(env.from) && !parseRemotePeerId(env.from)) throw new PreEffectToolRefusal("invalid remote sender"); for (const target of targets) { const peer = this.peers.get(target); if (!parseRemotePeerId(target) || !peer?.remoteRoom || !remoteFingerprint(peer.remoteMember)) throw new PreEffectToolRefusal("remote recipient unavailable"); const bound = this.remoteQueueRooms.get(target), member = this.remoteQueueMembers.get(target); if (this.hasRemoteWork(target) && (!bound || !member || bound !== peer.remoteRoom || member !== peer.remoteMember)) throw new PreEffectToolRefusal("remote queued identity binding changed"); const ttl = peer.remoteQueueTtlMs ?? REMOTE_QUEUE_TTL_MS; if (!Number.isSafeInteger(ttl) || ttl <= 0 || !Number.isSafeInteger(Date.now() + ttl)) throw new PreEffectToolRefusal("remote queue TTL unavailable"); rooms.add(peer.remoteRoom); } // ponytail: one original has one stable wire identity. A follow-up may derive // stable per-target wire ids and account each delivery separately before fan-out. if (targets.length > 1) throw new PreEffectToolRefusal(`remote targets ${targets.slice(0, 64).join(", ")}${targets.length > 64 ? ` and ${targets.length - 64} more` : ""}: send to each remote peer separately`); for (const room of rooms) { const pending = new Set([...this.remotePendingIds(room), ...(this.remoteReservations.get(room) ?? [])]); let external: readonly string[]; try { external = this.opts.remotePending?.(room) ?? []; } catch { throw new PreEffectToolRefusal("remote queue unavailable"); } if (!Array.isArray(external) || external.length > REMOTE_ROOM_CAP || external.some(id => typeof id !== "string" || id.length < 1 || id.length > 256)) throw new PreEffectToolRefusal("remote queue unavailable"); for (const id of external) pending.add(id); pending.add(env.id); if (pending.size > REMOTE_ROOM_CAP) throw new PreEffectToolRefusal("remote room queue is full"); } return [...rooms]; } private hasRemoteWork(peer: string, pending?: ReadonlySet): boolean { return (this.queues.get(peer)?.length ?? 0) > 0 || this.preparing.has(peer) || [...this.activeDeliveries.values()].includes(peer) || [...this.remoteTransport.values()].some(value => value.peer === peer) || (pending ?? new Set(this.journal?.pendingPeers() ?? [])).has(peer); } private remoteBindingSnapshot(values: ReadonlyMap): Record { if (!values.size) return {}; const pending = new Set(this.journal?.pendingPeers() ?? []); return Object.fromEntries([...values].filter(([peer]) => this.hasRemoteWork(peer, pending))); } private remoteMemberSnapshot(): Record { return this.remoteBindingSnapshot(this.remoteQueueMembers); } private remoteRoomSnapshot(): Record { return this.remoteBindingSnapshot(this.remoteQueueRooms); } private remoteExpirySnapshot(): Record> { const snapshot: Record> = {}; for (const [peer, expiries] of this.remoteQueueExpires) { const pending = new Set([...(this.queues.get(peer) ?? []), ...(this.preparing.get(peer) ?? [])].map(env => env.id)); for (const { peer: target, originals } of this.remoteTransport.values()) if (target === peer) for (const env of originals) pending.add(env.id); for (const [id, target] of this.activeDeliveries) if (target === peer) for (const env of this.journal?.get(id)?.originals ?? []) pending.add(env.id); // Uncertainty is still pending work. Keep its known TTL through checkpoints, // using unresolved rows only, never completed delivery history. for (const row of this.journal?.unresolved(peer) ?? []) for (const env of row.originals) pending.add(env.id); for (const id of expiries.keys()) if (!pending.has(id)) expiries.delete(id); if (expiries.size) snapshot[peer] = Object.fromEntries(expiries); else this.remoteQueueExpires.delete(peer); } return snapshot; } /** Metadata-only timer hint; an unknown retained deadline/binding is due immediately. */ nextRemoteExpiry(): number | undefined { let next: number | undefined; for (const [peer, queue] of this.queues) { if (!remoteId(peer) || !queue.length) continue; if (!this.remoteQueueRooms.has(peer) || !this.remoteQueueMembers.has(peer)) return Date.now(); const expiries = this.remoteQueueExpires.get(peer); for (const env of queue) { const expiry = expiries?.get(env.id); if (expiry === undefined) return Date.now(); next = next === undefined ? expiry : Math.min(next, expiry); } } return next; } /** Expiry is a durable uncertain outcome, never a silent retry/drop or a fresh timestamp. */ expireRemoteQueues(now = Date.now()): number { if (!Number.isSafeInteger(now) || now < 0) throw new Error("invalid remote queue clock"); if (!this.journal || this.closed) return 0; // Without a journal there is no durable sink for uncertain work. const expired = [...this.queues].filter(([peer]) => remoteId(peer)).flatMap(([peer, queue]) => queue.filter(env => { const expiry = this.remoteQueueExpires.get(peer)?.get(env.id); return this.remoteQueueRooms.get(peer) === undefined || this.remoteQueueMembers.get(peer) === undefined || expiry === undefined || expiry <= now; }).map(env => ({ peer, env }))); if (!expired.length) return 0; const queues = new Map([...this.queues].map(([peer, queue]) => [peer, [...queue]])); const expiries = new Map([...this.remoteQueueExpires].map(([peer, values]) => [peer, new Map(values)])); const held = [...this.recoveryHeldPeers], outcomes = this.pendingOutcomes.length; try { for (const { peer, env } of expired) { const queue = this.queues.get(peer)!; const index = queue.findIndex(item => item.id === env.id); if (index >= 0) queue.splice(index, 1); const known = this.remoteQueueExpires.get(peer)?.has(env.id); const failureCause: DeliveryFailureCause = known && this.remoteQueueRooms.has(peer) && this.remoteQueueMembers.has(peer) ? "timeout" : "push error"; this.remoteQueueExpires.get(peer)?.delete(env.id); this.pendingOutcomes.push({ id: crypto.randomUUID(), peer, state: "needs_review", createdAt: now, originals: [env], out: [env], failureCause, reason: !known ? "remote queue expiry unavailable after restore" : !this.remoteQueueRooms.has(peer) ? "remote queue room binding unavailable after restore" : !this.remoteQueueMembers.has(peer) ? "remote queue member binding unavailable after restore" : "remote queue expired before recipient admission" }); } this.persist(); } catch (error) { for (const [peer, before] of queues) this.queues.get(peer)!.splice(0, this.queues.get(peer)!.length, ...before); this.remoteQueueExpires.clear(); for (const [peer, values] of expiries) this.remoteQueueExpires.set(peer, values); this.recoveryHeldPeers.clear(); for (const peer of held) this.recoveryHeldPeers.add(peer); this.pendingOutcomes.length = outcomes; throw error; } this.onQueues?.(); return expired.length; } /** A room may acknowledge local admission only with a live, known-available journal. */ deliveryJournalAvailable(): boolean { return this.journal !== undefined && !this.storageError && !this.closed; } /** Explicit person disposition metadata only, never inferred from transport completion. */ remoteDisposition(deliveryId: string): "completed" | "retry" | "discard" | undefined { const resolution = this.journal?.resolution(deliveryId); return resolution?.actor === "user" ? resolution.action : undefined; } /** A late signed queue receipt is evidence for the person; it never auto-settles uncertainty. */ noteLateRemoteReceipt(peer: string, deliveryId: string, outcome: "completed" | "failed_safe"): boolean { if ((outcome !== "completed" && outcome !== "failed_safe") || !parseRemotePeerId(peer) || !this.peers.get(peer)?.remoteRoom || !this.journal || this.storageError || this.closed) return false; const row = this.journal.get(deliveryId), adapter = this.peers.get(peer)!; if (!row || row.peer !== peer || row.state !== "needs_review" || this.remoteQueueRooms.get(peer) !== adapter.remoteRoom || this.remoteQueueMembers.get(peer) !== adapter.remoteMember) return false; const reason = outcome === "completed" ? "late signed completed receipt: remote queue admitted; remains needs_review" : "late signed failed_safe receipt; remains needs_review"; if (row.reason !== reason) this.journal.transition(row.id, "needs_review", reason, row.revision); this.onQueues?.(); return true; } /** Settle an active or held remote row only when the current room adapter owns this receipt path. */ settleRemoteReceipt(source: PeerAdapter, deliveryId: string, outcome: "completed" | "failed_safe", reason: string, currentGuard: () => boolean): boolean { const peer = source.id; if ((outcome !== "completed" && outcome !== "failed_safe") || !parseRemotePeerId(peer) || this.peers.get(peer) !== source || !source.remoteRoom || !remoteFingerprint(source.remoteMember) || !this.journal || this.storageError || this.closed) return false; if (this.remoteQueueRooms.get(peer) !== source.remoteRoom || this.remoteQueueMembers.get(peer) !== source.remoteMember) return false; const row = this.journal.get(deliveryId); if (!row || row.peer !== peer || !["needs_review", "dispatching", "accepted"].includes(row.state) || row.originals.length !== 1 || row.originals[0]?.to?.includes(peer) !== true || this.journal.resolution(deliveryId)) return false; if (row.state === "needs_review" && row.originals.some(isInvocationKind)) return false; const activeOwner = this.activeDeliveries.get(deliveryId); if (activeOwner !== undefined && activeOwner !== peer) return false; try { if (currentGuard() !== true) return false; } catch { return false; } try { if (outcome === "completed") this.journal.completeRemoteReceipt(row.id, peer, row.revision, reason); else this.journal.failRemoteReceipt(row.id, peer, row.revision, reason); } catch (error) { if (error instanceof Error && /stale delivery revision|already has a person disposition|not unresolved/.test(error.message)) return false; this.storageError = "delivery journal unavailable"; this.onQueues?.(); return false; } this.activeDeliveries.delete(row.id); this.remoteTransport.delete(row.id); for (const env of row.originals) { this.attempts.delete(`${peer}:${env.id}`); this.remoteQueueExpires.get(peer)?.delete(env.id); } if (row.state !== "needs_review") for (const env of row.originals) if (isInvocationKind(env)) { try { this.onInvocationReceipt?.(env.id, outcome); } catch { /* the durable room receipt remains settled */ } } this.refreshRecoveryHold(peer); this.emit({ t: "remote_delivery_settled", peer, deliveryId: row.id, outcome }); this.onQueues?.(); void this.drain(peer); return true; } /** A typed room refusal before durable queue admission is safe to retry without failure accounting. */ requeueRemoteNotSent(source: PeerAdapter, deliveryId: string): boolean { const peer = source.id; if (!parseRemotePeerId(peer) || this.peers.get(peer) !== source || !source.remoteRoom || !remoteFingerprint(source.remoteMember) || !this.journal || this.storageError || this.closed || this.remoteQueueRooms.get(peer) !== source.remoteRoom || this.remoteQueueMembers.get(peer) !== source.remoteMember || this.activeDeliveries.get(deliveryId) !== peer) return false; const row = this.journal.get(deliveryId); if (!row || row.peer !== peer || row.state !== "dispatching" || row.originals.length !== 1) return false; const env = row.originals[0]!; if (env.to?.includes(peer) !== true) return false; const expiry = this.remoteQueueExpires.get(peer)?.get(env.id); if (expiry === undefined || expiry <= Date.now()) { this.deliveryReceipt(peer, { id: deliveryId, state: "needs_review", failureCause: expiry === undefined ? "push error" : "timeout", reason: expiry === undefined ? "remote queue expiry unavailable after restore" : "remote queue expired before recipient admission" }); return true; } const queue = this.queues.get(peer) ?? [], beforeQueue = [...queue]; if (queue.some(item => item.id === env.id)) return false; try { this.journal.transaction(() => { this.journal!.transition(deliveryId, "queued", "room transport confirmed not sent", row.revision); queue.unshift(env); this.queues.set(peer, queue); this.persist(); }); } catch { queue.splice(0, queue.length, ...beforeQueue); if (!beforeQueue.length && !this.queues.has(peer)) this.queues.delete(peer); this.storageError = "delivery journal unavailable"; this.onQueues?.(); return false; } this.activeDeliveries.delete(deliveryId); this.remoteTransport.delete(deliveryId); this.refreshRecoveryHold(peer); this.onQueues?.(); return true; } /** Host-only recovery port: expose one matching room original for proof revalidation. */ remoteDeliveryEnvelope(source: PeerAdapter, deliveryId: string): Envelope | undefined { const peer = source.id; if (this.peers.get(peer) !== source || !parseRemotePeerId(peer) || !source.remoteRoom || !remoteFingerprint(source.remoteMember) || this.remoteQueueRooms.get(peer) !== source.remoteRoom || this.remoteQueueMembers.get(peer) !== source.remoteMember || !this.journal || this.storageError || this.closed) return undefined; const row = this.journal.get(deliveryId), original = row?.originals[0]; if (!row || row.peer !== peer || !["needs_review", "dispatching", "accepted"].includes(row.state) || this.journal.resolution(deliveryId) || row.originals.length !== 1 || original?.to?.includes(peer) !== true) return undefined; return structuredClone(original); } /** Current host admission for sending remote work, separate from immutable room trust proof. */ remoteSendAllowed(source: PeerAdapter): boolean { const peer = source.id; if (!parseRemotePeerId(peer) || this.peers.get(peer) !== source || !source.remoteRoom || !remoteFingerprint(source.remoteMember) || !this.journal || this.storageError || this.closed || this.recoveryHeld || this.remoteQueueRooms.get(peer) !== source.remoteRoom || this.remoteQueueMembers.get(peer) !== source.remoteMember) return false; try { return this.isRostered(peer) && !this.paused.has(peer) && !this.manualPaused.has(peer) && this.opts.deliveryHeld?.(peer) !== true; } catch { return false; } } private holdRemoteDeliveryMetadata(peer: PeerId, row: JournalDelivery, reason: string): boolean { try { this.journal!.transition(row.id, "needs_review", reason, row.revision, row.failureCause ?? "push error"); } catch (error) { if (error instanceof Error && /stale delivery revision|unknown delivery|already has a person disposition/.test(error.message)) return false; this.storageError = "delivery journal unavailable"; this.onQueues?.(); return false; } this.activeDeliveries.delete(row.id); if (this.remoteTransport.get(row.id)?.peer === peer) this.remoteTransport.delete(row.id); this.refreshRecoveryHold(peer); this.onQueues?.(); void this.drain(peer); return true; } /** Hold a remote row for human inspection when its durable intent or delivery proof is unavailable. */ holdRemoteMissingIntent(source: PeerAdapter, deliveryId: string, currentGuard: () => boolean, origin: "restored" | "known-not-sent" | "proof-unavailable" = "restored"): boolean { if (origin !== "restored" && origin !== "known-not-sent" && origin !== "proof-unavailable") return false; const peer = source.id; if (!parseRemotePeerId(peer) || this.peers.get(peer) !== source || !source.remoteRoom || !remoteFingerprint(source.remoteMember) || !this.journal || this.storageError || this.closed || this.remoteQueueRooms.get(peer) !== source.remoteRoom || this.remoteQueueMembers.get(peer) !== source.remoteMember) return false; const row = this.journal.get(deliveryId); if (!row || row.peer !== peer || !["dispatching", "accepted", ...(origin === "proof-unavailable" ? ["needs_review"] : [])].includes(row.state) || row.originals.length !== 1 || row.originals[0]?.to?.includes(peer) !== true || this.journal.resolution(deliveryId)) return false; if (origin === "proof-unavailable" && row.originals.some(isInvocationKind)) return false; if (origin === "known-not-sent") { if (this.activeDeliveries.get(deliveryId) !== peer) return false; } else if (origin === "restored") { if (this.activeDeliveries.has(deliveryId) || this.remoteTransport.has(deliveryId)) return false; } else { const activeOwner = this.activeDeliveries.get(deliveryId), transportOwner = this.remoteTransport.get(deliveryId)?.peer; if (activeOwner !== undefined && activeOwner !== peer || transportOwner !== undefined && transportOwner !== peer) return false; } try { if (currentGuard() !== true) return false; } catch { return false; } if (origin === "proof-unavailable" && row.state === "needs_review") return true; const reason = origin === "restored" ? `room durable intent unavailable after restart; inspect ahub queue show ${deliveryId}` : origin === "known-not-sent" ? `room not-sent checkpoint unavailable; inspect ahub queue show ${deliveryId}` : `${ROOM_PROOF_UNAVAILABLE_REASON} ${deliveryId}`; return this.holdRemoteDeliveryMetadata(peer, row, reason); } /** Host-only quarantine when a signed room outcome belongs to an invalidated recipient tuple. */ holdInvalidatedRemoteOutcome(peerId: string, deliveryId: string, expectedRoom: string, expectedMember: string, currentGuard: () => boolean): boolean { // Exact equality below inherits the room bound enforced at add/loadSnapshot. if (!parseRemotePeerId(peerId) || typeof expectedRoom !== "string" || !expectedRoom || !remoteFingerprint(expectedMember) || !this.journal || this.storageError || this.closed || this.remoteQueueRooms.get(peerId) !== expectedRoom || this.remoteQueueMembers.get(peerId) !== expectedMember) return false; const row = this.journal.get(deliveryId); if (!row || row.peer !== peerId || !["dispatching", "accepted"].includes(row.state) || row.originals.length !== 1 || row.originals[0]?.to?.includes(peerId) !== true || this.journal.resolution(deliveryId) || this.activeDeliveries.has(deliveryId) || this.remoteTransport.has(deliveryId)) return false; try { if (currentGuard() !== true) return false; } catch { return false; } return this.holdRemoteDeliveryMetadata(peerId, row, `room recipient proof no longer current after restart; inspect ahub queue show ${deliveryId}`); } /** Person-authorized epoch change: hold metadata only, without cancellation, replay or completion. */ holdRemoteEpochRotated(peerId: string, deliveryId: string, expectedRoom: string, expectedMember: string, currentGuard: () => boolean): boolean { if (!parseRemotePeerId(peerId) || typeof expectedRoom !== "string" || !expectedRoom || !remoteFingerprint(expectedMember) || !this.journal || this.storageError || this.closed || this.remoteQueueRooms.get(peerId) !== expectedRoom || this.remoteQueueMembers.get(peerId) !== expectedMember) return false; const row = this.journal.get(deliveryId), reason = `${ROOM_EPOCH_ROTATED_REASON} ${deliveryId}`; if (!row || row.peer !== peerId || row.originals.length !== 1 || row.originals[0]?.to?.includes(peerId) !== true || this.journal.resolution(deliveryId)) return false; const active = this.activeDeliveries.get(deliveryId), transport = this.remoteTransport.get(deliveryId)?.peer; if (active !== undefined && active !== peerId || transport !== undefined && transport !== peerId) return false; if (!["dispatching", "accepted", "needs_review"].includes(row.state)) return false; if (row.state === "needs_review" && row.reason !== reason && row.reason !== `${ROOM_PROOF_UNAVAILABLE_REASON} ${deliveryId}`) return false; try { if (currentGuard() !== true) return false; } catch { return false; } if (row.state === "needs_review" && row.reason === reason) return true; return this.holdRemoteDeliveryMetadata(peerId, row, reason); } /** Resume the same delivery after the host revalidates its durable outbox proof. */ resumeRemotePending(source: PeerAdapter, deliveryId: string, state: "dispatching" | "accepted" | "needs_review", currentGuard: () => boolean): boolean { const peer = source.id; const journal = this.journal; if (!journal || !this.remoteSendAllowed(source)) return false; const row = journal.get(deliveryId), env = row?.originals[0], expiry = env && this.remoteQueueExpires.get(peer)?.get(env.id); if (!row || row.peer !== peer || !["dispatching", "accepted", "needs_review"].includes(row.state) || row.originals.length !== 1 || env?.to?.includes(peer) !== true || journal.resolution(deliveryId) || !env || expiry === undefined || expiry <= Date.now()) return false; if (row.state === "needs_review" && row.originals.some(isInvocationKind)) return false; if (state === "needs_review") return false; if ([...(this.queues.get(peer) ?? [])].some(item => item.id === env.id)) return false; if ([...this.activeDeliveries].some(([id, owner]) => owner === peer && id !== deliveryId)) return false; if ([...this.remoteTransport].some(([id, active]) => active.peer === peer && id !== deliveryId)) return false; try { if (currentGuard() !== true) return false; } catch { return false; } try { // Store and journal commit independently. An already-active journal row is // authoritative; a different Store state must not strand or downgrade it. if (row.state === "needs_review") journal.transition(deliveryId, state, "room outbox proof confirmed pending", row.revision); } catch { this.storageError = "delivery journal unavailable"; this.onQueues?.(); return false; } this.activeDeliveries.set(deliveryId, peer); this.remoteTransport.set(deliveryId, { peer, originals: row.originals }); this.refreshRecoveryHold(peer); this.onQueues?.(); void this.drain(peer); return true; } /** Returns the peers the envelope was accepted for, including durable deferred notices. */ publish(env: Envelope): PeerId[] { return this.publishResult(env).targets; } private clearReviewProvenance(peer: PeerId): void { this.reviewParents.delete(peer); for (const [id, source] of this.reviewResponses) if (source.peer === peer) this.reviewResponses.delete(id); } /** Host-derived observer provenance. Caller-supplied response/package markers are stripped. * ponytail: active turns and 128 delivered parent IDs per peer are attributable; arbitrary later * native-session paraphrases need explicit session provenance, never content matching or PII authority. */ reviewResponse(env: Envelope, parentId?: string): Envelope { if (env.from === HUB) return env; const pulled = this.lastPulled.get(env.from)?.originals ?? [], pushed = this.lastDelivery.get(env.from)?.originals ?? []; const active = pulled.length ? pulled : pushed; const parent = parentId ? pulled.find(item => item.id === parentId && isReviewObserverExcluded(item)) ?? pushed.find(item => item.id === parentId && isReviewObserverExcluded(item)) : active.find(isReviewObserverExcluded); const known = this.reviewResponses.get(env.id); let durableScope: string | undefined; try { durableScope = this.opts.reviewObserverScope?.(env.from); } catch { durableScope = "review-scope-unavailable"; } // Unknown provenance cannot clear an observer exclusion. const source = parent?.refs?.reviewPackage ?? parent?.refs?.reviewResponse ?? (parentId ? this.reviewParents.get(env.from)?.get(parentId) : undefined) ?? (known?.peer === env.from ? known.source : undefined) ?? durableScope; const { reviewPackage: _package, reviewResponse: _response, ...refs } = env.refs ?? {}; if (source && (env.kind === "chat" || env.kind === "status")) { this.reviewResponses.set(env.id, { peer: env.from, source }); if (this.reviewResponses.size > SEEN_CAP) this.reviewResponses.delete(this.reviewResponses.keys().next().value!); return { ...env, refs: { ...refs, reviewResponse: source } }; } return _package !== undefined || _response !== undefined ? { ...env, refs } : env; } /** Publication outcome distinguishes a policy drop from an empty audience. */ publishResult(env: Envelope): PublishResult { if (this.closed) return { targets: [] }; env = this.reviewResponse(env); if (this.storageError) throw new Error("delivery journal unavailable"); if (this.seen.has(env.id) || this.deferredHub.has(env.id)) return { targets: [] }; this.checkRemotePublication(env); if (this.recoveryHeld && (this.deferHub || this.replayingHub) && env.from === HUB && env.priority !== "fyi" && env.hop <= MAX_HOP) { if (this.deferredHub.size >= MAX_DEFERRED_HUB) throw new RecoveryDeferredHubError(); const targets = this.audience(env); const copy = structuredClone({ ...env, to: targets }); this.deferredHub.set(copy.id, copy); try { this.persist(); } catch (error) { this.deferredHub.delete(copy.id); throw error; } return { targets }; } return this.publishNow(env); } private publishNow(env: Envelope): PublishResult { if (this.closed) return { targets: [] }; if (this.storageError) throw new Error("delivery journal unavailable"); if (this.seen.has(env.id)) return { targets: [] }; const rooms = this.checkRemotePublication(env); for (const room of rooms) { const reserved = this.remoteReservations.get(room) ?? new Set(); reserved.add(env.id); this.remoteReservations.set(room, reserved); } try { this.seen.set(env.id, env); if (this.seen.size > SEEN_CAP) this.seen.delete(this.seen.keys().next().value as string); // fyi is for the record (console now, task board from M4), never worth an agent's turn. const dropped = env.hop > MAX_HOP ? "hop" : env.priority === "fyi" ? "fyi" : undefined; this.emit({ t: "envelope", env, ...(dropped ? { dropped } : {}) }); if (dropped) { this.persist(); return { targets: [], dropped }; } const hushed = this.hushed(env); if (hushed.length) this.emit({ t: "quiet", env, peers: hushed.map((h) => h.peer), reason: hushed[0]!.reason }); const targets = this.audience(env).filter((id) => !hushed.some((h) => h.peer === id) || !this.isRostered(id)); this.suppressDrain = !!this.journal; try { for (const id of targets) { const peer = this.peers.get(id); if (!peer) { this.enqueue(id, env); continue; } if (!this.journal && !this.held(id) && env.priority === "important" && !remoteId(id) && peer.steer && this.stateOf(id) === "busy" && !this.invocationTurnOpen(id)) { // Not queued while the steer is in flight, or an idle transition would deliver it a second time. try { this.beforeReviewInputHandoff(id, [env]); } catch { this.enqueue(id, env); continue; } this.steering++; const deliveryId = crypto.randomUUID(); this.activeDeliveries.set(deliveryId, id); if (this.journal) this.durableHandoff(id, deliveryId, [env], [env]); this.noteSteering(id, [env]); const steerResult = this.journal ? peer.steer([env], deliveryId) : peer.steer([env]); steerResult.then(() => { this.delivered(id, [env]); }).catch(() => { this.deliveryFailed(id); if (this.journal) this.journal.transition(deliveryId, "needs_review", "adapter steering outcome is uncertain", undefined, "push error"); this.activeDeliveries.delete(deliveryId); if (!this.journal) this.enqueue(id, env, true); }).finally(() => { this.steering--; }); } else this.enqueue(id, env); } } finally { this.suppressDrain = false; } if (this.journal) { this.persist(); if (!this.flushingHub) this.onQueues?.(); for (const id of targets) { const peer = this.peers.get(id); if (!this.held(id) && env.priority === "important" && !remoteId(id) && peer?.steer && this.stateOf(id) === "busy") void this.steerQueued(id, env); // steerQueued itself refuses to join an invocation's turn else void this.drain(id); } } const offRoster = targets.filter(id => !this.isRostered(id)); if (offRoster.length) this.emit({ t: "off_roster", env, peers: offRoster }); return { targets }; } finally { for (const room of rooms) { const reserved = this.remoteReservations.get(room); reserved?.delete(env.id); if (!reserved?.size) this.remoteReservations.delete(room); } } } isRostered(peer: PeerId): boolean { return this.opts.rostered?.(peer) ?? true; } /** Explicit off-roster recipients, including unattached retained targets; broadcasts have none. */ offRosterRecipients(env: Envelope): PeerId[] { return [...new Set(env.to ?? [])].filter(peer => peer !== env.from && !this.isRostered(peer)); } /** Membership changed externally: reconsider delivery, keeping every independent hold intact. */ rosterChanged(peer: PeerId): void { if (this.closed) return; this.onQueues?.(); void this.drain(peer); } /** Who an envelope is queued for: its `to`, or every peer but its sender. */ audience(env: Envelope): PeerId[] { const known = new Set([...this.peers.keys(), ...this.queues.keys(), ...(this.journal?.list().map((d) => d.peer) ?? [])]); return (env.to ?? [...this.peers.keys()]).filter((id) => id !== env.from && (known.has(id) || !this.isRostered(id)) && (env.to !== undefined || this.isRostered(id)) && (env.to !== undefined || !remoteId(id))); } /** The recipients of `env` that the silence policy holds it back from, each with why (issue #107). */ hushed(env: Envelope): { peer: PeerId; reason: string }[] { if (!this.opts.silence || env.hop > MAX_HOP || env.priority === "fyi") return []; return this.audience(env).filter(peer => this.isRostered(peer)).flatMap((peer) => { const reason = this.opts.silence!(env, peer); return reason ? [{ peer, reason }] : []; }); } /** A recently published envelope, for resolving `reply_to`. */ get(id: string): Envelope | undefined { return this.seen.get(id) ?? this.deferredHub.get(id); } /** Only newly saved versioned review packages may interpret absent as permission for explicit publication. */ reviewEnvelopeStatus(id: string): "published" | "absent" | "unknown" | "failed" | "discarded" { if (this.closed || this.storageError || !this.journal) return "unknown"; try { const state = this.journal.reviewEnvelopeState(id); if (state === "failed" || state === "discarded") return state; return state ? "published" : "absent"; } catch { return "unknown"; } } hasUnsettledReviewScope(peer: PeerId, task?: number): boolean { if (this.closed || this.storageError) return true; if (!this.journal) return false; // Ephemeral test buses retain the existing delivered-parent scope. try { const revision = this.journal.revision(); if (revision !== this.reviewScopeRevision) { this.reviewScopeCache.clear(); this.reviewScopeRevision = revision; } const key = JSON.stringify([peer, task ?? null]), cached = this.reviewScopeCache.get(key); if (cached !== undefined) return cached; const held = this.journal.hasUnsettledReviewScope(peer, task); this.reviewScopeCache.set(key, held); if (this.reviewScopeCache.size > 512) this.reviewScopeCache.delete(this.reviewScopeCache.keys().next().value!); return held; } catch { return true; } } /** Explicit recovery reuses the immutable package envelope; a durable publication is never replayed. */ publishReviewEnvelope(env: Envelope): PeerId[] { if (env.from !== HUB || env.kind !== "review" || !env.refs?.reviewPackage || !env.to?.length) throw new Error("review package envelope is invalid; refresh the saved package before retrying"); const status = this.reviewEnvelopeStatus(env.id); if (status === "published") { this.journal!.reviewEnvelopePublished(env.id, env); return [...env.to]; } if (status === "failed" || status === "discarded") throw new Error(`saved review package delivery is ${status}; inspect ahub queue list --peer ${env.to[0]} and ahub queue show before retrying`); if (status !== "absent") throw new Error("review package publication evidence is unavailable; inspect ahub queue list before retrying"); // A pre-checkpoint observer may have thrown after remembering the id but before any durable enqueue or native effect. this.seen.delete(env.id); return this.publish(env); } /** * #445 C2: whether the peer's current turn is one that holds an invocation request. With a journal that is a delivery of the peer's own that has not reached a * terminal receipt and whose payload holds the request (the receipt paths delete it from `activeDeliveries`); without one it is the peer being busy, which is the * best the bus can know (the daemon always has a journal). A steer is never sent into such a turn (the two steer sites and `steerQueued` ask this first): an adapter answers the highest-hop envelope of * everything its turn holds, and a steered one would become what the answer names instead of the request. */ private invocationTurnOpen(peer: PeerId): boolean { if (!this.journal) return this.stateOf(peer) === "busy" && [...(this.lastDelivery.get(peer)?.out ?? []), ...(this.lastPulled.get(peer)?.out ?? [])].some((e) => e.kind === "invocation"); for (const [deliveryId, owner] of this.activeDeliveries) { if (owner === peer && this.journal.get(deliveryId)?.out.some((e) => e.kind === "invocation")) return true; } return false; } /** The envelopes most recently handed to a peer, used to distinguish a received request from an unread queue. */ lastDeliveredTo(peer: PeerId): Envelope[] { return this.lastPulled.get(peer)?.out ?? this.lastDelivery.get(peer)?.out ?? []; } /** A confirmed new native session invalidates only this session's current-input cache; durable named-parent rows remain. */ resetLastDelivery(peer: PeerId): void { this.lastDelivery.delete(peer); this.lastPulled.delete(peer); } /** * Take back an envelope that has not been delivered yet (a request that has expired). True when it was removed from a * queue now; an envelope whose steer is still in flight is not in any queue, so its id is remembered and it is * dropped if the refused steer tries to queue it later. */ withdraw(envelopeId: string): boolean { this.markWithdrawn(envelopeId); let removed = this.deferredHub.delete(envelopeId); for (const queue of this.queues.values()) { const i = queue.findIndex((e) => e.id === envelopeId); if (i !== -1) { queue.splice(i, 1); removed = true; } } if (removed) this.onQueues?.(); this.persist(); return removed; } /** Revoke pending feed copies only; accepted/dispatching journal records and native turns are untouched. */ revokeSupervision(peer: PeerId): number { const queue = this.queues.get(peer); let removed = 0; for (const [id, env] of this.deferredHub) { if (!env.refs?.supervision || !env.to?.includes(peer)) continue; const remaining = env.to.filter(target => target !== peer); if (remaining.length) this.deferredHub.set(id, { ...env, to: remaining }); else this.deferredHub.delete(id); removed++; } if (!queue && !this.preparing.has(peer)) { if (removed) this.persist(); return removed; } const discarded = new Set(); for (let i = (queue?.length ?? 0) - 1; i >= 0; i--) { const env = queue![i]!; if (env.from !== HUB || !env.refs?.supervision) continue; queue!.splice(i, 1); removed++; discarded.add(env.id); this.markWithdrawn(env.id); this.discardQueued(peer, env, "supervision role or feed revoked"); } for (const env of this.preparing.get(peer) ?? []) { if (env.from !== HUB || !env.refs?.supervision || discarded.has(env.id)) continue; this.markWithdrawn(env.id); this.discardQueued(peer, env, "supervision role or feed revoked during preparation"); removed++; } if (removed) { this.persist(); this.onQueues?.(); } return removed; } private discardQueued(peer: PeerId, env: Envelope, reason: string): void { if (this.journal) this.pendingOutcomes.push({ id: crypto.randomUUID(), peer, state: "discarded", createdAt: Date.now(), originals: [env], out: [], reason }); this.emit({ t: "stale", env, peer, reason }); } private memoryDelivery(peer: PeerId, id: string, out: Envelope[], field: "rendered" | "delivered", originals: Envelope[] = out): void { if (remoteId(peer) || this.opts.reviewObserverInputExcluded?.(peer, originals) === true || [...out, ...originals].some(env => isReviewObserverExcluded(env) || env.private || remoteId(env.from) || env.to?.some(remoteId))) return; try { this.onMemoryDelivery?.(peer, id, out, field); } catch { /* optional telemetry never alters delivery */ } } private rememberReviewParents(peer: PeerId, originals: Envelope[], requireAttached = true): void { for (const env of originals) if ((!requireAttached || !this.closed && this.peers.has(peer) && this.stateOf(peer) !== "offline") && isReviewObserverExcluded(env)) { const parents = this.reviewParents.get(peer) ?? new Map(); parents.set(env.id, (env.refs?.reviewPackage ?? env.refs?.reviewResponse)!); if (parents.size > 128) parents.delete(parents.keys().next().value!); this.reviewParents.set(peer, parents); } } private delivered(peer: PeerId, originals: Envelope[], deliveryId?: string): void { this.rememberReviewParents(peer, originals); try { this.onDelivered?.(peer, originals, deliveryId); } catch { /* observation must never affect delivery settlement */ } } private deliveryFailed(peer: PeerId): void { try { this.onDeliveryFailed?.(peer); } catch { /* observation must never affect delivery settlement */ } } private noteSteering(peer: PeerId, originals: Envelope[]): void { try { this.onSteering?.(peer, originals); } catch { /* metadata observation cannot alter the steer attempt */ } } private beforeReviewInputHandoff(peer: PeerId, originals: Envelope[]): void { try { this.opts.beforeReviewInputHandoff?.(peer, originals); } catch { throw new ReviewInputHandoffError(); } } private markWithdrawn(id: string): void { this.withdrawn.add(id); if (this.withdrawn.size > 256) this.withdrawn.delete(this.withdrawn.values().next().value as string); } queued(id: PeerId): number { return this.queues.get(id)?.length ?? 0; } /** New automatic offers use only bounded pending metadata, never queue/history bodies. */ assignmentQueue(peer: PeerId): QueuePressure { const queued = this.queued(peer), tracking = this.trackingQueuePressure(); if (this.storageError) return { queued }; if (queued === 0) return { queued: 0, oldestQueuedAt: null }; if (!tracking) return { queued }; // A durable summary cannot revive provenance that this host discarded while tracking was off. const times = this.queueTimes.get(peer); let oldest: number | undefined; for (const env of this.queues.get(peer) ?? []) { const at = times?.get(env.id); if (typeof at !== "number" || !Number.isSafeInteger(at) || at <= 0) return { queued }; oldest = oldest === undefined ? at : Math.min(oldest, at); } if (this.journal) { try { const saved = this.journal.pendingQueueMetadata(peer); return saved?.queued === queued ? saved : { queued }; } catch { return { queued }; } } return oldest === undefined ? { queued } : { queued, oldestQueuedAt: oldest }; } private trackingQueuePressure(): boolean { let tracking = false; try { tracking = this.opts.trackQueuePressure?.() === true; } catch { /* unknown policy is not enabled */ } if (!tracking && this.queuePressureWasTracked) { this.queueTimes.clear(); this.queueTimeEntries = 0; } this.queuePressureWasTracked = tracking; this.journal?.setQueueMetadataTracking(tracking); return tracking; } private recordQueueTime(peer: PeerId, id: string, at: number | null): void { if (!this.trackingQueuePressure()) return; let times = this.queueTimes.get(peer); if (!times) { if (this.queueTimes.size >= QUEUE_TIME_PEERS_CAP) this.dropQueueTimes(this.queueTimes.keys().next().value!); this.queueTimes.set(peer, times = new Map()); } if (!times.has(id)) { times.set(id, at); this.queueTimeEntries++; } while (times.size > QUEUE_TIME_CAP) { times.delete(times.keys().next().value!); this.queueTimeEntries--; } while (this.queueTimeEntries > QUEUE_TIME_TOTAL_CAP) this.dropQueueTimes(this.queueTimes.keys().next().value!); } private dropQueueTimes(peer: PeerId): void { this.queueTimeEntries -= this.queueTimes.get(peer)?.size ?? 0; this.queueTimes.delete(peer); } /** * Queued envelopes that skip the batch window (issue #41: `queued 3` hid which ones the peer still waits out). * An `important` envelope that is in a queue is one that could not be steered, so it does not interrupt a * running turn; it is why the queue is delivered the moment the peer goes idle. */ queuedImportant(id: PeerId): number { return (this.queues.get(id) ?? []).filter((e) => e.priority === "important").length; } /** The oldest `important` envelope still waiting in a queue, for the busy-peer notice (#572 AC1); a read, never a delivery. */ oldestQueuedImportantAt(id: PeerId): number | undefined { return (this.queues.get(id) ?? []).reduce((oldest, e) => e.priority !== "important" ? oldest : oldest === undefined ? e.ts : Math.min(oldest, e.ts), undefined); } private enqueue(id: PeerId, env: Envelope, front = false): void { if (this.withdrawn.has(env.id)) return; const queue = this.queues.get(id) ?? []; this.queues.set(id, queue); // #713: a newer "task T is done, check your work" notice for this recipient replaces an earlier queued one for the same T: only the newest is useful, and the older // one is discarded through the same stale/discard path with a journal outcome. Never one that already failed once or is being prepared, as for supervision. const completedFor = env.from === HUB && env.kind === "task" && Number.isSafeInteger(env.refs?.completedFor) ? env.refs!.completedFor : undefined; if (!front && completedFor !== undefined) { for (let i = queue.length - 1; i >= 0; i--) { const old = queue[i]!; if (old.from !== HUB || old.refs?.completedFor !== completedFor || this.attempts.has(`${id}:${old.id}`)) continue; queue.splice(i, 1); this.markWithdrawn(old.id); this.discardQueued(id, old, `superseded completed-change notice for task #${completedFor}`); } } const key = env.from === HUB && env.refs?.supervision ? env.refs.supervisionKey : undefined; const replace = !front && key ? queue.findIndex((old) => old.from === HUB && old.refs?.supervision && old.refs.supervisionKey === key && !this.attempts.has(`${id}:${old.id}`)) : -1; const preparing = !front && key ? this.preparing.get(id)?.find((old) => old.from === HUB && old.refs?.supervision && old.refs.supervisionKey === key && !this.attempts.has(`${id}:${old.id}`) && !this.withdrawn.has(old.id)) : undefined; let queuedEnv = preparing ? { ...env, ts: Math.min(preparing.ts, env.ts) } : env; const clock = this.trackingQueuePressure() ? Date.now() : 0; let enteredAt = this.queueTimes.get(id)?.has(env.id) ? this.queueTimes.get(id)!.get(env.id)! : front || this.flushingHub || !Number.isSafeInteger(clock) || clock <= 0 ? null : clock; if (this.trackingQueuePressure() && !this.queueTimes.get(id)?.has(env.id) && queue.some(old => old.id === env.id)) enteredAt = null; if (preparing) enteredAt = this.queueTimes.get(id)?.get(preparing.id) ?? null; if (replace >= 0) { const old = queue[replace]!; enteredAt = this.queueTimes.get(id)?.get(old.id) ?? null; // Keep the first milestone's deadline, so continuous updates cannot create another batching window. queuedEnv = { ...queuedEnv, ts: Math.min(old.ts, queuedEnv.ts) }; queue[replace] = queuedEnv; this.markWithdrawn(old.id); this.discardQueued(id, old, "superseded supervision milestone"); } else if (front) queue.unshift(queuedEnv); else queue.push(queuedEnv); this.recordQueueTime(id, queuedEnv.id, enteredAt); if (preparing && !this.withdrawn.has(preparing.id)) { this.markWithdrawn(preparing.id); this.discardQueued(id, preparing, "superseded supervision milestone during preparation"); } if (!remoteId(id) && queue.length > this.opts.queueCap) { const victim = queue.findIndex((e) => e.priority !== "important"); const [lost] = queue.splice(victim === -1 ? 0 : victim, 1); if (this.journal) this.pendingOutcomes.push({ id: crypto.randomUUID(), peer: id, state: "failed", createdAt: Date.now(), originals: [lost!], out: [], reason: "queue capacity exceeded", failureCause: "adapter refused" }); this.emit({ t: "overflow", env: lost!, peer: id }); } if (remoteId(id) && !front) { const room = this.peers.get(id)?.remoteRoom; if (room !== undefined) this.remoteQueueRooms.set(id, room); const member = this.peers.get(id)?.remoteMember; if (member !== undefined) this.remoteQueueMembers.set(id, member); const expiries = this.remoteQueueExpires.get(id) ?? new Map(); if (!expiries.has(env.id)) expiries.set(env.id, Date.now() + (this.peers.get(id)?.remoteQueueTtlMs ?? REMOTE_QUEUE_TTL_MS)); this.remoteQueueExpires.set(id, expiries); } if (queuedEnv.priority === "important" && this.peers.get(id)?.pullOnly) { // Advisory only (issue #398): the envelope stays queued for `pull`; the hook must never affect it. const counts = { queued: queue.length, important: queue.filter((e) => e.priority === "important").length }; const nudge = () => { try { this.opts.onImportantQueued?.(id, counts); } catch { /* a nudge never stops an enqueue */ } }; if (this.flushingHub) this.deferredNudges.push(nudge); else nudge(); } if (!this.flushingHub) this.onQueues?.(); if (!this.suppressDrain) this.persist(); if (!this.suppressDrain) void this.drain(id); } /** 0 = deliver now; otherwise how long the oldest envelope still has to wait for company. */ private wait(queue: Envelope[]): number { const supervisionOnly = queue.every((e) => e.from === HUB && e.refs?.supervision && e.priority === "status"); if ((!supervisionOnly && queue.length >= this.opts.batchMax) || queue.some((e) => e.priority === "important")) return 0; return Math.max(0, queue[0]!.ts + this.opts.batchMs - Date.now()); } private uncertain(peer: PeerId, deliveryId: string, reason: string, failureCause: DeliveryFailureCause = "push error"): void { const row = this.journal?.get(deliveryId); if (row && ["dispatching", "accepted"].includes(row.state)) this.deliveryReceipt(peer, { id: deliveryId, state: "needs_review", reason, failureCause }); } private async steerQueued(id: PeerId, env: Envelope): Promise { const peer = this.peers.get(id); const queue = this.queues.get(id); if (!this.journal || !peer?.steer || !queue || this.storageError) return; // #445 C2: an invocation's turn answers the request alone. Joining it with a steer would change what its answer names, so the envelope waits in the queue for the next delivery. if (this.invocationTurnOpen(id)) { void this.drain(id); return; } const index = queue.findIndex((item) => item.id === env.id); if (index < 0) return; this.steering++; const deliveryId = crypto.randomUUID(); let removed = false, handedOff = false; try { const out = this.retryOut(id, [env], [env]); this.beforeReviewInputHandoff(id, [env]); queue.splice(index, 1); removed = true; this.durableHandoff(id, deliveryId, [env], out); handedOff = true; this.activeDeliveries.set(deliveryId, id); this.noteSteering(id, [env]); try { await peer.steer(out, deliveryId); } catch { this.uncertain(id, deliveryId, "steering outcome is uncertain"); } } catch (error) { if (removed && !handedOff) queue.splice(index, 0, env); if (!(error instanceof ReviewInputHandoffError)) this.storageError = "delivery journal unavailable"; } finally { this.steering--; this.onQueues?.(); } } /** Holds on a peer's queue, for a drain and a pull alike: off roster, recovery, an uncertain delivery, a pause (console, budget, conductor). */ /** #445 C2: whether a delivery to this peer would wait on a hold (roster, recovery, pause or a lifecycle fence). */ isHeld(id: PeerId): boolean { return this.held(id); } private held(id: PeerId): boolean { return !this.isRostered(id) || this.recoveryHeld || this.recoveryHeldPeers.has(id) || this.paused.has(id) || this.opts.deliveryHeld?.(id) === true; } /** What a peer was just handed stays resolvable for `reply_to`: moved to the newest end, the stored envelope kept. */ private remember(envs: Envelope[]): void { for (const e of envs) { const kept = this.seen.get(e.id) ?? e; this.seen.delete(e.id); this.seen.set(e.id, kept); } while (this.seen.size > SEEN_CAP) this.seen.delete(this.seen.keys().next().value as string); } /** A push may go out now: nothing holds the queue, the peer is idle, and its session shows pushes (issue #205). */ private deliverable(id: PeerId): boolean { const peer = this.peers.get(id); const remoteBinding = !remoteId(id) || !!peer?.remoteRoom && this.remoteQueueRooms.get(id) === peer.remoteRoom && this.remoteQueueMembers.get(id) === peer.remoteMember; return remoteBinding && !this.held(id) && this.stateOf(id) === "idle" && !peer?.pullOnly; } /** * What one push delivery would take (the preface, then `take`'s batch), explicitly pulled by its attached session and recorded as * completed: the tool result that returns it is the readback, so nothing waits for settlement and nothing is ever * `accepted` (issue #205). It is checkpointed like a push, so queued rows of the same envelopes (an operator retry) * are grouped into it, and registered for `reply_to` like a push. Undefined while held. A failed journal write puts * back only this peer's queue and preface (every pause stays) and stops the bus like any other journal failure. * ponytail: recorded completed at hand-out, before anything shows the model saw it: a reply lost on the way, a tool * call cancelled (Esc) or a plugin that dies loses the batch, and `ahub queue resolve --action retry` refuses a * terminal row. The completed row keeps the envelopes (`ahub queue show `) to resend by hand; take/confirm in two * steps if loss is ever observed. */ pull(id: PeerId, options: { allowNeedsReviewHold?: boolean } = {}): Envelope[] | undefined { if (remoteId(id)) return undefined; // A local inbox read is not signed remote queue admission. if (this.storageError) throw new Error("delivery journal unavailable"); if (this.held(id) && !(options.allowNeedsReviewHold === true && this.pullMayReadBehindNeedsReview(id))) return undefined; const queue = this.queues.get(id) ?? []; this.dropIrrelevant(id, queue); const preface = this.prefaces.get(id); if (!preface && !queue.length) return []; const queued = [...queue]; // A pull-only peer drains within a byte budget (oldest first, important ones marked as they always were); an attached channel session that pulls keeps one push's worth (#493). const batch = [...(preface ? [preface] : []), ...(this.peers.get(id)?.pullOnly ? this.takeBudget(id, queue) : this.take(id, queue))]; let out: Envelope[] = []; const deliveryId = crypto.randomUUID(); try { out = this.retryOut(id, batch, batch); this.beforeReviewInputHandoff(id, batch); this.prefaces.delete(id); // Before the checkpoint, as in a drain, so the persisted snapshot carries it; a failed policy read rolls back too. this.remember(out); this.journal?.transaction(() => { this.durableHandoff(id, deliveryId, batch, out, false); // observe only after this outer transaction commits this.journal!.completeDelivered(deliveryId, id, "pull", "read through hub_inbox"); }); } catch (error) { queue.splice(0, queue.length, ...queued); if (preface) this.prefaces.set(id, preface); if (!(error instanceof ReviewInputHandoffError)) this.storageError = "delivery journal unavailable"; throw error; } if (this.journal) { this.memoryDelivery(id, deliveryId, out, "rendered", batch); this.memoryDelivery(id, deliveryId, out, "delivered", batch); } this.lastPulled.set(id, { out, originals: batch }); this.rememberReviewParents(id, batch, false); if (batch.length) { try { this.onPulled?.(id, batch); } catch { /* metadata observation cannot change a committed inbox result */ } } this.failureStreak.delete(id); this.lastFailure.delete(id); // read, as a completed push receipt clears them try { this.onQueues?.(); } catch { /* a committed inbox result must still reach its caller */ } return out; } /** Explicit inbox reads may pass only a needs_review hold; every other recovery fence still blocks. */ private pullMayReadBehindNeedsReview(id: PeerId): boolean { if (!this.journal || this.closed || this.storageError || !this.isRostered(id) || this.recoveryHeld || this.paused.has(id) || this.opts.deliveryHeld?.(id) === true) return false; if (this.pendingOutcomes.some(row => row.peer === id)) return false; const unresolved = this.journal.unresolved(id); return unresolved.some(row => row.state === "needs_review") && unresolved.every(row => row.state === "needs_review" || row.state === "queued"); } private async drain(id: PeerId): Promise { if (this.storageError || this.draining.has(id) || !this.peers.has(id)) return; if (remoteId(id)) this.expireRemoteQueues(); this.draining.add(id); try { const peer = this.peers.get(id)!; const queue = this.queues.get(id)!; while (!this.storageError && queue.length && this.deliverable(id)) { if (this.dropIrrelevant(id, queue) && !queue.length) break; const delay = remoteId(id) ? 0 : this.wait(queue); if (delay > 0) { this.arm(id, delay); break; } const preface = remoteId(id) ? undefined : this.prefaces.get(id); // Durable queues retain the batch while asynchronous condensation runs. Another publish // may checkpoint during that wait; it must not checkpoint the batch out of existence. if (!this.journal) this.prefaces.delete(id); const batch = this.take(id, queue, !this.journal); this.preparing.set(id, batch); const delivery = preface ? [preface, ...batch] : batch; const mayCondense = this.opts.condense && !remoteId(id) && !delivery.some((e) => e.priority === "important" || remoteId(e.from)); this.condensing += mayCondense ? 1 : 0; let out: Envelope[]; try { const condensed = mayCondense ? await this.opts.condense!(delivery).catch(() => delivery) : delivery; out = this.retryOut(id, delivery, condensed); } finally { this.condensing -= mayCondense ? 1 : 0; } // #1447: the batch is still preparation, not a started native turn. Urgent work // queued during condensation must participate in the next take, ahead of chat. if (mayCondense && queue.some(env => env.priority === "important")) { if (!this.journal) { if (preface) this.restorePreface(id, preface); queue.unshift(...batch.filter(env => !this.withdrawn.has(env.id))); } continue; } // A session that cannot show pushes may have taken the peer while this was condensed (issue #205). if (!this.deliverable(id)) { if (!this.journal) { if (preface) this.restorePreface(id, preface); queue.unshift(...batch.filter((e) => !this.withdrawn.has(e.id))); } break; } // The final recheck (issue #106): a task can close while the delivery was condensed or prepared. if (batch.some((e) => !this.isRelevant(id, e))) { if (!this.journal) { if (preface) this.restorePreface(id, preface); queue.unshift(...batch.filter((e) => !this.withdrawn.has(e.id))); } this.dropIrrelevant(id, queue); continue; } const deliveryId = crypto.randomUUID(); if (this.journal) { if ((!remoteId(id) && this.prefaces.get(id) !== preface) || batch.some((e) => !queue.some((item) => item.id === e.id))) continue; this.beforeReviewInputHandoff(id, delivery); const queued = [...queue], seen = [...this.seen]; for (const env of batch) queue.splice(queue.findIndex((item) => item.id === env.id), 1); this.prefaces.delete(id); this.remember(out); // the checkpoint must retain rendered reply ids across a restart try { this.durableHandoff(id, deliveryId, delivery, out); } catch (error) { queue.splice(0, queue.length, ...queued); if (preface) this.prefaces.set(id, preface); this.seen.clear(); for (const [key, env] of seen) this.seen.set(key, env); throw error; } this.activeDeliveries.set(deliveryId, id); } else { try { this.beforeReviewInputHandoff(id, delivery); } catch (error) { if (preface) this.restorePreface(id, preface); queue.unshift(...batch.filter(e => !this.withdrawn.has(e.id))); throw error; } this.remember(out); } this.lastPulled.delete(id); this.lastDelivery.set(id, { out, originals: delivery }); for (const env of delivery) if (env.kind === "invocation") this.invocationDeliveries.set(env.id, deliveryId); if (remoteId(id)) this.remoteTransport.set(deliveryId, { peer: id, originals: delivery }); this.preparing.delete(id); // from here on the transport/journal owns settlement try { if (remoteId(id)) { const env = delivery[0], expiry = env && this.remoteQueueExpires.get(id)?.get(env.id); if (!env || delivery.length !== 1 || expiry === undefined || expiry <= Date.now() || !peer.setRemoteDeadline) throw new Error("remote queue deadline unavailable"); peer.setRemoteDeadline(env.id, expiry); } try { this.onDeliver?.(id, delivery); } catch { /* observation must never affect delivery */ } if (this.journal) await peer.deliver(out, deliveryId); else { await peer.deliver(out); this.delivered(id, delivery); } } catch { if (this.journal) this.uncertain(id, deliveryId, "adapter delivery outcome is uncertain"); else if (delivery.some(env => env.kind === "invocation")) { this.recoveryHeldPeers.add(id); for (const env of delivery) if (env.kind === "invocation") this.onInvocationUncertain?.(env.id); } else this.failed(id, delivery); break; } finally { this.remoteTransport.delete(deliveryId); } } } catch (error) { if (!(error instanceof ReviewInputHandoffError)) this.storageError = "delivery journal unavailable"; } finally { this.preparing.delete(id); this.draining.delete(id); this.onQueues?.(); } } private isRelevant(id: PeerId, env: Envelope): boolean { return this.irrelevance(id, env) === undefined; } /** Why a queued envelope no longer goes to `id`, or undefined when it still does. */ private irrelevance(id: PeerId, env: Envelope): string | undefined { const verdict = this.withdrawn.has(env.id) ? false : this.opts.relevant?.(id, env) ?? true; return verdict === true ? undefined : typeof verdict === "string" ? verdict : `stale: task #${env.refs?.task ?? "?"} is no longer open for ${id}`; } /** * A notice about the recipient's open task can wait out a whole Codex turn; once the task is closed it would only * start a turn of its own (issue #106). Checked when the delivery is built, not when the notice was published. Only * this recipient's copy goes: the other queues keep theirs, and no other delivery record changes. */ private dropIrrelevant(id: PeerId, queue: Envelope[]): boolean { if (!this.opts.relevant && !this.withdrawn.size) return false; let dropped = false; for (let i = queue.length - 1; i >= 0; i--) { const env = queue[i]!; const reason = this.irrelevance(id, env); if (reason === undefined) continue; queue.splice(i, 1); dropped = true; if (this.journal) this.pendingOutcomes.push({ id: crypto.randomUUID(), peer: id, state: "discarded", createdAt: Date.now(), originals: [env], out: [], reason }); this.emit({ t: "stale", env, peer: id, reason }); } if (dropped) { this.persist(); this.onQueues?.(); } return dropped; } /** * The next delivery: important envelopes first (they are why the queue is ready), then the rest in order. * An envelope that already failed once goes alone, so a poison one cannot take a digest down with it. */ private take(id: PeerId, queue: Envelope[], remove = true): Envelope[] { const digestMax = this.opts.digestMax?.() ?? DIGEST_MAX; const ordered = [...queue.filter((e) => e.priority === "important"), ...queue.filter((e) => e.priority !== "important")]; const batch: Envelope[] = []; for (const env of ordered) { const failedBefore = this.attempts.has(`${id}:${env.id}`); if (failedBefore && batch.length) break; // #445 C2: an invocation or its result goes alone, so the reply to the turn answers exactly one of them. if (isInvocationKind(env) && batch.length) break; batch.push(env); if (failedBefore || remoteId(id) || batch.length === digestMax || isInvocationKind(env)) break; } if (remove) for (const env of batch) queue.splice(queue.indexOf(env), 1); return batch; } /** * #713: what one pull hands a pull-only peer. Oldest first, so the oldest ordinary item is never kept behind newer important ones (the push order is important * first; a pull is a catch-up). The budget counts each item's rendered bytes as the peer will read them (`frame`), and the first item always goes, so one huge * envelope cannot stall the queue. An envelope that already failed once still goes alone, as in `take`. */ private takeBudget(id: PeerId, queue: Envelope[]): Envelope[] { const pullBudgetBytes = this.opts.pullBudgetBytes?.() ?? PULL_BUDGET_BYTES; const batch: Envelope[] = []; let bytes = 0; for (const env of queue) { const failedBefore = this.attempts.has(`${id}:${env.id}`); if (failedBefore && batch.length) break; const size = Buffer.byteLength(frame(env)) + 2; if (batch.length && bytes + size > pullBudgetBytes) break; if (isInvocationKind(env) && batch.length) break; // #445 C2: alone, as in `take` batch.push(env); bytes += size; if (failedBefore || isInvocationKind(env)) break; } for (const env of batch) queue.splice(queue.indexOf(env), 1); return batch; } private arm(id: PeerId, ms: number): void { clearTimeout(this.timers.get(id)); const timer = setTimeout(() => void this.drain(id), ms); timer.unref?.(); this.timers.set(id, timer); } /** At-least-once: back to the queue head and retried after a pause; given up after MAX_ATTEMPTS so one poison envelope cannot block the peer. */ /** Delivery health is independent of task outcome: only a completed delivery clears the streak. */ failingPeers(): Record { return Object.fromEntries([...this.failureStreak].filter(([, n]) => n >= 3).map(([peer]) => [peer, this.lastFailure.get(peer) ?? "delivery retries exhausted"])); } hasInFlight(peer: PeerId): boolean { return [...this.activeDeliveries.values()].includes(peer) || this.draining.has(peer); } private failed(id: PeerId, envs: Envelope[], reason = "delivery failed without an error detail", quota = false): void { const maxAttempts = this.opts.maxAttempts?.() ?? MAX_ATTEMPTS; if (!this.journal) this.deliveryFailed(id); // A quota refusal ran no work. The budget pause fences retries until reset; it is not a poison attempt. const quotaPaused = quota && this.paused.has(id); this.lastFailure.set(id, reason.replace(/\s+/g, " ").slice(0, 300)); if (!quotaPaused && envs.some((env) => !(env.from === HUB && env.kind === "presence") && (this.attempts.get(`${id}:${env.id}`) ?? 0) + 1 >= maxAttempts)) { this.failureStreak.set(id, (this.failureStreak.get(id) ?? 0) + 1); } const keep = envs.filter((env) => { // Only the recall block is a preface. The hub also sends task and review envelopes, and those are retried like any other. if (env.from === HUB && env.kind === "presence") { this.restorePreface(id, env); // rides again on the next delivery, without counting as a failed envelope return false; } if (env.kind === "invocation") { const key = `${id}:${env.id}`, n = (this.attempts.get(key) ?? 0) + 1; let read = false; try { read = this.canRetryInvocation?.(env.id) === true; } catch { /* Unknown refuses replay. */ } if (read && n < 2) { this.attempts.set(key, n); return true; } this.attempts.delete(key); this.emit({ t: "undeliverable", env, peer: id, reason: "invocation safe delivery refusal; no further automatic retry" }); return false; } if (quotaPaused) return true; const key = `${id}:${env.id}`; const n = (this.attempts.get(key) ?? 0) + 1; if (n < maxAttempts) return this.attempts.set(key, n); this.attempts.delete(key); this.emit({ t: "undeliverable", env, peer: id, reason: this.lastFailure.get(id) }); return false; }); this.queues.get(id)!.unshift(...keep); this.persist(); // The idle transition caused by the failure itself may have been swallowed by the `draining` guard. this.arm(id, this.opts.retryMs); } private emit(e: BusEvent): void { if (this.flushingHub) { this.deferredEvents.push(e); return; } if ("env" in e && (remoteEnvelope(e.env) || e.env.to?.some(remoteId) || ("peer" in e && remoteId(e.peer)))) { const { refs: _, ...env } = e.env; e = { ...e, env: { ...env, body: "[remote room message withheld]", ...(env.to ? { to: env.to.filter(id => /^[a-z][a-z0-9-]{0,31}$/.test(id) || !!parseRemotePeerId(id)) } : {}) }, ...("reason" in e ? { reason: "remote room delivery" } : {}) }; } for (const tap of this.taps) tap(e); } }