From 2c16d57fcc055cd67c6a0794f1daf84f0d9fe721 Mon Sep 17 00:00:00 2001 From: Keaton Hoskins Date: Mon, 2 Nov 2026 09:11:21 -0800 Subject: [PATCH 1/3] fix(T765): auto-close informational mail on read; remind unanswered work mail at 30 min, alert the lead at 2 h OpenCode agents opened requests within seconds and never replied or acked; the read-but-unacked reminder ran only on a prompt hook, which OpenCode lacks. 70% of read-but-unacked mail was status/reply asking for nothing. - message/reply/status without needs_reply or owner authority acks as 'auto: read' on a full read; the daemon sweep closes the backlog and older-connector reads (metadata-only reads stay open) - work mail read 30+ min ago with no reply or ack is named by id at the next prompt and at Stop - 2 h unanswered: one alert per message to the project lead; the copy's note 'unanswered' shows in receipts - agentmbx read marks mail read like mbx_read Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 +++ skill/SKILL.md | 5 +- src/cli.ts | 16 +++++- src/mcp.ts | 8 +-- src/node.ts | 13 +++-- src/unanswered.ts | 86 +++++++++++++++++++++++++++++ src/wake.ts | 13 +++-- test/hook-stop-read.test.ts | 26 +++++++++ test/hud-new-vs-read.test.ts | 4 +- test/message-prefix.test.ts | 2 +- test/project-mailbox-mcp.test.ts | 2 +- test/project-mailbox.test.ts | 3 +- test/unanswered.test.ts | 93 ++++++++++++++++++++++++++++++++ 13 files changed, 255 insertions(+), 22 deletions(-) create mode 100644 src/unanswered.ts create mode 100644 test/unanswered.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f3c5ec1..8133709b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +- **Mail you read and set aside no longer goes quiet (T765, owner decision 2026-11-02).** Agents, mostly in OpenCode, opened requests within seconds and then never replied or acked: axiom-lab-dev had 15 requests and tasks from Oct 28 to 29 still waiting. The "read, not acked" reminder only ran on a prompt hook, and OpenCode has none. Meanwhile 70% of all read-but-unacked mail (961 of 1,371) was status or reply mail that asked for nothing. Now: + - **Informational mail closes when read.** A full read of message, reply or status mail with no needs_reply and no owner authority acks it as `auto: read` (one `auto_ack` audit row per read). The daemon closes the existing backlog, and reads by older connectors, the same way; a metadata-only read (no content shown) stays open. + - **Work mail is reminded at 30 min.** A request, task, decision, alert or needs_reply message read 30+ minutes ago with no reply and no ack is named by id at the next prompt, and before the session goes idle (the Stop hook, which OpenCode does run). At most once per 30 minutes per session. + - **The lead hears at 2 h.** Unanswered 2 hours after the read, the agent's project lead gets one alert per message (ids and senders, never content), and the sender's receipt shows the copy as `unanswered`. + - `agentmbx read` (the CLI fallback) now marks mail read like `mbx_read`. + ## 0.5.55 (2026-10-28) - **Mail between your own agents is trusted (T754, owner decision 2026-10-28).** Before, reading any message marked external fenced the reader's whole session for an hour: every send became external, and recipients could only read it. The fence then spread through replies across teams. In the 7 days before this change, 57% of all mail carried the label, and 92% of that was inherited, with no outside content involved. Now: diff --git a/skill/SKILL.md b/skill/SKILL.md index 8d2b327e..e4835e8d 100644 --- a/skill/SKILL.md +++ b/skill/SKILL.md @@ -28,7 +28,10 @@ the running AgentMBX; the installed skill refreshes itself on upgrade. Send vs reply: to answer a message use `mbx_reply {id, body}`; `mbx_send` starts a new thread (`to` + `subject`, one line ≤200 characters). -Lifecycle: new → notified (a wake or a notice was sent) → read → acked. Only `mbx_ack` clears it. Bodies are at most 256 KB. +Lifecycle: new → notified (a wake or a notice was sent) → read → acked. Bodies are at most 256 KB. +Message, reply and status mail that asks for nothing (no needs_reply) is acked for you when you read it in full; don't ack it. +Requests, tasks, decisions, alerts and needs_reply mail stay open until you reply or `mbx_ack` with `did`: after 30 min +you are reminded by id, and after 2 h your project lead is told (T765). Declining is an answer: ack with did="declined: why". ## Startup and resume diff --git a/src/cli.ts b/src/cli.ts index 44728a68..ccb7426c 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -28,6 +28,7 @@ import { readStdin, stdinIsTTY } from "./stdin.ts"; import { runStatuslineSuggest } from "./statusline-suggest.ts"; import { assertKnownRecipients, offlineWarnings, recipientReceipts } from "./receipts.ts"; import { escalateUnheldMail, retirePhantoms, returnNeverClaimed } from "./stranded.ts"; +import { sweepUnanswered, unansweredReminder } from "./unanswered.ts"; import { activeLead, leadSummary, makeLead, makeLeadRevocation, projectLeadLine, projectLeadView, revokeLead, storeLead } from "./project-ledger.ts"; import { leadHistory } from "./lead-record.ts"; import { DEFAULT_PORT, defaultHome, didWarning, formatFor, messageReadView, MbxNode, summaryLine, trustLabel, WAKE_KINDS, type SendProvenanceScope } from "./node.ts"; @@ -747,6 +748,7 @@ async function run(argv: string[]) { case "read": { const row = node.read(pos[0] ?? die("read "), me), readMode = mode as "full" | "metadata" | "quarantine"; node.observeRead(row, descriptor.cli, descriptor.session_id, readMode); + node.markRead([row], me, { mode: readMode }); // T765: the CLI fallback reads like mbx_read const scope = { cli: descriptor.cli, session_id: descriptor.session_id }; const view = readMode === "full" ? null : messageReadView(node, row, me, readMode, Date.now(), scope); return console.log(view ? JSON.stringify(view) : formatFor(node, row, me, scope)); @@ -1098,7 +1100,7 @@ If the codes differ, do not approve: someone is in the middle.`); let lastAddrs = addrSignature(node), lastBeacon = 0; const beacon = () => { const sig = addrSignature(node); if (sig !== lastAddrs || Date.now() - lastBeacon > 300_000) { lastAddrs = sig; lastBeacon = Date.now(); void sendPresence(node).catch(() => {}); } }; setInterval(beacon, 10_000).unref(); setTimeout(() => { lastBeacon = 0; beacon(); }, 2_000).unref(); - setInterval(() => { void refreshDirectory(node); void pullPolicies(node); void refreshPeerEncKeys(node); void healStuckPeers(node, () => browse(3_000)).then(() => sendPresence(node, fetch, stuckHosts(node))).catch(() => {}); try { node.pruneDeadSessions(); } catch { /* db busy: next minute */ } try { node.sweepStaleRows(); } catch { /* db busy: next minute */ } try { node.expirePendingPeers(); } catch { /* db busy: next minute */ } try { escalateUnheldMail(node, Date.now(), (subtitle, body) => void notifyDesktop({ subtitle, body })); } catch { /* db busy: next minute */ } }, 60_000); void refreshDirectory(node); void pullPolicies(node); void refreshPeerEncKeys(node); + setInterval(() => { void refreshDirectory(node); void pullPolicies(node); void refreshPeerEncKeys(node); void healStuckPeers(node, () => browse(3_000)).then(() => sendPresence(node, fetch, stuckHosts(node))).catch(() => {}); try { node.pruneDeadSessions(); } catch { /* db busy: next minute */ } try { node.sweepStaleRows(); } catch { /* db busy: next minute */ } try { node.expirePendingPeers(); } catch { /* db busy: next minute */ } try { escalateUnheldMail(node, Date.now(), (subtitle, body) => void notifyDesktop({ subtitle, body })); } catch { /* db busy: next minute */ } try { sweepUnanswered(node); } catch { /* db busy: next minute */ } }, 60_000); void refreshDirectory(node); void pullPolicies(node); void refreshPeerEncKeys(node); // a policy about to lapse: one desktop reminder, 48 h ahead, with the renew command (only where the owner key is) const remind = () => { try { if (!node.ownerPub) return; for (const p of dueReminders(node.store.db)) void notifyDesktop({ subtitle: "Policy expires soon", body: `${policySummary(p)} expires ${p.exp.slice(0, 16).replace("T", " ")}Z. Renew: agentmbx policy renew ${p.id.slice(-6)}` }); } catch { /* db busy */ } }; @@ -1801,6 +1803,9 @@ async function hook(node: MbxNode, event: string | undefined, cli: string) { node.store.set(readKey, readSnap); if (readIds.length) lines.push(`[mbx] ${readAckLine(readIds.length)}`); } + // T765: work mail read 30+ min ago with no reply or ack is named by id (shares its throttle with the Stop reminder). + const due = unansweredReminder(node, agent, `${cli}:${sid ?? process.ppid}`); + if (due) lines.push(due); } // T189: on_session_start output is dropped and a resume does not fire it, so the first bound turn of each entry (a new // conversation, --resume, /new, /resume, a compression's new id) carries the bounded resume notice (T184 spec R5-R9). @@ -1868,6 +1873,15 @@ async function hook(node: MbxNode, event: string | undefined, cli: string) { return selfWatchInstruction({ delegated: !!delegationNote(node.store.db, agent, node.host), cli }); }; if (!fresh.length) { + // T765: before going idle, name work mail read 30+ min ago with no reply or ack. OpenCode has no prompt hook, + // so this Stop is where its agents hear about it. Bounded by the reminder's own throttle and allowContinue. + const due = unansweredReminder(node, agent, `${cli}:${sid ?? process.ppid}`); + if (due && node.allowContinue(agent, null)) { + if (cli === "kimi") { process.stderr.write(`${due}\n`); process.exitCode = 2; return; } + if (cli === "agy") { const out = agyHookOutput("Stop", due); if (out) console.log(out); return; } + console.log(JSON.stringify({ decision: "block", reason: due })); + return; + } if (cli === "grok" && input.stopHookActive !== true && !liveWatcher(node, agent) && !grokWatchArmed(input, sid)) { console.log(JSON.stringify({ decision: "block", reason: grokWatchReminder(sid) })); return; diff --git a/src/mcp.ts b/src/mcp.ts index 5ac6ebd8..cc5c582b 100644 --- a/src/mcp.ts +++ b/src/mcp.ts @@ -1208,7 +1208,7 @@ async function configureMcp(server: McpServer, node: MbxNode, startupClosed: () return { draft, warnings: externalWarning(origin, taint) }; }; /** Opening mail marks the reader's own copies read (delivered/notified → read; never past acked), for sender receipts (T207). */ - const markRead = (rows: { id: string }[], agent: string) => node.markRead(rows, agent); // its own copy, else a project copy it may read (T493) + const markRead = (rows: { id: string }[], agent: string, mode: "full" | "metadata" | "quarantine" = "full") => node.markRead(rows, agent, { mode }); // its own copy, else a project copy it may read (T493) // Identity and policy notes belong to the ready caller, never the transport's provisional mailbox. const sessionNotes = (state: State, tool: string): string => { if (!bound(state)) return ""; @@ -1891,12 +1891,12 @@ async function configureMcp(server: McpServer, node: MbxNode, startupClosed: () server.registerTool("mbx_read", { title: "Read mbx messages", - description: "Read one or more messages (ids or unique id prefixes). mode=full (default) shows full content framed with current sender verification and policy. Its policy line means: outward-reversible = push a non-default branch or open a draft PR; outward = merge, release, deploy, delete, secrets, spend. metadata returns only identifiers, times, sender identity, counts and computed policy/provenance: no subject/body/refs/receipt notes and no untrusted exposure. quarantine returns a labelled UNTRUSTED derived-outside summary (first512 Unicode code points, extraction/truncation stated), records an untrusted read and preserves source root times; it claims no sanitization or consent. All modes mark your own copy read. Full content separately records raw exposure. Next: mbx_reply if needed, then mbx_ack once dealt with.", + description: "Read one or more messages (ids or unique id prefixes). mode=full (default) shows full content framed with current sender verification and policy. Its policy line means: outward-reversible = push a non-default branch or open a draft PR; outward = merge, release, deploy, delete, secrets, spend. metadata returns only identifiers, times, sender identity, counts and computed policy/provenance: no subject/body/refs/receipt notes and no untrusted exposure. quarantine returns a labelled UNTRUSTED derived-outside summary (first512 Unicode code points, extraction/truncation stated), records an untrusted read and preserves source root times; it claims no sanitization or consent. All modes mark your own copy read; a full read also acks message/reply/status mail that asks for nothing (no needs_reply). Full content separately records raw exposure. Next: mbx_reply if needed, then mbx_ack once dealt with.", inputSchema: { ids: z.array(z.string().min(6)).min(1).max(20), mode: z.enum(["full", "metadata", "quarantine"]).default("full") }, annotations: { readOnlyHint: true }, }, ({ ids, mode }) => { const { agent } = current(), rows = ids.map((id) => node.read(id, agent)); - noteRead(rows, { mode }); markRead(rows, agent); + noteRead(rows, { mode }); markRead(rows, agent, mode); if (mode === "full") return text(rows.map(m => formatFor(node, m, agent, sendScope())).join("\n\n")); const messages = rows.map(m => messageReadView(node, m, agent, mode, Date.now(), sendScope())); return text(JSON.stringify({ messages }), { messages }); @@ -1954,7 +1954,7 @@ async function configureMcp(server: McpServer, node: MbxNode, startupClosed: () const m = node.message(id, agent); const rows = node.thread(m && node.canSee(m, agent) ? m.thread : id, agent); noteRead(rows, { mode }); - markRead(rows, agent); + markRead(rows, agent, mode); if (mode !== "full") { const messages = rows.map(m => messageReadView(node, m, agent, mode, Date.now(), sendScope())); return text(JSON.stringify({ messages }), { messages }); diff --git a/src/node.ts b/src/node.ts index cb45e56f..998cab29 100644 --- a/src/node.ts +++ b/src/node.ts @@ -26,6 +26,7 @@ import { backfillProjectKeys, backfillRegistry, projectOf } from "./registry.ts" import { ensureRepoTable, recordRepoAssociation } from "./repo-association.ts"; import { resolveLeadRecipients } from "./lead-record.ts"; import { isSlotName } from "./project-slot.ts"; +import { autoAckRead } from "./unanswered.ts"; import { projectLabel, projectMailboxBySlot, projectsLedBy, resolveProjectMailbox, rewriteProjectAliases, type ProjectMailbox } from "./project-mailbox.ts"; import { Store, type DeliveryState, type MessageRow } from "./store.ts"; @@ -961,13 +962,17 @@ export class MbxNode { })); } - /** Mark the reader's copy of each message read: its own when it has one, else a project copy it may read (T493). */ - markRead(rows: { id: string }[], agent: string) { + /** Mark the reader's copy of each message read: its own when it has one, else a project copy it may read (T493). + * T765: a full read closes informational mail (message/reply/status asking for nothing) as acked "auto: read". */ + markRead(rows: { id: string }[], agent: string, opts: { mode?: "full" | "metadata" | "quarantine" } = {}) { const slots = this.readableSlots(agent); for (const r of rows) { - if (this.store.db.prepare("SELECT 1 FROM deliveries WHERE msg_id=? AND agent=?").get(r.id, agent)) { this.setDelivery(r.id, agent, "read"); continue; } - for (const slot of slots) this.setDelivery(r.id, slot, "read"); + // A metadata read showed no content: its note keeps the daemon's auto-ack sweep off it (T765). + const note = opts.mode === "metadata" ? "metadata" : null; + if (this.store.db.prepare("SELECT 1 FROM deliveries WHERE msg_id=? AND agent=?").get(r.id, agent)) { this.setDelivery(r.id, agent, "read", note); continue; } + for (const slot of slots) this.setDelivery(r.id, slot, "read", note); } + if ((opts.mode ?? "full") === "full") for (const name of [agent, ...slots]) autoAckRead(this.store, rows.map((r) => r.id), name); } /** Every unacked delivery, read or not (whoami, handoff and the agents list count this). */ diff --git a/src/unanswered.ts b/src/unanswered.ts new file mode 100644 index 00000000..56642de1 --- /dev/null +++ b/src/unanswered.ts @@ -0,0 +1,86 @@ +// T765 (owner decision 2026-11-02): read-but-unanswered mail. Mail that asks for nothing (message, reply or status, no +// needs_reply, no owner authority) closes when it is read. Work mail (request, task, decision, alert, or anything with +// needs_reply) an agent read but neither answered nor acked is named again after 30 min, at the next prompt or before +// the session goes idle, and after 2 h its project lead gets one alert. Ids and senders only, never content. +import type { MbxNode } from "./node.ts"; +import type { Store } from "./store.ts"; +import { activeLead } from "./lead-record.ts"; +import { notSlot } from "./project-slot.ts"; + +export const REMIND_AFTER_MS = 30 * 60_000; +export const ALERT_AFTER_MS = 2 * 3600_000; +/** Older reads are left alone: the alert is for work going stale now, not for archaeology. */ +const LOOKBACK_MS = 7 * 24 * 3600_000; +const iso = (ms: number) => new Date(ms).toISOString(); + +const INFORMATIONAL = `m.kind IN ('message','reply','status') AND m.authority IS NULL AND coalesce(json_extract(m.envelope,'$.needs_reply'),0)=0`; +const WORK = `(m.kind IN ('request','task','decision','alert') OR m.authority IS NOT NULL OR json_extract(m.envelope,'$.needs_reply')=1)`; + +/** Ack read copies of informational mail: `ids` after a full read, or (no ids) every one not merely peeked at with a + * metadata read. One audit row per call; returns the count. */ +export function autoAckRead(store: Store, ids?: string[], agent?: string, now = Date.now()): number { + if (ids && !ids.length) return 0; + const only = ids ? `AND m.id IN (${ids.map(() => "?").join(",")})` : ""; + const r = store.db.prepare(`UPDATE deliveries SET state='acked', note='auto: read', updated_at=? + WHERE state='read' ${agent ? "AND agent=?" : ""} ${ids ? "" : "AND coalesce(note,'')<>'metadata'"} AND msg_id IN (SELECT m.id FROM messages m WHERE ${INFORMATIONAL} ${only})`) + .run(iso(now), ...(agent ? [agent] : []), ...(ids ?? [])); + const n = Number(r.changes); + if (n) store.audit("auto_ack", { ...(agent ? { agent } : {}), count: n, why: "auto: read (informational mail)" }); + return n; +} + +export interface Unanswered { id: string; kind: string; from: string; read_at: string; note: string | null } + +/** Work mail `agent` read at least `age` ago (within the lookback), still unacked and with no reply from it. Newest first. */ +export function unansweredMail(node: MbxNode, agent: string, age: number, now = Date.now()): Unanswered[] { + return node.store.db.prepare(`SELECT m.id id, m.kind kind, m.from_addr "from", d.updated_at read_at, d.note note + FROM deliveries d JOIN messages m ON m.id=d.msg_id + WHERE d.agent=? AND d.state='read' AND d.updated_at<=? AND d.updated_at>=? AND m.from_addr NOT LIKE 'mbx@%' AND ${WORK} + AND NOT EXISTS (SELECT 1 FROM messages r WHERE r.reply_to=m.id AND r.from_addr=?) + ORDER BY d.updated_at DESC LIMIT 20`).all(agent, iso(now - age), iso(now - LOOKBACK_MS), `${agent}@${node.host}`) as unknown as Unanswered[]; +} + +const idList = (rows: Unanswered[], n: number) => `${rows.slice(0, n).map((u) => u.id).join(", ")}${rows.length > n ? ", …" : ""}`; + +/** The 30 min reminder for one session, at most once per REMIND_AFTER_MS per session; null when nothing is due. */ +export function unansweredReminder(node: MbxNode, agent: string, session: string, now = Date.now()): string | null { + const due = unansweredMail(node, agent, REMIND_AFTER_MS, now); + if (!due.length) return null; + const key = `unanswered-nag:${session}:${agent}`, last = Date.parse(node.store.get(key) ?? ""); + if (Number.isFinite(last) && now - last < REMIND_AFTER_MS) return null; + node.store.set(key, iso(now)); + return `[mbx] ${due.length} work message(s) you read have no reply or ack: ${idList(due, 5)}. Answer each with mbx_reply, or mbx_ack with did="".`; +} + +/** The project lead to alert about `agent`: the active lead of its latest project, on this host, and not `agent` itself. */ +export function leadToAlert(node: MbxNode, agent: string, now = Date.now()): string | null { + const project = (node.store.db.prepare("SELECT project FROM identity_projects WHERE name=? ORDER BY last_seen DESC LIMIT 1").get(agent) as { project: string } | undefined)?.project; + const lead = project ? activeLead(node, project, new Date(now)) : null; + return lead && lead.host === node.host && lead.agent !== agent ? lead.agent : null; +} + +/** Daemon sweep: close informational mail already read, then alert each lead once per message unanswered 2 h after read. + * The alerted copies carry note 'unanswered', which the sender's receipts show. Returns the agents reported. */ +export function sweepUnanswered(node: MbxNode, now = Date.now()): string[] { + autoAckRead(node.store, undefined, undefined, now); + // A project slot is read by its lead, who is the one this alert would go to: slots are never listed (T493). + const agents = (node.store.db.prepare(`SELECT DISTINCT agent FROM deliveries WHERE state='read' AND coalesce(note,'')<>'unanswered' + AND updated_at<=? AND updated_at>=? AND ${notSlot("agent")}`).all(iso(now - ALERT_AFTER_MS), iso(now - LOOKBACK_MS)) as { agent: string }[]) + .map((r) => r.agent); + const out: string[] = []; + for (const agent of agents) { + const due = unansweredMail(node, agent, ALERT_AFTER_MS, now).filter((u) => u.note !== "unanswered"); + const lead = due.length ? leadToAlert(node, agent, now) : null; + if (!lead) continue; + const list = due.slice(0, 10).map((u) => `${u.id} (${u.kind} from ${u.from})`).join(", "); + try { + node.send({ from: "mbx", to: [lead], kind: "alert", subject: `Unanswered mail: ${agent} read work and did not reply or ack`.slice(0, 200), + body: `${agent} read ${due.length} work message(s) over 2 h ago and has neither replied nor acked them: ${list}${due.length > 10 ? ", …" : ""}. ` + + `Check on ${agent} (it may have moved on mid-task), or reassign the work.` }); + } catch { continue; } + node.store.tx(() => { for (const u of due) node.store.db.prepare("UPDATE deliveries SET note='unanswered' WHERE msg_id=? AND agent=? AND state='read'").run(u.id, agent); }); + node.store.audit("unanswered.alert", { agent, lead, count: due.length }); + out.push(agent); + } + return out; +} diff --git a/src/wake.ts b/src/wake.ts index 8eb81aea..0d951d17 100644 --- a/src/wake.ts +++ b/src/wake.ts @@ -21,7 +21,7 @@ import { isSlotName } from "./project-slot.ts"; import { markSkewNoted, wakeSkewNote } from "./connector-skew.ts"; import { codexFailureClass, enqueueCodexQueue, reconcileCodexQueue, type CodexPending, type CodexQueueContext } from "./codex-queue.ts"; import { identityGeneration } from "./identity-control.ts"; -import { activeLead } from "./lead-record.ts"; +import { leadToAlert } from "./unanswered.ts"; const run = promisify(execFile); /** `ok` is true only for an admitted wake or a shown notice. Provider adapters also report the typed `outcome` (T178, @@ -472,18 +472,17 @@ export function alertLeadOfStall(node: MbxNode, agent: string, rows: PendingRow[ if (!work.length) return null; const key = `stall-alert:${agent}`, last = Date.parse(node.store.get(key) ?? ""); if (Number.isFinite(last) && now - last < STALL_ALERT_MS) return null; - const project = (node.store.db.prepare("SELECT project FROM identity_projects WHERE name=? ORDER BY last_seen DESC LIMIT 1").get(agent) as { project: string } | undefined)?.project; - const lead = project ? activeLead(node, project, new Date(now)) : null; - if (!lead || lead.host !== node.host || lead.agent === agent) return null; + const lead = leadToAlert(node, agent, now); + if (!lead) return null; node.store.set(key, new Date(now).toISOString()); const list = work.slice(0, 10).map(r => `${r.id} (${r.kind} from ${r.from_addr})`).join(", "); try { - node.send({ from: "mbx", to: [lead.agent], kind: "alert", subject: `Stalled mail: ${agent} cannot be woken`.slice(0, 200), + node.send({ from: "mbx", to: [lead], kind: "alert", subject: `Stalled mail: ${agent} cannot be woken`.slice(0, 200), body: `${agent} has ${work.length} unread work message(s) that no session wake reached: ${list}. Its session is idle or has no push path, ` + `so the mail waits for its next prompt. Ask the owner to prompt ${agent}, or reassign the work.` }); } catch { node.store.db.prepare("DELETE FROM kv WHERE k=?").run(key); return null; } - node.store.audit("wake.stall_alert", { agent, lead: lead.agent, count: work.length }); - return lead.agent; + node.store.audit("wake.stall_alert", { agent, lead, count: work.length }); + return lead; } // ---- wake reconciliation and pressure (T179) ------------------------------------------------------------- diff --git a/test/hook-stop-read.test.ts b/test/hook-stop-read.test.ts index 75485171..6ed9be1b 100644 --- a/test/hook-stop-read.test.ts +++ b/test/hook-stop-read.test.ts @@ -137,3 +137,29 @@ for (const [cli, sid] of Object.entries(DIGEST_CLIS)) test(`T584 ${cli}: MBX_STO blocks("1", `${kind} still continues`); } }); + +// T765: a request read 30+ min ago with no reply or ack continues the Stop once per window. OpenCode has no prompt hook, +// so this is where its agents hear about mail they opened and set aside. +for (const cli of ["opencode", "claude"]) test(`T765 ${cli}: stop names work mail read 30+ min ago and not answered, once per window`, { timeout: 120_000 }, (t) => { + const home = mkdtempSync(join(tmpdir(), "mbx-t765-stop-")); + createOwnerKey(home, "test-only-passphrase"); + const n = new MbxNode(home, { host: "alpha" }), owner = unlockOwnerKey(home, "test-only-passphrase"); + t.after(() => { n.close(); rmSync(home, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }); }); + const [sid] = SIDS[cli]!; + bindWakeLease(n, { agent: "worker", cli, session_id: sid, pid: process.pid }); + const rec = makePolicy({ level: "autonomous", agents: ["worker"], hosts: ["alpha"], ownerPub: owner.publicKey }); + assert.equal(acceptSigned(n.store.db, { rec, sig: signData(owner.privateKey, canonical(rec)) }, "alpha"), null); + const stop = (): string => { + const env: NodeJS.ProcessEnv = { ...process.env, MBX_HOME: home, AGENTMBX_DEV: "1", MBX_AGENT: "unrelated" }; + const r = spawnSync(process.execPath, [resolve("bin/agentmbx.js"), "hook", "stop", "--cli", cli], { + input: JSON.stringify({ session_id: sid, cwd: process.cwd() }), encoding: "utf8", timeout: 30_000, env }); + return r.stdout + r.stderr; + }; + const id = sendLeased(n, { from: "boss", to: ["worker"], subject: "set aside", body: "b", kind: "request" }).envelope.id; + n.setDelivery(id, "worker", "read"); + assert.doesNotMatch(stop(), /no reply or ack/, "read just now: not due"); + n.store.db.prepare("UPDATE deliveries SET updated_at=? WHERE msg_id=?").run(new Date(Date.now() - 31 * 60_000).toISOString(), id); + const out = stop(); + assert.match(out, /no reply or ack/); assert.match(out, new RegExp(id)); + assert.doesNotMatch(stop(), /no reply or ack/, "once per window per session"); +}); diff --git a/test/hud-new-vs-read.test.ts b/test/hud-new-vs-read.test.ts index 92892509..aef393d3 100644 --- a/test/hud-new-vs-read.test.ts +++ b/test/hud-new-vs-read.test.ts @@ -24,11 +24,11 @@ function seeded(t: { after: (fn: () => void) => void }, cli: string, fresh: numb n.bindSession({ agent: "drum", cli, session_id: `${cli}-sess`, pid: process.pid, session_key: "k" }); claim(n, "drum", `${cli}-sess`, cli); const ids: string[] = []; - for (let i = 0; i < fresh + read + 1; i++) ids.push(n.send({ from: "boss", to: ["drum"], subject: `m${i}`, body: "b", needs_reply: i === 0 }).envelope.id); + for (let i = 0; i < fresh + read + 1; i++) ids.push(n.send({ from: "boss", to: ["drum"], subject: `m${i}`, body: "b", kind: "request", needs_reply: i === 0 }).envelope.id); // T765: work mail stays read-but-unacked n.markRead(ids.slice(0, read).map((id) => ({ id })), "drum"); // the first `read` messages: read, never acked n.ack(ids[ids.length - 1], "drum"); // one handled message // T308 AC2: another identity's new and read mail never reaches drum's counts - const other = [n.send({ from: "boss", to: ["other"], subject: "x", body: "b" }).envelope.id, n.send({ from: "boss", to: ["other"], subject: "y", body: "b" }).envelope.id]; + const other = [n.send({ from: "boss", to: ["other"], subject: "x", body: "b", kind: "request" }).envelope.id, n.send({ from: "boss", to: ["other"], subject: "y", body: "b", kind: "request" }).envelope.id]; n.markRead([{ id: other[0] }], "other"); writeHud(n); const v1 = JSON.parse(readFileSync(hudSessionPath(h, cli, `${cli}-sess`), "utf8")) as HudStatus; diff --git a/test/message-prefix.test.ts b/test/message-prefix.test.ts index e3aa5659..57715764 100644 --- a/test/message-prefix.test.ts +++ b/test/message-prefix.test.ts @@ -43,7 +43,7 @@ test("MCP and scoped CLI thread/reply paths resolve only visible prefixes", asyn } const denied = spawnSync(process.execPath, [bin, "send", "--as", "reader", "--to", "receiver", "--reply-to", prefix, "-m", "reply"], { env, encoding: "utf8" }); assert.equal(denied.status, 3); assert.ok(hidden.every(id => !denied.stderr.includes(id))); - const own = n.send({ from: "sender", to: ["reader"], subject: "visible", body: "visible-body" }).envelope.id; + const own = n.send({ from: "sender", to: ["reader"], subject: "visible", body: "visible-body", kind: "request" }).envelope.id; // T765: a work kind stays unacked after the read assert.ok(own.startsWith(prefix)); const thread = await call("mbx_thread", { id: prefix }); assert.notEqual(thread.isError, true); assert.match(JSON.stringify(thread), /visible-body/); const cli = spawnSync(process.execPath, [bin, "thread", prefix, "--as", "reader"], { env, encoding: "utf8" }); diff --git a/test/project-mailbox-mcp.test.ts b/test/project-mailbox-mcp.test.ts index 327556cb..90aaf8ac 100644 --- a/test/project-mailbox-mcp.test.ts +++ b/test/project-mailbox-mcp.test.ts @@ -83,7 +83,7 @@ const refused = async (c: Client, name: string, args: Record) = test("T493 AC2: the live lead sees the project mailbox as a labelled inbox section, and one ack clears it", async (t) => { const w = world(t); w.designate("agentmbx-lead"); - const m1 = w.send(["agentmbx"]), m2 = w.send(["agentmbx"], { kind: "request", needs_reply: true }); + const m1 = w.send(["agentmbx"], { kind: "task" }), m2 = w.send(["agentmbx"], { kind: "request", needs_reply: true }); const personal = w.withNode((n) => n.send({ from: "agentmbx-builder", to: ["agentmbx-lead"], subject: "personal note", body: "only for the lead persona", kind: "message", project: w.projA }).envelope.id); const slot = slotFor(CLEO_ID); diff --git a/test/project-mailbox.test.ts b/test/project-mailbox.test.ts index 2a12e0c7..6193f8d7 100644 --- a/test/project-mailbox.test.ts +++ b/test/project-mailbox.test.ts @@ -338,7 +338,7 @@ test("T493: reading and acknowledging a project copy takes the lead's lease scop assert.equal(state(personalOnly.envelope.id, "agentmbx-lead"), "delivered"); // A message that reached both: reading marks the personal copy first and leaves the project copy alone; ack likewise. - const both = w.n.send(w.draft(["agentmbx", "agentmbx-lead"])); + const both = w.n.send({ ...w.draft(["agentmbx", "agentmbx-lead"]), kind: "request" }); // T765: a work kind stays read until acked asLead(() => w.n.markRead([{ id: both.envelope.id }], "agentmbx-lead")); assert.equal(state(both.envelope.id, "agentmbx-lead"), "read"); assert.equal(state(both.envelope.id, mailbox.slot), "delivered"); asLead(() => w.n.ack(both.envelope.id, "agentmbx-lead")); @@ -454,6 +454,7 @@ const RATCHET: Record "src/store.ts": { max: 3, category: "schema", why: "triggers and the legacy visibility backfill" }, "src/stranded.ts": { max: 3, category: "enumerator (excludes project slots, asserted in the enumeration contract)", why: "established-name gated; a slot is recognised, not claimed" }, "src/sync-daemon.ts": { max: 2, category: "enumerator (excludes project slots, asserted in the enumeration contract)", why: "cloud read model" }, + "src/unanswered.ts": { max: 4, category: "enumerator (excludes project slots, asserted in the enumeration contract)", why: "T765: the 2 h sweep lists agents with notSlot(); the auto-ack writer, the per-agent unanswered query and the alert note update work on one named mailbox or one message" }, "src/wake.ts": { max: 8, category: "slot-aware (maps a project slot to its lead; test/wake-project-mail.test.ts)", why: "the dispatcher keys a slot row to the project's current lead (T557) and operates on the row's own mailbox; reconcile works per (message, mailbox) pair; T679 keepCodexNotice reads one row by (msg_id, agent) to decide whether an owned Codex queue notice is still due; T667 noteWatchReported/requeueWatchReported read and requeue one row by (msg_id, agent), never enumerate names" }, }; diff --git a/test/unanswered.test.ts b/test/unanswered.test.ts new file mode 100644 index 00000000..87ca1a50 --- /dev/null +++ b/test/unanswered.test.ts @@ -0,0 +1,93 @@ +// T765: informational mail closes on read; work mail read but unanswered is reminded at 30 min and reported to the lead at 2 h. +import { test, type TestContext } from "node:test"; +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { canonical, signData } from "../src/crypto.ts"; +import { makeLead, storeLead } from "../src/lead-record.ts"; +import { MbxNode } from "../src/node.ts"; +import { createOwnerKey, unlockOwnerKey } from "../src/owner.ts"; +import { noteProject } from "../src/registry.ts"; +import { ALERT_AFTER_MS, REMIND_AFTER_MS, sweepUnanswered, unansweredReminder } from "../src/unanswered.ts"; + +type Kind = "message" | "reply" | "status" | "request" | "task"; + +function world(t: TestContext) { + const n = new MbxNode(mkdtempSync(join(tmpdir(), "mbx-t765-")), { host: "testhost", bind: "127.0.0.1", port: 0 }); + createOwnerKey(n.home, "test-only-passphrase"); + const owner = unlockOwnerKey(n.home, "test-only-passphrase"); + t.after(() => { n.close(); rmSync(n.home, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 }); }); + const dir = join(n.home, "alpha"); + mkdirSync(join(dir, ".cleo"), { recursive: true }); + writeFileSync(join(dir, ".cleo", "project-id"), "# CLEO project id: write once, commit it\n071b70b3-551d-44bb-b993-1e84bfa2fe09\n"); + const A = realpathSync(dir); + for (const name of ["alpha-lead", "alpha-worker"]) { n.registerAgent(name); noteProject(n.store, name, A, true); } + const rec = makeLead({ project: A, agent: "alpha-lead", host: n.host, ownerPub: owner.publicKey }); + storeLead(n, rec, signData(owner.privateKey, canonical(rec))); + const send = (kind: Kind, needs_reply = false) => + n.send({ from: "boss", to: ["alpha-worker"], subject: "secret-subject", body: "secret-body", kind, needs_reply }).envelope.id; + const read = (id: string) => n.markRead([n.message(id, "alpha-worker")!], "alpha-worker"); + const state = (id: string) => (n.store.db.prepare("SELECT state, note FROM deliveries WHERE msg_id=? AND agent='alpha-worker'").get(id) as { state: string; note: string | null }); + const alerts = () => (n.store.db.prepare("SELECT m.envelope FROM deliveries d JOIN messages m ON m.id=d.msg_id WHERE d.agent='alpha-lead'").all() as { envelope: string }[]) + .map(r => JSON.parse(r.envelope) as { kind: string; subject: string; body: string }); + return { n, send, read, state, alerts }; +} + +test("T765: a full read acks message, reply and status mail that asks for nothing; work and needs_reply mail stay read", (t) => { + const { n, send, read, state } = world(t); + const info = (["message", "reply", "status"] as const).map((k) => send(k)); + const work = [send("request"), send("task"), send("message", true)]; + for (const id of [...info, ...work]) read(id); + for (const id of info) assert.deepEqual({ ...state(id) }, { state: "acked", note: "auto: read" }); + for (const id of work) assert.equal(state(id).state, "read"); + assert.ok(n.store.db.prepare("SELECT 1 FROM audit WHERE event='auto_ack'").get(), "audited"); +}); + +test("T765: metadata reads never auto-ack", (t) => { + const { n, send, state } = world(t); + const id = send("status"); + n.markRead([{ id }], "alpha-worker", { mode: "metadata" }); + assert.equal(state(id).state, "read"); + sweepUnanswered(n); + assert.equal(state(id).state, "read", "nor does the sweep close a peeked-at copy"); +}); + +test("T765: the reminder names work read 30+ min ago once per window, and stops once replied to", (t) => { + const { n, send, read } = world(t); + const id = send("request"); + read(id); + const now = Date.now(); + assert.equal(unansweredReminder(n, "alpha-worker", "s1", now), null, "not due yet"); + const line = unansweredReminder(n, "alpha-worker", "s1", now + REMIND_AFTER_MS + 1); + assert.match(line ?? "", new RegExp(id)); + assert.ok(!line!.includes("secret"), "ids only"); + assert.equal(unansweredReminder(n, "alpha-worker", "s1", now + REMIND_AFTER_MS + 2), null, "throttled per session"); + n.send({ from: "alpha-worker", to: ["boss"], subject: "re", body: "done", kind: "reply", reply_to: id }); + assert.equal(unansweredReminder(n, "alpha-worker", "s2", now + REMIND_AFTER_MS + 3), null, "a reply answers it"); +}); + +test("T765: the sweep closes informational backlog and alerts the lead once per message after 2 h", (t) => { + const { n, send, state, alerts } = world(t); + const status = send("status"), req = send("request"); + // A read made by a path that does not auto-ack (an older connector): the sweep closes it. + for (const id of [status, req]) n.setDelivery(id, "alpha-worker", "read"); + const later = Date.now() + ALERT_AFTER_MS + 1; + assert.deepEqual(sweepUnanswered(n, later), ["alpha-worker"]); + assert.equal(state(status).state, "acked"); + assert.deepEqual({ ...state(req) }, { state: "read", note: "unanswered" }, "the sender's receipt shows it"); + const [a] = alerts(); + assert.equal(a.kind, "alert"); + assert.match(a.body, new RegExp(req)); + assert.ok(!a.body.includes("secret-subject") && !a.body.includes("secret-body")); + assert.deepEqual(sweepUnanswered(n, later + 60_000), [], "each message alerts once"); + assert.equal(alerts().length, 1); +}); + +test("T765: the lead's own unanswered mail alerts no one", (t) => { + const { n, alerts } = world(t); + const id = n.send({ from: "boss", to: ["alpha-lead"], subject: "s", body: "b", kind: "request" }).envelope.id; + n.setDelivery(id, "alpha-lead", "read"); + assert.deepEqual(sweepUnanswered(n, Date.now() + ALERT_AFTER_MS + 1), []); + assert.equal(alerts().filter((a) => a.subject.startsWith("Unanswered")).length, 0); +}); From 0b557e5e6cda908729c8c094892efe7e7a071af5 Mon Sep 17 00:00:00 2001 From: Keaton Hoskins Date: Mon, 2 Nov 2026 09:44:39 -0800 Subject: [PATCH 2/3] test(T765): identity-recovery mail is a request so it stays unacked after mbx_read Co-Authored-By: Claude Opus 5.5 --- test/identity-recovery.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/identity-recovery.test.ts b/test/identity-recovery.test.ts index 914e9983..8f0d9608 100644 --- a/test/identity-recovery.test.ts +++ b/test/identity-recovery.test.ts @@ -29,7 +29,7 @@ for (const cli of ["codex", "opencode"]) test(`${cli} a newer process of the sam await previous.connect(transport()); assert.notEqual((await call(previous, "mbx_whoami", { name: "circle", role: "reviewer" })).isError, true); const holder = node.store.db.prepare("SELECT token,holder_pid FROM identity_leases WHERE name='circle'").get()!; - const mail = node.send({ from: "sender", to: ["circle"], subject: "pending", body: "preserved" }).envelope.id; + const mail = node.send({ from: "sender", to: ["circle"], subject: "pending", body: "preserved", kind: "request" }).envelope.id; // T765: work mail stays unacked after mbx_read restarted = true; await replacement.connect(transport()); // Another conversation that (wrongly) remembers the same identity stays unbound and pending: the live holder keeps it. From a48a05e5a40b3022e67871ca85632293ba4592a4 Mon Sep 17 00:00:00 2001 From: Keaton Hoskins Date: Mon, 2 Nov 2026 10:21:39 -0800 Subject: [PATCH 3/3] build(T765): rebuild dist Co-Authored-By: Claude Opus 5.5 --- dist/cli.js | 27 ++++++++++++++++ dist/mcp.js | 8 ++--- dist/node.js | 15 ++++++--- dist/unanswered.js | 79 ++++++++++++++++++++++++++++++++++++++++++++++ dist/wake.js | 13 ++++---- 5 files changed, 127 insertions(+), 15 deletions(-) create mode 100644 dist/unanswered.js diff --git a/dist/cli.js b/dist/cli.js index 48544a83..8ee5d8a1 100644 --- a/dist/cli.js +++ b/dist/cli.js @@ -28,6 +28,7 @@ import { readStdin, stdinIsTTY } from "./stdin.js"; import { runStatuslineSuggest } from "./statusline-suggest.js"; import { assertKnownRecipients, offlineWarnings, recipientReceipts } from "./receipts.js"; import { escalateUnheldMail, retirePhantoms, returnNeverClaimed } from "./stranded.js"; +import { sweepUnanswered, unansweredReminder } from "./unanswered.js"; import { activeLead, leadSummary, makeLead, makeLeadRevocation, projectLeadLine, projectLeadView, revokeLead, storeLead } from "./project-ledger.js"; import { leadHistory } from "./lead-record.js"; import { DEFAULT_PORT, defaultHome, didWarning, formatFor, messageReadView, MbxNode, summaryLine, trustLabel, WAKE_KINDS } from "./node.js"; @@ -900,6 +901,7 @@ async function run(argv) { case "read": { const row = node.read(pos[0] ?? die("read "), me), readMode = mode; node.observeRead(row, descriptor.cli, descriptor.session_id, readMode); + node.markRead([row], me, { mode: readMode }); // T765: the CLI fallback reads like mbx_read const scope = { cli: descriptor.cli, session_id: descriptor.session_id }; const view = readMode === "full" ? null : messageReadView(node, row, me, readMode, Date.now(), scope); return console.log(view ? JSON.stringify(view) : formatFor(node, row, me, scope)); @@ -1348,6 +1350,9 @@ If the codes differ, do not approve: someone is in the middle.`); catch { /* db busy: next minute */ } try { escalateUnheldMail(node, Date.now(), (subtitle, body) => void notifyDesktop({ subtitle, body })); } + catch { /* db busy: next minute */ } try { + sweepUnanswered(node); + } catch { /* db busy: next minute */ } }, 60_000); void refreshDirectory(node); void pullPolicies(node); @@ -2196,6 +2201,10 @@ async function hook(node, event, cli) { if (readIds.length) lines.push(`[mbx] ${readAckLine(readIds.length)}`); } + // T765: work mail read 30+ min ago with no reply or ack is named by id (shares its throttle with the Stop reminder). + const due = unansweredReminder(node, agent, `${cli}:${sid ?? process.ppid}`); + if (due) + lines.push(due); } // T189: on_session_start output is dropped and a resume does not fire it, so the first bound turn of each entry (a new // conversation, --resume, /new, /resume, a compression's new id) carries the bounded resume notice (T184 spec R5-R9). @@ -2273,6 +2282,24 @@ async function hook(node, event, cli) { return selfWatchInstruction({ delegated: !!delegationNote(node.store.db, agent, node.host), cli }); }; if (!fresh.length) { + // T765: before going idle, name work mail read 30+ min ago with no reply or ack. OpenCode has no prompt hook, + // so this Stop is where its agents hear about it. Bounded by the reminder's own throttle and allowContinue. + const due = unansweredReminder(node, agent, `${cli}:${sid ?? process.ppid}`); + if (due && node.allowContinue(agent, null)) { + if (cli === "kimi") { + process.stderr.write(`${due}\n`); + process.exitCode = 2; + return; + } + if (cli === "agy") { + const out = agyHookOutput("Stop", due); + if (out) + console.log(out); + return; + } + console.log(JSON.stringify({ decision: "block", reason: due })); + return; + } if (cli === "grok" && input.stopHookActive !== true && !liveWatcher(node, agent) && !grokWatchArmed(input, sid)) { console.log(JSON.stringify({ decision: "block", reason: grokWatchReminder(sid) })); return; diff --git a/dist/mcp.js b/dist/mcp.js index d3c05c51..2c1e7a00 100644 --- a/dist/mcp.js +++ b/dist/mcp.js @@ -1433,7 +1433,7 @@ async function configureMcp(server, node, startupClosed) { return { draft, warnings: externalWarning(origin, taint) }; }; /** Opening mail marks the reader's own copies read (delivered/notified → read; never past acked), for sender receipts (T207). */ - const markRead = (rows, agent) => node.markRead(rows, agent); // its own copy, else a project copy it may read (T493) + const markRead = (rows, agent, mode = "full") => node.markRead(rows, agent, { mode }); // its own copy, else a project copy it may read (T493) // Identity and policy notes belong to the ready caller, never the transport's provisional mailbox. const sessionNotes = (state, tool) => { if (!bound(state)) @@ -2183,13 +2183,13 @@ async function configureMcp(server, node, startupClosed) { }); server.registerTool("mbx_read", { title: "Read mbx messages", - description: "Read one or more messages (ids or unique id prefixes). mode=full (default) shows full content framed with current sender verification and policy. Its policy line means: outward-reversible = push a non-default branch or open a draft PR; outward = merge, release, deploy, delete, secrets, spend. metadata returns only identifiers, times, sender identity, counts and computed policy/provenance: no subject/body/refs/receipt notes and no untrusted exposure. quarantine returns a labelled UNTRUSTED derived-outside summary (first512 Unicode code points, extraction/truncation stated), records an untrusted read and preserves source root times; it claims no sanitization or consent. All modes mark your own copy read. Full content separately records raw exposure. Next: mbx_reply if needed, then mbx_ack once dealt with.", + description: "Read one or more messages (ids or unique id prefixes). mode=full (default) shows full content framed with current sender verification and policy. Its policy line means: outward-reversible = push a non-default branch or open a draft PR; outward = merge, release, deploy, delete, secrets, spend. metadata returns only identifiers, times, sender identity, counts and computed policy/provenance: no subject/body/refs/receipt notes and no untrusted exposure. quarantine returns a labelled UNTRUSTED derived-outside summary (first512 Unicode code points, extraction/truncation stated), records an untrusted read and preserves source root times; it claims no sanitization or consent. All modes mark your own copy read; a full read also acks message/reply/status mail that asks for nothing (no needs_reply). Full content separately records raw exposure. Next: mbx_reply if needed, then mbx_ack once dealt with.", inputSchema: { ids: z.array(z.string().min(6)).min(1).max(20), mode: z.enum(["full", "metadata", "quarantine"]).default("full") }, annotations: { readOnlyHint: true }, }, ({ ids, mode }) => { const { agent } = current(), rows = ids.map((id) => node.read(id, agent)); noteRead(rows, { mode }); - markRead(rows, agent); + markRead(rows, agent, mode); if (mode === "full") return text(rows.map(m => formatFor(node, m, agent, sendScope())).join("\n\n")); const messages = rows.map(m => messageReadView(node, m, agent, mode, Date.now(), sendScope())); @@ -2248,7 +2248,7 @@ async function configureMcp(server, node, startupClosed) { const m = node.message(id, agent); const rows = node.thread(m && node.canSee(m, agent) ? m.thread : id, agent); noteRead(rows, { mode }); - markRead(rows, agent); + markRead(rows, agent, mode); if (mode !== "full") { const messages = rows.map(m => messageReadView(node, m, agent, mode, Date.now(), sendScope())); return text(JSON.stringify({ messages }), { messages }); diff --git a/dist/node.js b/dist/node.js index a0596f26..215629ac 100644 --- a/dist/node.js +++ b/dist/node.js @@ -23,6 +23,7 @@ import { backfillProjectKeys, backfillRegistry, projectOf } from "./registry.js" import { ensureRepoTable, recordRepoAssociation } from "./repo-association.js"; import { resolveLeadRecipients } from "./lead-record.js"; import { isSlotName } from "./project-slot.js"; +import { autoAckRead } from "./unanswered.js"; import { projectLabel, projectMailboxBySlot, projectsLedBy, resolveProjectMailbox, rewriteProjectAliases } from "./project-mailbox.js"; import { Store } from "./store.js"; export const DEFAULT_PORT = 7373; @@ -1072,17 +1073,23 @@ export class MbxNode { WHERE d.agent=? ${opts.all ? "" : "AND d.state <> 'acked'"} ORDER BY m.ts LIMIT ?`).all(project.slot, opts.limit ?? 50).map((m) => this.currentAuthority(m)), })); } - /** Mark the reader's copy of each message read: its own when it has one, else a project copy it may read (T493). */ - markRead(rows, agent) { + /** Mark the reader's copy of each message read: its own when it has one, else a project copy it may read (T493). + * T765: a full read closes informational mail (message/reply/status asking for nothing) as acked "auto: read". */ + markRead(rows, agent, opts = {}) { const slots = this.readableSlots(agent); for (const r of rows) { + // A metadata read showed no content: its note keeps the daemon's auto-ack sweep off it (T765). + const note = opts.mode === "metadata" ? "metadata" : null; if (this.store.db.prepare("SELECT 1 FROM deliveries WHERE msg_id=? AND agent=?").get(r.id, agent)) { - this.setDelivery(r.id, agent, "read"); + this.setDelivery(r.id, agent, "read", note); continue; } for (const slot of slots) - this.setDelivery(r.id, slot, "read"); + this.setDelivery(r.id, slot, "read", note); } + if ((opts.mode ?? "full") === "full") + for (const name of [agent, ...slots]) + autoAckRead(this.store, rows.map((r) => r.id), name); } /** Every unacked delivery, read or not (whoami, handoff and the agents list count this). */ unreadCount(agent) { diff --git a/dist/unanswered.js b/dist/unanswered.js new file mode 100644 index 00000000..d746c27a --- /dev/null +++ b/dist/unanswered.js @@ -0,0 +1,79 @@ +import { activeLead } from "./lead-record.js"; +import { notSlot } from "./project-slot.js"; +export const REMIND_AFTER_MS = 30 * 60_000; +export const ALERT_AFTER_MS = 2 * 3600_000; +/** Older reads are left alone: the alert is for work going stale now, not for archaeology. */ +const LOOKBACK_MS = 7 * 24 * 3600_000; +const iso = (ms) => new Date(ms).toISOString(); +const INFORMATIONAL = `m.kind IN ('message','reply','status') AND m.authority IS NULL AND coalesce(json_extract(m.envelope,'$.needs_reply'),0)=0`; +const WORK = `(m.kind IN ('request','task','decision','alert') OR m.authority IS NOT NULL OR json_extract(m.envelope,'$.needs_reply')=1)`; +/** Ack read copies of informational mail: `ids` after a full read, or (no ids) every one not merely peeked at with a + * metadata read. One audit row per call; returns the count. */ +export function autoAckRead(store, ids, agent, now = Date.now()) { + if (ids && !ids.length) + return 0; + const only = ids ? `AND m.id IN (${ids.map(() => "?").join(",")})` : ""; + const r = store.db.prepare(`UPDATE deliveries SET state='acked', note='auto: read', updated_at=? + WHERE state='read' ${agent ? "AND agent=?" : ""} ${ids ? "" : "AND coalesce(note,'')<>'metadata'"} AND msg_id IN (SELECT m.id FROM messages m WHERE ${INFORMATIONAL} ${only})`) + .run(iso(now), ...(agent ? [agent] : []), ...(ids ?? [])); + const n = Number(r.changes); + if (n) + store.audit("auto_ack", { ...(agent ? { agent } : {}), count: n, why: "auto: read (informational mail)" }); + return n; +} +/** Work mail `agent` read at least `age` ago (within the lookback), still unacked and with no reply from it. Newest first. */ +export function unansweredMail(node, agent, age, now = Date.now()) { + return node.store.db.prepare(`SELECT m.id id, m.kind kind, m.from_addr "from", d.updated_at read_at, d.note note + FROM deliveries d JOIN messages m ON m.id=d.msg_id + WHERE d.agent=? AND d.state='read' AND d.updated_at<=? AND d.updated_at>=? AND m.from_addr NOT LIKE 'mbx@%' AND ${WORK} + AND NOT EXISTS (SELECT 1 FROM messages r WHERE r.reply_to=m.id AND r.from_addr=?) + ORDER BY d.updated_at DESC LIMIT 20`).all(agent, iso(now - age), iso(now - LOOKBACK_MS), `${agent}@${node.host}`); +} +const idList = (rows, n) => `${rows.slice(0, n).map((u) => u.id).join(", ")}${rows.length > n ? ", …" : ""}`; +/** The 30 min reminder for one session, at most once per REMIND_AFTER_MS per session; null when nothing is due. */ +export function unansweredReminder(node, agent, session, now = Date.now()) { + const due = unansweredMail(node, agent, REMIND_AFTER_MS, now); + if (!due.length) + return null; + const key = `unanswered-nag:${session}:${agent}`, last = Date.parse(node.store.get(key) ?? ""); + if (Number.isFinite(last) && now - last < REMIND_AFTER_MS) + return null; + node.store.set(key, iso(now)); + return `[mbx] ${due.length} work message(s) you read have no reply or ack: ${idList(due, 5)}. Answer each with mbx_reply, or mbx_ack with did="".`; +} +/** The project lead to alert about `agent`: the active lead of its latest project, on this host, and not `agent` itself. */ +export function leadToAlert(node, agent, now = Date.now()) { + const project = node.store.db.prepare("SELECT project FROM identity_projects WHERE name=? ORDER BY last_seen DESC LIMIT 1").get(agent)?.project; + const lead = project ? activeLead(node, project, new Date(now)) : null; + return lead && lead.host === node.host && lead.agent !== agent ? lead.agent : null; +} +/** Daemon sweep: close informational mail already read, then alert each lead once per message unanswered 2 h after read. + * The alerted copies carry note 'unanswered', which the sender's receipts show. Returns the agents reported. */ +export function sweepUnanswered(node, now = Date.now()) { + autoAckRead(node.store, undefined, undefined, now); + // A project slot is read by its lead, who is the one this alert would go to: slots are never listed (T493). + const agents = node.store.db.prepare(`SELECT DISTINCT agent FROM deliveries WHERE state='read' AND coalesce(note,'')<>'unanswered' + AND updated_at<=? AND updated_at>=? AND ${notSlot("agent")}`).all(iso(now - ALERT_AFTER_MS), iso(now - LOOKBACK_MS)) + .map((r) => r.agent); + const out = []; + for (const agent of agents) { + const due = unansweredMail(node, agent, ALERT_AFTER_MS, now).filter((u) => u.note !== "unanswered"); + const lead = due.length ? leadToAlert(node, agent, now) : null; + if (!lead) + continue; + const list = due.slice(0, 10).map((u) => `${u.id} (${u.kind} from ${u.from})`).join(", "); + try { + node.send({ from: "mbx", to: [lead], kind: "alert", subject: `Unanswered mail: ${agent} read work and did not reply or ack`.slice(0, 200), + body: `${agent} read ${due.length} work message(s) over 2 h ago and has neither replied nor acked them: ${list}${due.length > 10 ? ", …" : ""}. ` + + `Check on ${agent} (it may have moved on mid-task), or reassign the work.` }); + } + catch { + continue; + } + node.store.tx(() => { for (const u of due) + node.store.db.prepare("UPDATE deliveries SET note='unanswered' WHERE msg_id=? AND agent=? AND state='read'").run(u.id, agent); }); + node.store.audit("unanswered.alert", { agent, lead, count: due.length }); + out.push(agent); + } + return out; +} diff --git a/dist/wake.js b/dist/wake.js index b1d83508..629b8b88 100644 --- a/dist/wake.js +++ b/dist/wake.js @@ -19,7 +19,7 @@ import { isSlotName } from "./project-slot.js"; import { markSkewNoted, wakeSkewNote } from "./connector-skew.js"; import { codexFailureClass, enqueueCodexQueue, reconcileCodexQueue } from "./codex-queue.js"; import { identityGeneration } from "./identity-control.js"; -import { activeLead } from "./lead-record.js"; +import { leadToAlert } from "./unanswered.js"; const run = promisify(execFile); const attemptId = () => ulid(); const receipt = (strength, r = {}) => ({ strength, nativeId: null, sessionId: null, nativeStatus: null, providerVersion: null, ...r }); @@ -540,14 +540,13 @@ export function alertLeadOfStall(node, agent, rows, now = Date.now()) { const key = `stall-alert:${agent}`, last = Date.parse(node.store.get(key) ?? ""); if (Number.isFinite(last) && now - last < STALL_ALERT_MS) return null; - const project = node.store.db.prepare("SELECT project FROM identity_projects WHERE name=? ORDER BY last_seen DESC LIMIT 1").get(agent)?.project; - const lead = project ? activeLead(node, project, new Date(now)) : null; - if (!lead || lead.host !== node.host || lead.agent === agent) + const lead = leadToAlert(node, agent, now); + if (!lead) return null; node.store.set(key, new Date(now).toISOString()); const list = work.slice(0, 10).map(r => `${r.id} (${r.kind} from ${r.from_addr})`).join(", "); try { - node.send({ from: "mbx", to: [lead.agent], kind: "alert", subject: `Stalled mail: ${agent} cannot be woken`.slice(0, 200), + node.send({ from: "mbx", to: [lead], kind: "alert", subject: `Stalled mail: ${agent} cannot be woken`.slice(0, 200), body: `${agent} has ${work.length} unread work message(s) that no session wake reached: ${list}. Its session is idle or has no push path, ` + `so the mail waits for its next prompt. Ask the owner to prompt ${agent}, or reassign the work.` }); } @@ -555,8 +554,8 @@ export function alertLeadOfStall(node, agent, rows, now = Date.now()) { node.store.db.prepare("DELETE FROM kv WHERE k=?").run(key); return null; } - node.store.audit("wake.stall_alert", { agent, lead: lead.agent, count: work.length }); - return lead.agent; + node.store.audit("wake.stall_alert", { agent, lead, count: work.length }); + return lead; } // ---- wake reconciliation and pressure (T179) ------------------------------------------------------------- /** An `unknown` attempt is held this long before its mail may be woken once more (still within WAKE_LIMITS). */