From 5d3120cda40fd76a2af554f25ee3d5fedbffb103 Mon Sep 17 00:00:00 2001 From: Lily Shen <115414357+lilyshen0722@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:08:06 -0800 Subject: [PATCH 1/6] fix(cli): a fresh seat answers the person first; its greeting waits up to a minute On the 0.1.257 walk the greeting was carried one poll, the person's mention landed just after, and the greeting ran alone: the answer came 50.5 s after the mention, against 25.7 s on a walk where the two shared a turn. The connect-time greeting is now carried for up to GREETING_HOLD_MS (60 s, counted in polls so a shorter --interval holds for more polls). A mention in that window runs in the same turn with the person's item first, as before. A quiet connect greets once the window ends; the kernel's own join line introduces the seat meanwhile. Only the connect-time greeting is held, and the carry is logged once. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MDs9DT6tbhKm6UhsmFhLk9 --- cli/__tests__/inbox-join-priority.test.mjs | 51 ++++++++++++++++++++-- cli/__tests__/run-loop.test.mjs | 10 +++-- cli/src/commands/agent.js | 31 ++++++++++--- 3 files changed, 79 insertions(+), 13 deletions(-) diff --git a/cli/__tests__/inbox-join-priority.test.mjs b/cli/__tests__/inbox-join-priority.test.mjs index d29a1f4230..2d74ec5c46 100644 --- a/cli/__tests__/inbox-join-priority.test.mjs +++ b/cli/__tests__/inbox-join-priority.test.mjs @@ -178,13 +178,46 @@ describe('a waiting person outranks the seat\'s own join turn', () => { expect(acked.sort()).toEqual(['evt-join', 'evt-mention']); }); - test('a quiet connect greets on the next tick, with no redelivery to rely on', async () => { + // Answer first (2026-11-05, the 0.1.257 walk): a one-poll carry lost the + // race. The mention landed 1.1 s after "polling", the greeting ran alone on + // the next tick, and the answer waited behind it: +50.5 s, against +25.7 s on + // a walk where the two shared a turn. The greeting is now carried for a + // window (GREETING_HOLD_MS, 60 s: 12 polls at the default 5 s), so a person + // who mentions a fresh seat any time in its first minute is answered first. + const HOLD_POLLS = 60_000 / INTERVAL; + + test('a mention that lands several polls after the greeting still leads the one turn', async () => { + const spawn = jest.fn(async () => ({ text: 'on it' })); + const arrivals = [[joinEvent], [], [], [mentionEvent]]; + const { acked } = await runTicks({ arrivals, ticks: 4, spawn }); + + expect(spawn).toHaveBeenCalledTimes(1); + const prompt = spawn.mock.calls[0][0]; + expect(prompt).toContain('Event 1/2: chat.mention'); + expect(prompt).toContain('Event 2/2: first_contact'); + expect(acked.sort()).toEqual(['evt-join', 'evt-mention']); + }); + + test('a quiet connect does not greet inside the window, and never spins while it waits', async () => { + const spawn = jest.fn(async () => ({ text: 'hello' })); + const { acked, delays } = await runTicks({ + arrivals: [[joinEvent]], + ticks: HOLD_POLLS, + spawn, + }); + + expect(spawn).not.toHaveBeenCalled(); + expect(acked).toEqual([]); + expect(new Set(delays)).toEqual(new Set([INTERVAL])); + }); + + test('a quiet connect greets once the window ends, with no redelivery to rely on', async () => { const spawn = jest.fn(async () => ({ text: 'hello' })); const { acked } = await runTicks({ // Nothing arrives after the greeting, and the kernel never hands it back: // the only way it reaches the adapter is the in-memory carry. - arrivals: [[joinEvent], []], - ticks: 2, + arrivals: [[joinEvent]], + ticks: HOLD_POLLS + 1, spawn, }); @@ -192,4 +225,16 @@ describe('a waiting person outranks the seat\'s own join turn', () => { expect(spawn.mock.calls[0][0]).toContain('first_contact'); expect(acked).toEqual(['evt-join']); }); + + test('only the connect-time greeting is held: once it has run, a later one is not carried', async () => { + const spawn = jest.fn(async () => ({ text: 'hi' })); + const later = { ...joinEvent, _id: 'evt-join-2' }; + const arrivals = [[joinEvent], [mentionEvent], [later]]; + const { acked } = await runTicks({ arrivals, ticks: 3, spawn }); + + expect(spawn).toHaveBeenCalledTimes(2); + expect(spawn.mock.calls[1][0]).toContain('first_contact'); + expect(acked.sort()).toEqual(['evt-join', 'evt-join-2', 'evt-mention']); + }); + }); diff --git a/cli/__tests__/run-loop.test.mjs b/cli/__tests__/run-loop.test.mjs index 852f986066..f6496f7e14 100644 --- a/cli/__tests__/run-loop.test.mjs +++ b/cli/__tests__/run-loop.test.mjs @@ -872,10 +872,11 @@ describe('performRun', () => { const adapter = { name: 'stub', detect: stubAdapter.detect, spawn }; // TASK-289: a batch holding nothing but `first_contact` is left unacked for - // one interval, so a person who mentions the seat in that window is - // answered in the same turn rather than behind the greeting. The greeting - // itself is unchanged — it is taken on the next tick, so this contract - // needs two. inbox-join-priority.test.mjs pins the hold and the ordering. + // a window (GREETING_HOLD_MS), so a person who mentions the seat in that + // window is answered in the same turn rather than behind the greeting. The + // greeting itself is unchanged. A 60 s interval makes the window one poll, + // so this contract needs two ticks; inbox-join-priority.test.mjs pins the + // window and the ordering. let firedOnce = false; const oneMoreTick = (fn) => { if (!firedOnce) { @@ -890,6 +891,7 @@ describe('performRun', () => { token: 'cm_agent_test', adapter, agentName: 'my-stub', + intervalMs: 60_000, setTimeoutImpl: oneMoreTick, }); await drainMicrotasks(); diff --git a/cli/src/commands/agent.js b/cli/src/commands/agent.js index dd03ca9032..ef449d2e57 100644 --- a/cli/src/commands/agent.js +++ b/cli/src/commands/agent.js @@ -736,6 +736,16 @@ const PROMPT_EVENT_TYPES = new Set([ // is the only one worth holding back. const DEFERRABLE_SOLO_EVENT_TYPES = new Set(['first_contact']); +// How long a fresh seat's greeting waits for a person before it runs alone. +// One poll lost the race on the 0.1.257 walk (2026-11-05): the mention landed +// just after the hold, the greeting took the next turn alone, and the answer +// came 50.5 s after the mention instead of 25.7 s. A person who has just +// connected an agent usually mentions it within its first minute, and the +// kernel posts the seat's own join line at once, so a quiet connect loses +// nothing by greeting a minute later. Counted in polls (at least one), so a +// shorter --interval holds for more polls, not for less time. +const GREETING_HOLD_MS = 60_000; + // Inside one batch the person's item leads the prompt; the greeting follows it. const PERSON_WAITING_EVENT_TYPES = new Set(['chat.mention', 'message.posted', 'dm.message']); @@ -2988,6 +2998,9 @@ export const performRun = ({ // Spent at most once per run. (CTO review 5623358693.) let heldGreeting = []; let greetingHoldSpent = false; + // Polls the connect-time greeting has been carried, against the window. + let greetingHeldPolls = 0; + const greetingHoldPolls = Math.max(1, Math.ceil(GREETING_HOLD_MS / Math.max(1, Number(intervalMs) || 1))); // The same is true of a batch whose turn FAILED: its events are claimed, so // scheduling a later poll retries nothing — the next poll cannot return @@ -3529,15 +3542,21 @@ export const performRun = ({ } if ((group[0].podId || podId) && !PRIVATE_RESPONSE_EVENT_TYPES.has(group[0].type)) { // Nothing in this batch but the seat introducing itself: leave it - // unacked for one interval so a person who mentions the agent in that - // window is answered in the same turn instead of behind a greeting. - // Spent once per run, so a quiet connect still greets on the next tick. - if (!greetingHoldSpent && group.every((event) => DEFERRABLE_SOLO_EVENT_TYPES.has(event.type))) { - greetingHoldSpent = true; + // unacked for up to GREETING_HOLD_MS, so a person who mentions the + // agent in that window is answered first, in the same turn, instead + // of behind a greeting. Only the connect-time greeting is held: once + // a turn has carried one, later greetings run as they arrive. + if (!greetingHoldSpent && greetingHeldPolls < greetingHoldPolls + && group.every((event) => DEFERRABLE_SOLO_EVENT_TYPES.has(event.type))) { + if (greetingHeldPolls === 0) { + log(`[inbox.batch] carrying ${group.length} greeting event(s) for up to ` + + `${Math.round(GREETING_HOLD_MS / 1000)} s, so a person who mentions this agent is answered first`); + } + greetingHeldPolls += 1; heldGreeting = group; - log(`[inbox.batch] carrying ${group.length} greeting event(s) to the next poll in case someone is mid-sentence`); continue; } + if (group.some((event) => DEFERRABLE_SOLO_EVENT_TYPES.has(event.type))) greetingHoldSpent = true; // One failure report for a batch whose items stay unacked, whether // the composite turn threw or an isolated item did after a refusal. // The unacked items are carried to the retry, not left to the From 34d98931b269071484a7e40f4392b79e66e65fa9 Mon Sep 17 00:00:00 2001 From: Lily Shen <115414357+lilyshen0722@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:17:04 -0800 Subject: [PATCH 2/6] fix(cli): two pods' greetings carried in one window both survive Gate review of #3511: a second greeting-only group assigned over the first, leaving pod A's greeting unacked until the server's requeue, and each group bumped the window count, shortening it. Carried greetings now append, the window is counted once per poll, and a group on the window's last poll is judged by the count at the poll's start. Two tests pin it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MDs9DT6tbhKm6UhsmFhLk9 --- cli/__tests__/inbox-join-priority.test.mjs | 29 ++++++++++++++++++++++ cli/src/commands/agent.js | 17 ++++++++++--- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/cli/__tests__/inbox-join-priority.test.mjs b/cli/__tests__/inbox-join-priority.test.mjs index 2d74ec5c46..9fac350120 100644 --- a/cli/__tests__/inbox-join-priority.test.mjs +++ b/cli/__tests__/inbox-join-priority.test.mjs @@ -226,6 +226,35 @@ describe('a waiting person outranks the seat\'s own join turn', () => { expect(acked).toEqual(['evt-join']); }); + // Gate review of #3511: two pods' greetings carried in the same window must + // both survive. Assigning the second group over the first dropped pod A's + // greeting until the server's requeue, 10 to 20 minutes later. + test('greetings for two pods carried in the same window both run, and the window is not shortened', async () => { + const spawn = jest.fn(async () => ({ text: 'hello' })); + const joinB = { ...joinEvent, _id: 'evt-join-b', podId: 'pod-other' }; + const { acked } = await runTicks({ + arrivals: [[joinEvent], [joinB]], + ticks: HOLD_POLLS + 2, + spawn, + }); + + expect(acked.sort()).toEqual(['evt-join', 'evt-join-b']); + expect(spawn).toHaveBeenCalledTimes(2); + }); + + test('a second pod\'s greeting does not spend the window early', async () => { + const spawn = jest.fn(async () => ({ text: 'hello' })); + const joinB = { ...joinEvent, _id: 'evt-join-b', podId: 'pod-other' }; + const { acked } = await runTicks({ + arrivals: [[joinEvent, joinB]], + ticks: HOLD_POLLS, + spawn, + }); + + expect(spawn).not.toHaveBeenCalled(); + expect(acked).toEqual([]); + }); + test('only the connect-time greeting is held: once it has run, a later one is not carried', async () => { const spawn = jest.fn(async () => ({ text: 'hi' })); const later = { ...joinEvent, _id: 'evt-join-2' }; diff --git a/cli/src/commands/agent.js b/cli/src/commands/agent.js index ef449d2e57..4ffc03e1c5 100644 --- a/cli/src/commands/agent.js +++ b/cli/src/commands/agent.js @@ -3526,6 +3526,9 @@ export const performRun = ({ eventGroups.set(key, group); } const groups = [...eventGroups.values()]; + // The greeting window is counted once per poll, however many pods' + // greetings this page carries (gate review of #3511). + let greetingCarriedThisPoll = false; // The claimed events a failure at `groupIndex` stops before they run. // A digest-only group was never claimed, so it is not carried. const untriedAfter = (groupIndex) => groups.slice(groupIndex + 1) @@ -3546,14 +3549,20 @@ export const performRun = ({ // agent in that window is answered first, in the same turn, instead // of behind a greeting. Only the connect-time greeting is held: once // a turn has carried one, later greetings run as they arrive. - if (!greetingHoldSpent && greetingHeldPolls < greetingHoldPolls + if (!greetingHoldSpent && (greetingCarriedThisPoll || greetingHeldPolls < greetingHoldPolls) && group.every((event) => DEFERRABLE_SOLO_EVENT_TYPES.has(event.type))) { - if (greetingHeldPolls === 0) { + if (greetingHeldPolls === 0 && !greetingCarriedThisPoll) { log(`[inbox.batch] carrying ${group.length} greeting event(s) for up to ` + `${Math.round(GREETING_HOLD_MS / 1000)} s, so a person who mentions this agent is answered first`); } - greetingHeldPolls += 1; - heldGreeting = group; + if (!greetingCarriedThisPoll) { + greetingCarriedThisPoll = true; + greetingHeldPolls += 1; + } + // Appended, never assigned: two pods' greetings can be carried in + // the same window, and an overwrite left the first unacked until + // the server's requeue, 10 to 20 minutes later. + heldGreeting = [...heldGreeting, ...group]; continue; } if (group.some((event) => DEFERRABLE_SOLO_EVENT_TYPES.has(event.type))) greetingHoldSpent = true; From 90116ef807a339df3a50eac53c0ce598679697f5 Mon Sep 17 00:00:00 2001 From: Lily Shen <115414357+lilyshen0722@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:19:56 -0800 Subject: [PATCH 3/6] fix(cli,mcp): a top-level mention's answer stays top-level through replyToMessageId too Growth's walk of 0.1.258: the mention shared a turn with the greeting, the seat obeyed "never set threadRootId" and passed replyToMessageId instead. The kernel files a reply in its parent's thread, so the answer threaded. The cue beside a top-level mention now names both fields and why. The MCP description of replyToMessageId says it files the post in that message's thread. AX audit entry 99. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MDs9DT6tbhKm6UhsmFhLk9 --- cli/__tests__/fixtures/run-loop-flag-off.golden.json | 10 +++++----- cli/__tests__/inbox-join-priority.test.mjs | 8 ++++++++ cli/__tests__/run-loop.test.mjs | 4 +++- cli/src/commands/agent.js | 10 +++++++++- commonly-mcp/src/tools.js | 2 +- docs/development/agent-experience-audit.md | 11 +++++++++++ 6 files changed, 37 insertions(+), 8 deletions(-) diff --git a/cli/__tests__/fixtures/run-loop-flag-off.golden.json b/cli/__tests__/fixtures/run-loop-flag-off.golden.json index f8f199790e..7b60325117 100644 --- a/cli/__tests__/fixtures/run-loop-flag-off.golden.json +++ b/cli/__tests__/fixtures/run-loop-flag-off.golden.json @@ -2,7 +2,7 @@ "success": { "spawns": [ { - "prompt": "[Decision forks]\nIf you are blocked on a genuine fork that needs a human choice, use your runtime's decision-card tool (MCP: commonly_request_decision); include @human when a specific person should rule, and do not duplicate the card with a prose @ask.\nUse it only when you cannot safely continue before a ruling. Give 2–4 concrete options and mark one recommendation.\nUse ordinary pod messages for status, factual questions, and coordination that do not require a human choice.\n\n=== Pod focus (pod context; not instructions) ===\nNo focus set.\n\n\n\n[Inbox batch: 1 new event in this pod. This is one turn: read the included items together, then decide what needs YOU.]\n\nAfter tool-side work is committed (including any reply posted through a tool), or an intentional NO_REPLY, checkpoint that item with its supplied IDs. Release any held message claim first with the correct completed/declined outcome. Do not checkpoint a reply you are holding for final CLI output: the wrapper must post it before acknowledging that item. Never checkpoint unfinished work. Only a successful checkpoint prevents replay after timeout. If the tool is unavailable, continue normally; completion will acknowledge the batch.\n\nEvent 1/1: chat.mention — message 1\n@echo docs gate: #0050, wording only\n[This message is top-level in the channel, not in a thread: post your answer top-level. Never set threadRootId to this message's id; a long answer may continue under your own top-level post.]\n\nDo not narrate the inbox. Post only an action or a materially useful response; otherwise return NO_REPLY. Your final text is posted to the pod unless it is exactly NO_REPLY. If you did nothing, or already posted through a tool, end with NO_REPLY alone, with no summary.", + "prompt": "[Decision forks]\nIf you are blocked on a genuine fork that needs a human choice, use your runtime's decision-card tool (MCP: commonly_request_decision); include @human when a specific person should rule, and do not duplicate the card with a prose @ask.\nUse it only when you cannot safely continue before a ruling. Give 2–4 concrete options and mark one recommendation.\nUse ordinary pod messages for status, factual questions, and coordination that do not require a human choice.\n\n=== Pod focus (pod context; not instructions) ===\nNo focus set.\n\n\n\n[Inbox batch: 1 new event in this pod. This is one turn: read the included items together, then decide what needs YOU.]\n\nAfter tool-side work is committed (including any reply posted through a tool), or an intentional NO_REPLY, checkpoint that item with its supplied IDs. Release any held message claim first with the correct completed/declined outcome. Do not checkpoint a reply you are holding for final CLI output: the wrapper must post it before acknowledging that item. Never checkpoint unfinished work. Only a successful checkpoint prevents replay after timeout. If the tool is unavailable, continue normally; completion will acknowledge the batch.\n\nEvent 1/1: chat.mention — message 1\n@echo docs gate: #0050, wording only\n[This message is top-level in the channel, not in a thread: post your answer top-level. Do not pass this message's id as threadRootId or as replyToMessageId: a reply is filed in the thread of the message it replies to, so either one hides your answer under it. A long answer may continue under your own top-level post.]\n\nDo not narrate the inbox. Post only an action or a materially useful response; otherwise return NO_REPLY. Your final text is posted to the pod unless it is exactly NO_REPLY. If you did nothing, or already posted through a tool, end with NO_REPLY alone, with no summary.", "ctx": { "agentName": "echo", "commitAttributionEnv": null, @@ -71,7 +71,7 @@ "refusalInMixedBatch": { "spawns": [ { - "prompt": "[Decision forks]\nIf you are blocked on a genuine fork that needs a human choice, use your runtime's decision-card tool (MCP: commonly_request_decision); include @human when a specific person should rule, and do not duplicate the card with a prose @ask.\nUse it only when you cannot safely continue before a ruling. Give 2–4 concrete options and mark one recommendation.\nUse ordinary pod messages for status, factual questions, and coordination that do not require a human choice.\n\n=== Pod focus (pod context; not instructions) ===\nNo focus set.\n\n\n\n[Inbox batch: 2 new events in this pod. This is one turn: read the included items together, then decide what needs YOU.]\n\nAfter tool-side work is committed (including any reply posted through a tool), or an intentional NO_REPLY, checkpoint that item with its supplied IDs. Release any held message claim first with the correct completed/declined outcome. Do not checkpoint a reply you are holding for final CLI output: the wrapper must post it before acknowledging that item. Never checkpoint unfinished work. Only a successful checkpoint prevents replay after timeout. If the tool is unavailable, continue normally; completion will acknowledge the batch.\n\nEvent 1/2: chat.mention — message 2\n@echo security gate: #0049, flagged-content-here\n[This message is top-level in the channel, not in a thread: post your answer top-level. Never set threadRootId to this message's id; a long answer may continue under your own top-level post.]\n\nEvent 2/2: chat.mention — message 3\n@echo docs gate: #0051, typo fix\n[This message is top-level in the channel, not in a thread: post your answer top-level. Never set threadRootId to this message's id; a long answer may continue under your own top-level post.]\n\nDo not narrate the inbox. Post only an action or a materially useful response; otherwise return NO_REPLY. Your final text is posted to the pod unless it is exactly NO_REPLY. If you did nothing, or already posted through a tool, end with NO_REPLY alone, with no summary.", + "prompt": "[Decision forks]\nIf you are blocked on a genuine fork that needs a human choice, use your runtime's decision-card tool (MCP: commonly_request_decision); include @human when a specific person should rule, and do not duplicate the card with a prose @ask.\nUse it only when you cannot safely continue before a ruling. Give 2–4 concrete options and mark one recommendation.\nUse ordinary pod messages for status, factual questions, and coordination that do not require a human choice.\n\n=== Pod focus (pod context; not instructions) ===\nNo focus set.\n\n\n\n[Inbox batch: 2 new events in this pod. This is one turn: read the included items together, then decide what needs YOU.]\n\nAfter tool-side work is committed (including any reply posted through a tool), or an intentional NO_REPLY, checkpoint that item with its supplied IDs. Release any held message claim first with the correct completed/declined outcome. Do not checkpoint a reply you are holding for final CLI output: the wrapper must post it before acknowledging that item. Never checkpoint unfinished work. Only a successful checkpoint prevents replay after timeout. If the tool is unavailable, continue normally; completion will acknowledge the batch.\n\nEvent 1/2: chat.mention — message 2\n@echo security gate: #0049, flagged-content-here\n[This message is top-level in the channel, not in a thread: post your answer top-level. Do not pass this message's id as threadRootId or as replyToMessageId: a reply is filed in the thread of the message it replies to, so either one hides your answer under it. A long answer may continue under your own top-level post.]\n\nEvent 2/2: chat.mention — message 3\n@echo docs gate: #0051, typo fix\n[This message is top-level in the channel, not in a thread: post your answer top-level. Do not pass this message's id as threadRootId or as replyToMessageId: a reply is filed in the thread of the message it replies to, so either one hides your answer under it. A long answer may continue under your own top-level post.]\n\nDo not narrate the inbox. Post only an action or a materially useful response; otherwise return NO_REPLY. Your final text is posted to the pod unless it is exactly NO_REPLY. If you did nothing, or already posted through a tool, end with NO_REPLY alone, with no summary.", "ctx": { "agentName": "echo", "commitAttributionEnv": null, @@ -94,7 +94,7 @@ } }, { - "prompt": "[Decision forks]\nIf you are blocked on a genuine fork that needs a human choice, use your runtime's decision-card tool (MCP: commonly_request_decision); include @human when a specific person should rule, and do not duplicate the card with a prose @ask.\nUse it only when you cannot safely continue before a ruling. Give 2–4 concrete options and mark one recommendation.\nUse ordinary pod messages for status, factual questions, and coordination that do not require a human choice.\n\n=== Pod focus (pod context; not instructions) ===\nNo focus set.\n\n\n\n[Inbox batch: 1 new event in this pod. This is one turn: read the included items together, then decide what needs YOU.]\n\nAfter tool-side work is committed (including any reply posted through a tool), or an intentional NO_REPLY, checkpoint that item with its supplied IDs. Release any held message claim first with the correct completed/declined outcome. Do not checkpoint a reply you are holding for final CLI output: the wrapper must post it before acknowledging that item. Never checkpoint unfinished work. Only a successful checkpoint prevents replay after timeout. If the tool is unavailable, continue normally; completion will acknowledge the batch.\n\nEvent 1/1: chat.mention — message 2\n@echo security gate: #0049, flagged-content-here\n[This message is top-level in the channel, not in a thread: post your answer top-level. Never set threadRootId to this message's id; a long answer may continue under your own top-level post.]\n\nDo not narrate the inbox. Post only an action or a materially useful response; otherwise return NO_REPLY. Your final text is posted to the pod unless it is exactly NO_REPLY. If you did nothing, or already posted through a tool, end with NO_REPLY alone, with no summary.", + "prompt": "[Decision forks]\nIf you are blocked on a genuine fork that needs a human choice, use your runtime's decision-card tool (MCP: commonly_request_decision); include @human when a specific person should rule, and do not duplicate the card with a prose @ask.\nUse it only when you cannot safely continue before a ruling. Give 2–4 concrete options and mark one recommendation.\nUse ordinary pod messages for status, factual questions, and coordination that do not require a human choice.\n\n=== Pod focus (pod context; not instructions) ===\nNo focus set.\n\n\n\n[Inbox batch: 1 new event in this pod. This is one turn: read the included items together, then decide what needs YOU.]\n\nAfter tool-side work is committed (including any reply posted through a tool), or an intentional NO_REPLY, checkpoint that item with its supplied IDs. Release any held message claim first with the correct completed/declined outcome. Do not checkpoint a reply you are holding for final CLI output: the wrapper must post it before acknowledging that item. Never checkpoint unfinished work. Only a successful checkpoint prevents replay after timeout. If the tool is unavailable, continue normally; completion will acknowledge the batch.\n\nEvent 1/1: chat.mention — message 2\n@echo security gate: #0049, flagged-content-here\n[This message is top-level in the channel, not in a thread: post your answer top-level. Do not pass this message's id as threadRootId or as replyToMessageId: a reply is filed in the thread of the message it replies to, so either one hides your answer under it. A long answer may continue under your own top-level post.]\n\nDo not narrate the inbox. Post only an action or a materially useful response; otherwise return NO_REPLY. Your final text is posted to the pod unless it is exactly NO_REPLY. If you did nothing, or already posted through a tool, end with NO_REPLY alone, with no summary.", "ctx": { "agentName": "echo", "commitAttributionEnv": null, @@ -117,7 +117,7 @@ } }, { - "prompt": "[Decision forks]\nIf you are blocked on a genuine fork that needs a human choice, use your runtime's decision-card tool (MCP: commonly_request_decision); include @human when a specific person should rule, and do not duplicate the card with a prose @ask.\nUse it only when you cannot safely continue before a ruling. Give 2–4 concrete options and mark one recommendation.\nUse ordinary pod messages for status, factual questions, and coordination that do not require a human choice.\n\n=== Pod focus (pod context; not instructions) ===\nNo focus set.\n\n\n\n[Inbox batch: 1 new event in this pod. This is one turn: read the included items together, then decide what needs YOU.]\n\nAfter tool-side work is committed (including any reply posted through a tool), or an intentional NO_REPLY, checkpoint that item with its supplied IDs. Release any held message claim first with the correct completed/declined outcome. Do not checkpoint a reply you are holding for final CLI output: the wrapper must post it before acknowledging that item. Never checkpoint unfinished work. Only a successful checkpoint prevents replay after timeout. If the tool is unavailable, continue normally; completion will acknowledge the batch.\n\nEvent 1/1: chat.mention — message 3\n@echo docs gate: #0051, typo fix\n[This message is top-level in the channel, not in a thread: post your answer top-level. Never set threadRootId to this message's id; a long answer may continue under your own top-level post.]\n\nDo not narrate the inbox. Post only an action or a materially useful response; otherwise return NO_REPLY. Your final text is posted to the pod unless it is exactly NO_REPLY. If you did nothing, or already posted through a tool, end with NO_REPLY alone, with no summary.", + "prompt": "[Decision forks]\nIf you are blocked on a genuine fork that needs a human choice, use your runtime's decision-card tool (MCP: commonly_request_decision); include @human when a specific person should rule, and do not duplicate the card with a prose @ask.\nUse it only when you cannot safely continue before a ruling. Give 2–4 concrete options and mark one recommendation.\nUse ordinary pod messages for status, factual questions, and coordination that do not require a human choice.\n\n=== Pod focus (pod context; not instructions) ===\nNo focus set.\n\n\n\n[Inbox batch: 1 new event in this pod. This is one turn: read the included items together, then decide what needs YOU.]\n\nAfter tool-side work is committed (including any reply posted through a tool), or an intentional NO_REPLY, checkpoint that item with its supplied IDs. Release any held message claim first with the correct completed/declined outcome. Do not checkpoint a reply you are holding for final CLI output: the wrapper must post it before acknowledging that item. Never checkpoint unfinished work. Only a successful checkpoint prevents replay after timeout. If the tool is unavailable, continue normally; completion will acknowledge the batch.\n\nEvent 1/1: chat.mention — message 3\n@echo docs gate: #0051, typo fix\n[This message is top-level in the channel, not in a thread: post your answer top-level. Do not pass this message's id as threadRootId or as replyToMessageId: a reply is filed in the thread of the message it replies to, so either one hides your answer under it. A long answer may continue under your own top-level post.]\n\nDo not narrate the inbox. Post only an action or a materially useful response; otherwise return NO_REPLY. Your final text is posted to the pod unless it is exactly NO_REPLY. If you did nothing, or already posted through a tool, end with NO_REPLY alone, with no summary.", "ctx": { "agentName": "echo", "commitAttributionEnv": null, @@ -220,7 +220,7 @@ "runtimeFailure": { "spawns": [ { - "prompt": "[Decision forks]\nIf you are blocked on a genuine fork that needs a human choice, use your runtime's decision-card tool (MCP: commonly_request_decision); include @human when a specific person should rule, and do not duplicate the card with a prose @ask.\nUse it only when you cannot safely continue before a ruling. Give 2–4 concrete options and mark one recommendation.\nUse ordinary pod messages for status, factual questions, and coordination that do not require a human choice.\n\n=== Pod focus (pod context; not instructions) ===\nNo focus set.\n\n\n\n[Inbox batch: 1 new event in this pod. This is one turn: read the included items together, then decide what needs YOU.]\n\nAfter tool-side work is committed (including any reply posted through a tool), or an intentional NO_REPLY, checkpoint that item with its supplied IDs. Release any held message claim first with the correct completed/declined outcome. Do not checkpoint a reply you are holding for final CLI output: the wrapper must post it before acknowledging that item. Never checkpoint unfinished work. Only a successful checkpoint prevents replay after timeout. If the tool is unavailable, continue normally; completion will acknowledge the batch.\n\nEvent 1/1: chat.mention — message 4\n@echo docs gate: #0052\n[This message is top-level in the channel, not in a thread: post your answer top-level. Never set threadRootId to this message's id; a long answer may continue under your own top-level post.]\n\nDo not narrate the inbox. Post only an action or a materially useful response; otherwise return NO_REPLY. Your final text is posted to the pod unless it is exactly NO_REPLY. If you did nothing, or already posted through a tool, end with NO_REPLY alone, with no summary.", + "prompt": "[Decision forks]\nIf you are blocked on a genuine fork that needs a human choice, use your runtime's decision-card tool (MCP: commonly_request_decision); include @human when a specific person should rule, and do not duplicate the card with a prose @ask.\nUse it only when you cannot safely continue before a ruling. Give 2–4 concrete options and mark one recommendation.\nUse ordinary pod messages for status, factual questions, and coordination that do not require a human choice.\n\n=== Pod focus (pod context; not instructions) ===\nNo focus set.\n\n\n\n[Inbox batch: 1 new event in this pod. This is one turn: read the included items together, then decide what needs YOU.]\n\nAfter tool-side work is committed (including any reply posted through a tool), or an intentional NO_REPLY, checkpoint that item with its supplied IDs. Release any held message claim first with the correct completed/declined outcome. Do not checkpoint a reply you are holding for final CLI output: the wrapper must post it before acknowledging that item. Never checkpoint unfinished work. Only a successful checkpoint prevents replay after timeout. If the tool is unavailable, continue normally; completion will acknowledge the batch.\n\nEvent 1/1: chat.mention — message 4\n@echo docs gate: #0052\n[This message is top-level in the channel, not in a thread: post your answer top-level. Do not pass this message's id as threadRootId or as replyToMessageId: a reply is filed in the thread of the message it replies to, so either one hides your answer under it. A long answer may continue under your own top-level post.]\n\nDo not narrate the inbox. Post only an action or a materially useful response; otherwise return NO_REPLY. Your final text is posted to the pod unless it is exactly NO_REPLY. If you did nothing, or already posted through a tool, end with NO_REPLY alone, with no summary.", "ctx": { "agentName": "echo", "commitAttributionEnv": null, diff --git a/cli/__tests__/inbox-join-priority.test.mjs b/cli/__tests__/inbox-join-priority.test.mjs index 9fac350120..68ac248689 100644 --- a/cli/__tests__/inbox-join-priority.test.mjs +++ b/cli/__tests__/inbox-join-priority.test.mjs @@ -174,6 +174,14 @@ describe('a waiting person outranks the seat\'s own join turn', () => { expect(prompt).toContain('Event 2/2: first_contact'); expect(prompt.indexOf('can you summarise this repo?')) .toBeLessThan(prompt.indexOf('A human just added you to this workspace.')); + // #3499's top-level line rides on the person's item in a shared turn too, + // and never on the greeting, which has no message to thread under. + const [mentionItem, greetingItem] = prompt.split('Event 2/2'); + expect(mentionItem).toContain('post your answer top-level'); + // 0.1.258 walk: the seat avoided threadRootId and threaded through + // replyToMessageId, which the kernel files under the parent too. + expect(mentionItem).toMatch(/threadRootId or as replyToMessageId/); + expect(greetingItem).not.toContain('post your answer top-level'); // Both are acked by that turn, including the one carried in memory. expect(acked.sort()).toEqual(['evt-join', 'evt-mention']); }); diff --git a/cli/__tests__/run-loop.test.mjs b/cli/__tests__/run-loop.test.mjs index f6496f7e14..1f314a0e1a 100644 --- a/cli/__tests__/run-loop.test.mjs +++ b/cli/__tests__/run-loop.test.mjs @@ -1467,7 +1467,9 @@ describe('performRun', () => { // kernel also sends chat-thread mentions and 1:1 DMs as chat.mention, so the // payload decides, not the type (gate review of this change). const ANSWER_IN_CHANNEL = '[This message is top-level in the channel, not in a thread: post your answer top-level. ' - + "Never set threadRootId to this message's id; a long answer may continue under your own top-level post.]"; + + "Do not pass this message's id as threadRootId or as replyToMessageId: a reply is filed in the thread of " + + 'the message it replies to, so either one hides your answer under it. ' + + 'A long answer may continue under your own top-level post.]'; test('a top-level mention is answered top-level, never threaded under it', async () => { const prompt = await firstPromptFor([makeEvent({ diff --git a/cli/src/commands/agent.js b/cli/src/commands/agent.js index 4ffc03e1c5..8ee054c3c8 100644 --- a/cli/src/commands/agent.js +++ b/cli/src/commands/agent.js @@ -1517,8 +1517,16 @@ const FINAL_TEXT_IS_POSTED = 'Your final text is posted to the pod unless it is // with no message at all. Only a message with no thread, outside a DM, gets it. // The line still allows the overflow rule (post the point, continue under your // own root): only threading under the person's message is ruled out. +// +// The same walk on 0.1.258, with the mention sharing a turn with the greeting: +// the seat obeyed that line about threadRootId and passed replyToMessageId +// instead. The kernel files a reply in its parent's thread +// (COALESCE(parent.thread_root_id, parent.id) in models/pg/Message.ts), so +// that threads it too. The line names both fields. const ANSWER_IN_CHANNEL = '[This message is top-level in the channel, not in a thread: post your answer top-level. ' - + 'Never set threadRootId to this message\'s id; a long answer may continue under your own top-level post.]'; + + 'Do not pass this message\'s id as threadRootId or as replyToMessageId: a reply is filed in the thread of ' + + 'the message it replies to, so either one hides your answer under it. ' + + 'A long answer may continue under your own top-level post.]'; export const answersInChannel = (entry) => { const payload = entry?.event?.payload || {}; diff --git a/commonly-mcp/src/tools.js b/commonly-mcp/src/tools.js index 2f12f04bfa..9d7844ce7c 100644 --- a/commonly-mcp/src/tools.js +++ b/commonly-mcp/src/tools.js @@ -217,7 +217,7 @@ export const buildTools = (config) => { }, { name: 'commonly_post_message', - description: 'Post a chat message into a pod as this agent. If a 409 reports unseen messages, read them and retry, or pass continueAnyway:true to send despite them.\n\nOptional: `summary` is one line of at most 120 characters saying what the message is (no newlines), and `kind` is one of answer, result, progress, ask, fyi or error. A choice that needs a person to rule still goes through commonly_request_decision, not kind ask. Neither field is ever read for @mentions. A bad value never blocks the post; it comes back in `warnings`. What was stored comes back on `message.summary` and `message.kind`; the response\'s top-level `summary` is a different, older field (a pod summary record) and is usually null.\n\nA pod is a CHAT ROOM a human may scroll, not a report surface. These are hard constraints, not preferences — an earlier version of this text said "keep it concise" and produced a 2,698-character median, because "concise" is unfalsifiable and a model can believe it complied at any length:\n- Aim under 400 characters per message. NEVER hit that by cutting content: if you have more to say, send another message. Two short messages beat one wall, and both beat saying less than you meant.\n- Over ~800 characters of ONE indivisible thing (a diff, a table, a doc) it is not a message — attach it with commonly_attach_file and post one line saying what it is.\n- Post the RESULT, not your reasoning. The thinking earned the answer; it is not the answer. Reasoning belongs in a PR body or a doc.\n- Never open with a bold sentence. No section headers, no ✅/❌ lists, no pasted tables — those are report furniture and they are what make agent rooms unreadable.\n- Never narrate your own diligence ("noting this for the record", "stated precisely so it is not misread"). Delete those sentences entirely.\n- One idea per message. A second header means it should be two messages or a linked document.\n- Cap 3 messages per minute AND 3 in a row. The rate cap alone produced 24-message monologues: at 3/min sustained for seven minutes, one agent owned the entire room. A rate bounds how FAST you talk, never how LONG you hold the floor.\n- Before a 4th consecutive message with nobody else having spoken, STOP. Not "wrap up" — stop. A run of your own messages is a monologue whatever its rate, and the reader experiences it as one wall you pressed enter inside of. If the remaining material genuinely needs saying, it is a document: attach it and post one line.\n- Splitting is for one answer that does not fit, not for thinking out loud in public. Three messages answering one question is fine. Three messages arriving at an answer is reasoning, and the rule above already says reasoning does not go in the room.\n\nReply to what was actually said. If you would add nothing, do not post — in a 1:1 DM you may return the literal string NO_REPLY (and ONLY that string) to stay silent.\n\nThree addressing modes: a plain post broadcasts to the room; `replyToMessageId` addresses a specific message AND pings its author (matches the backend field name in ADR-004 §Message shape); `threadRootId` continues an existing thread WITHOUT pinging anyone — use it for follow-ups, elaboration, and anything past your first message on a topic. Prose overflow goes in a thread, not as consecutive top-level messages: post one top-level message, then put the detail in its thread by passing the first message\'s id as threadRootId.' + '\n\nCARD RULE: when a linear.*, sentry.* or atlassian.* list tool returns records, post them as ONE card, not bullet prose. Set messageType "card"; content is the same list as plain text (the fallback every reader sees); payload is {"kind":"ui","v":1,"lang":"openui@1","catalogId":"' + UI_CARD_CATALOGUE.revision.catalogId + '","catalogRev":' + UI_CARD_CATALOGUE.revision.catalogRev + ',"catalogHash":"' + UI_CARD_CATALOGUE.revision.catalogHash + '","source":""}. Call commonly_get_ui_card_catalogue first for the grammar. Links in a card must be credential-free https on an approved host.' + '\n\nIf a genuine fork needs a human to choose, call commonly_request_decision; include @human in the question when a specific person should rule, and let the tool post its own interactive card. Do not duplicate the ask in chat; status updates and ordinary questions remain messages.', + description: 'Post a chat message into a pod as this agent. If a 409 reports unseen messages, read them and retry, or pass continueAnyway:true to send despite them.\n\nOptional: `summary` is one line of at most 120 characters saying what the message is (no newlines), and `kind` is one of answer, result, progress, ask, fyi or error. A choice that needs a person to rule still goes through commonly_request_decision, not kind ask. Neither field is ever read for @mentions. A bad value never blocks the post; it comes back in `warnings`. What was stored comes back on `message.summary` and `message.kind`; the response\'s top-level `summary` is a different, older field (a pod summary record) and is usually null.\n\nA pod is a CHAT ROOM a human may scroll, not a report surface. These are hard constraints, not preferences — an earlier version of this text said "keep it concise" and produced a 2,698-character median, because "concise" is unfalsifiable and a model can believe it complied at any length:\n- Aim under 400 characters per message. NEVER hit that by cutting content: if you have more to say, send another message. Two short messages beat one wall, and both beat saying less than you meant.\n- Over ~800 characters of ONE indivisible thing (a diff, a table, a doc) it is not a message — attach it with commonly_attach_file and post one line saying what it is.\n- Post the RESULT, not your reasoning. The thinking earned the answer; it is not the answer. Reasoning belongs in a PR body or a doc.\n- Never open with a bold sentence. No section headers, no ✅/❌ lists, no pasted tables — those are report furniture and they are what make agent rooms unreadable.\n- Never narrate your own diligence ("noting this for the record", "stated precisely so it is not misread"). Delete those sentences entirely.\n- One idea per message. A second header means it should be two messages or a linked document.\n- Cap 3 messages per minute AND 3 in a row. The rate cap alone produced 24-message monologues: at 3/min sustained for seven minutes, one agent owned the entire room. A rate bounds how FAST you talk, never how LONG you hold the floor.\n- Before a 4th consecutive message with nobody else having spoken, STOP. Not "wrap up" — stop. A run of your own messages is a monologue whatever its rate, and the reader experiences it as one wall you pressed enter inside of. If the remaining material genuinely needs saying, it is a document: attach it and post one line.\n- Splitting is for one answer that does not fit, not for thinking out loud in public. Three messages answering one question is fine. Three messages arriving at an answer is reasoning, and the rule above already says reasoning does not go in the room.\n\nReply to what was actually said. If you would add nothing, do not post — in a 1:1 DM you may return the literal string NO_REPLY (and ONLY that string) to stay silent.\n\nThree addressing modes: a plain post broadcasts to the room; `replyToMessageId` addresses a specific message AND pings its author (matches the backend field name in ADR-004 §Message shape), and files your post in that message\'s thread, so do not use it to answer a top-level message you want answered in the channel; `threadRootId` continues an existing thread WITHOUT pinging anyone — use it for follow-ups, elaboration, and anything past your first message on a topic. Prose overflow goes in a thread, not as consecutive top-level messages: post one top-level message, then put the detail in its thread by passing the first message\'s id as threadRootId.' + '\n\nCARD RULE: when a linear.*, sentry.* or atlassian.* list tool returns records, post them as ONE card, not bullet prose. Set messageType "card"; content is the same list as plain text (the fallback every reader sees); payload is {"kind":"ui","v":1,"lang":"openui@1","catalogId":"' + UI_CARD_CATALOGUE.revision.catalogId + '","catalogRev":' + UI_CARD_CATALOGUE.revision.catalogRev + ',"catalogHash":"' + UI_CARD_CATALOGUE.revision.catalogHash + '","source":""}. Call commonly_get_ui_card_catalogue first for the grammar. Links in a card must be credential-free https on an approved host.' + '\n\nIf a genuine fork needs a human to choose, call commonly_request_decision; include @human in the question when a specific person should rule, and let the tool post its own interactive card. Do not duplicate the ask in chat; status updates and ordinary questions remain messages.', inputSchema: reqWith({ podId: STRING, content: STRING, diff --git a/docs/development/agent-experience-audit.md b/docs/development/agent-experience-audit.md index 7ea8a7df5d..f7802b451f 100644 --- a/docs/development/agent-experience-audit.md +++ b/docs/development/agent-experience-audit.md @@ -4367,3 +4367,14 @@ A person granted their agent GitHub through the grant broker, then revoked the g **Repair:** `grantRemovalCueService` adds one entry per agent to the grant's own `RoomGrant.removalCuePending` (ADR-034 D4 allows no new Mongo collection) when `revokeGrant` moves a live grant, which covers a direct revoke and a connection removal, and when a granter takes a named agent off a grant. `AgentEventService.enqueueEvent` claims the entries with an atomic `$pull` as it builds the agent's next `chat.mention` or `thread.mention`, and prepends one line to `payload.content`: "[access: GitHub access was removed by its owner. There is nothing to reconnect; ask them if you need it again.]". An entry whose agent holds a live grant on the same connector again is dropped unread. `backend/__tests__/service/grantRemovalCue.test.js` covers revoke, removal, re-grant, another agent and concurrent builds on real mongod. **Lesson:** when the kernel takes a capability away, a missing tool is not enough information for the agent. Say what changed and who changed it, inline, on the next turn. + +## 100. "Never set threadRootId" taught the seat that replyToMessageId stays top-level (2026-11-05, launch) + +*Origin: Growth's walk of CLI 0.1.258, after #3499 told a seat to answer a top-level mention top-level.* + +#3499 added a line beside each top-level mention: post your answer top-level, and never set `threadRootId` to this message's id. On the next walk the mention shared a turn with the seat's greeting. The seat obeyed the line as written and posted through `commonly_post_message` with `replyToMessageId` set to the mention instead. The kernel files every reply in its parent's thread (`COALESCE(parent.thread_root_id, parent.id)` in `models/pg/Message.ts`), so the answer threaded anyway. The MCP tool's description fed the wrong model: it said `replyToMessageId` "addresses a specific message AND pings its author" and `threadRootId` "continues an existing thread", which reads as if only the second one threads. + +**Repair:** #3511. The cue names both fields and says why: a reply is filed in the thread of the message it replies to. The MCP description of `replyToMessageId` says it files the post in that message's thread. + +**Lesson:** a prohibition that names one field reads as permission for its sibling. When two fields reach the same storage effect, name the effect, and name every field that causes it. + From 0665bc0a5b1379b097548a4198562c968c2f7e3d Mon Sep 17 00:00:00 2001 From: Lily Shen <115414357+lilyshen0722@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:32:19 -0800 Subject: [PATCH 4/6] fix(cli): the greeting hold ignores digest rows, keeps to the clock, and never overflows the prompt CodeRabbit on #3511: - A digest row from the greeting's pod made the group mixed, so the greeting ran at once. Digest rows now ride along without counting as a person. - The window counted polls only, so long turns for other pods between polls could stretch the carry. It is now bounded by GREETING_HOLD_MS on the clock as well, so the carried greeting's age at release is what one poll already allowed on main. - A carried greeting joining a full page from the same pod made the group one longer than the prompt's body cap; the last event was acked unseen. The greeting is carried again instead. Two tests are red without the fix. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MDs9DT6tbhKm6UhsmFhLk9 --- cli/__tests__/inbox-join-priority.test.mjs | 45 +++++++++++++++++++++- cli/src/commands/agent.js | 27 +++++++++++-- 2 files changed, 68 insertions(+), 4 deletions(-) diff --git a/cli/__tests__/inbox-join-priority.test.mjs b/cli/__tests__/inbox-join-priority.test.mjs index 68ac248689..4af28409df 100644 --- a/cli/__tests__/inbox-join-priority.test.mjs +++ b/cli/__tests__/inbox-join-priority.test.mjs @@ -88,7 +88,7 @@ const drainMicrotasks = async () => { // A claim-once inbox: each /events call returns everything currently pending // and marks it taken, exactly like claimPage. `arrivals[i]` is what lands in // the inbox before tick i. -const runTicks = async ({ arrivals, ticks = 2, spawn }) => { +const runTicks = async ({ arrivals, ticks = 2, spawn, runOptions = {} }) => { const delays = []; const acked = []; let pending = []; @@ -129,6 +129,7 @@ const runTicks = async ({ arrivals, ticks = 2, spawn }) => { instanceId: 'default', intervalMs: INTERVAL, setTimeoutImpl, + ...runOptions, }); for (let i = 0; i < ticks; i += 1) { // eslint-disable-next-line no-await-in-loop @@ -263,6 +264,48 @@ describe('a waiting person outranks the seat\'s own join turn', () => { expect(acked).toEqual([]); }); + // CodeRabbit on #3511: a digest row from the same pod made the greeting's + // group mixed, so it ran at once instead of being held. + test('a digest row beside the greeting does not stop the hold', async () => { + const spawn = jest.fn(async () => ({ text: 'hello' })); + const digestRow = { + _id: 'evt-digest', type: 'chat.message', deliveryMode: 'digest', podId: POD, + agentName: 'my-stub', instanceId: 'default', payload: { content: 'ambient chatter', messageId: 'msg-d' }, + }; + const { acked } = await runTicks({ arrivals: [[joinEvent, digestRow]], ticks: HOLD_POLLS, spawn }); + + expect(spawn).not.toHaveBeenCalled(); + expect(acked).toEqual([]); + }); + + // CodeRabbit on #3511: a carried greeting joining a full page from the same + // pod made the group one longer than the prompt's body cap, and the last + // event was acked without the model seeing it. + test('a carried greeting never pushes a full page past the body cap', async () => { + const LIMIT = 3; + const spawn = jest.fn(async () => ({ text: 'ok' })); + const page = [1, 2, 3].map((n) => ({ + ...mentionEvent, _id: `evt-m${n}`, payload: { content: `question ${n}`, messageId: `msg-${n}` }, + })); + const { acked } = await runTicks({ + arrivals: [[joinEvent], page], + ticks: HOLD_POLLS + 3, + spawn, + runOptions: { inboxBatchLimit: LIMIT }, + }); + + for (const [prompt] of spawn.mock.calls) { + const bodies = (prompt.match(/^Event \d+\/\d+:/gm) || []).length; + expect(bodies).toBeLessThanOrEqual(LIMIT); + } + const prompts = spawn.mock.calls.map(([prompt]) => prompt).join('\n'); + for (const id of acked) { + if (id === 'evt-join') expect(prompts).toContain('A human just added you to this workspace.'); + else expect(prompts).toContain(`question ${id.replace('evt-m', '')}`); + } + expect(acked.sort()).toEqual(['evt-join', 'evt-m1', 'evt-m2', 'evt-m3']); + }); + test('only the connect-time greeting is held: once it has run, a later one is not carried', async () => { const spawn = jest.fn(async () => ({ text: 'hi' })); const later = { ...joinEvent, _id: 'evt-join-2' }; diff --git a/cli/src/commands/agent.js b/cli/src/commands/agent.js index 8ee054c3c8..8212119b4c 100644 --- a/cli/src/commands/agent.js +++ b/cli/src/commands/agent.js @@ -3008,6 +3008,7 @@ export const performRun = ({ let greetingHoldSpent = false; // Polls the connect-time greeting has been carried, against the window. let greetingHeldPolls = 0; + let greetingHoldStartedAt = null; const greetingHoldPolls = Math.max(1, Math.ceil(GREETING_HOLD_MS / Math.max(1, Number(intervalMs) || 1))); // The same is true of a batch whose turn FAILED: its events are claimed, so @@ -3533,7 +3534,19 @@ export const performRun = ({ group.push(event); eventGroups.set(key, group); } - const groups = [...eventGroups.values()]; + // A carried greeting must not push a full page past the prompt's body + // cap: an event past the cap gets no body yet is acked with the batch + // (CodeRabbit on #3511). Carry the greeting again instead. + for (const [key, group] of eventGroups) { + const wakeCount = group.filter((event) => event.deliveryMode !== 'digest').length; + if (wakeCount <= batchLimit) continue; + const overflow = group.filter((event) => carriedIds.has(String(event._id)) + && DEFERRABLE_SOLO_EVENT_TYPES.has(event.type)); + if (!overflow.length) continue; + heldGreeting = [...heldGreeting, ...overflow]; + eventGroups.set(key, group.filter((event) => !overflow.includes(event))); + } + const groups = [...eventGroups.values()].filter((group) => group.length > 0); // The greeting window is counted once per poll, however many pods' // greetings this page carries (gate review of #3511). let greetingCarriedThisPoll = false; @@ -3557,8 +3570,15 @@ export const performRun = ({ // agent in that window is answered first, in the same turn, instead // of behind a greeting. Only the connect-time greeting is held: once // a turn has carried one, later greetings run as they arrive. - if (!greetingHoldSpent && (greetingCarriedThisPoll || greetingHeldPolls < greetingHoldPolls) - && group.every((event) => DEFERRABLE_SOLO_EVENT_TYPES.has(event.type))) { + // Digest rows ride along with a greeting without counting as a + // person waiting (CodeRabbit on #3511). The window is bounded by the + // clock too, so turns run for other pods between polls can't stretch + // the carry past its delivery lease (CodeRabbit on #3511). + if (!greetingHoldSpent + && (greetingCarriedThisPoll || (greetingHeldPolls < greetingHoldPolls + && (greetingHoldStartedAt === null || Date.now() - greetingHoldStartedAt < GREETING_HOLD_MS))) + && group.some((event) => DEFERRABLE_SOLO_EVENT_TYPES.has(event.type)) + && group.every((event) => DEFERRABLE_SOLO_EVENT_TYPES.has(event.type) || event.deliveryMode === 'digest')) { if (greetingHeldPolls === 0 && !greetingCarriedThisPoll) { log(`[inbox.batch] carrying ${group.length} greeting event(s) for up to ` + `${Math.round(GREETING_HOLD_MS / 1000)} s, so a person who mentions this agent is answered first`); @@ -3566,6 +3586,7 @@ export const performRun = ({ if (!greetingCarriedThisPoll) { greetingCarriedThisPoll = true; greetingHeldPolls += 1; + if (greetingHoldStartedAt === null) greetingHoldStartedAt = Date.now(); } // Appended, never assigned: two pods' greetings can be carried in // the same window, and an overwrite left the first unacked until From b3e30d1189bb3a99cdeb08264b2b53d0df63e091 Mon Sep 17 00:00:00 2001 From: Lily Shen <115414357+lilyshen0722@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:56:46 -0800 Subject: [PATCH 5/6] fix(cli): the poll leaves room for what the loop carries, so a busy pod can't keep the greeting out CodeRabbit on #3511: with a full page arriving every poll, the overflow pass re-carried the greeting each time, holding it until the server's requeue. The poll now asks for batchLimit minus the events it carries (held greeting or failed batch), so a carried event always fits beside the page. This also closes the same overflow for carried retries, which predated this PR. The overflow pass stays as a backstop. The test fixture now honors the page limit; a test with consecutive full pages is red without the fix. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MDs9DT6tbhKm6UhsmFhLk9 --- cli/__tests__/inbox-join-priority.test.mjs | 36 +++++++++++++++++++--- cli/src/commands/agent.js | 7 ++++- 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/cli/__tests__/inbox-join-priority.test.mjs b/cli/__tests__/inbox-join-priority.test.mjs index 4af28409df..a2eac101c6 100644 --- a/cli/__tests__/inbox-join-priority.test.mjs +++ b/cli/__tests__/inbox-join-priority.test.mjs @@ -93,13 +93,15 @@ const runTicks = async ({ arrivals, ticks = 2, spawn, runOptions = {} }) => { const acked = []; let pending = []; let poll = 0; - const mockGet = jest.fn(async (routePath) => { + const mockGet = jest.fn(async (routePath, params = {}) => { if (String(routePath).includes('/events')) { pending = pending.concat(arrivals[poll] || []); poll += 1; - const claimed = pending; - pending = []; - return { events: claimed, inboxCount: claimed.length }; + // claimPage honors the requested limit; the rest stays pending. + const limit = Number.isFinite(params.limit) ? params.limit : pending.length; + const claimed = pending.slice(0, limit); + pending = pending.slice(limit); + return { events: claimed, inboxCount: claimed.length + pending.length }; } return {}; }); @@ -306,6 +308,32 @@ describe('a waiting person outranks the seat\'s own join turn', () => { expect(acked.sort()).toEqual(['evt-join', 'evt-m1', 'evt-m2', 'evt-m3']); }); + // CodeRabbit on #3511: with a full page arriving on every poll, re-carrying + // an overflowing greeting kept it back far past the window. The poll now + // asks for fewer events while some are carried, so the carry always fits. + test('consecutive full pages: the greeting still runs, in a turn within the body cap', async () => { + const LIMIT = 3; + const spawn = jest.fn(async () => ({ text: 'ok' })); + const fullPage = (poll) => [1, 2, 3].map((n) => ({ + ...mentionEvent, _id: `evt-p${poll}-${n}`, payload: { content: `q ${poll}.${n}`, messageId: `msg-${poll}-${n}` }, + })); + const arrivals = [[joinEvent], ...Array.from({ length: 6 }, (_, i) => fullPage(i + 1))]; + const { acked, mockGet } = await runTicks({ + arrivals, ticks: 8, spawn, runOptions: { inboxBatchLimit: LIMIT }, + }); + + expect(acked).toContain('evt-join'); + for (const [prompt] of spawn.mock.calls) { + expect((prompt.match(/^Event \d+\/\d+:/gm) || []).length).toBeLessThanOrEqual(LIMIT); + } + // While the greeting was carried, the poll left room for it. + const limits = mockGet.mock.calls + .filter(([route]) => String(route).includes('/events')) + .map(([, params]) => params.limit); + expect(limits[0]).toBe(LIMIT); + expect(limits[1]).toBe(LIMIT - 1); + }); + test('only the connect-time greeting is held: once it has run, a later one is not carried', async () => { const spawn = jest.fn(async () => ({ text: 'hi' })); const later = { ...joinEvent, _id: 'evt-join-2' }; diff --git a/cli/src/commands/agent.js b/cli/src/commands/agent.js index 8212119b4c..5351144b16 100644 --- a/cli/src/commands/agent.js +++ b/cli/src/commands/agent.js @@ -3485,8 +3485,13 @@ export const performRun = ({ // The liveness clock runs from here until the next scheduled wait, paused // only while a model turn runs (lib/poll-liveness.js). pollLiveness.arm(); + // Leave room for what this loop carries (a held greeting, a failed + // batch), so a carried event never pushes a full page past the prompt's + // body cap and a busy pod can't keep the greeting out (CodeRabbit on + // #3511). The overflow pass below stays as the backstop. + const carriedCount = heldRetry.length + heldGreeting.length; const page = await client.get('/api/agents/runtime/events', { - agentName, instanceId, limit: batchLimit, + agentName, instanceId, limit: Math.max(1, batchLimit - carriedCount), ...(adapter?.name ? { reportedCli: adapter.name } : {}), }); pollLiveness.arm(); From 405393f44217ac9334cbeb3e9ae5527f15188121 Mon Sep 17 00:00:00 2001 From: Lily Shen <115414357+lilyshen0722@users.noreply.github.com> Date: Thu, 5 Nov 2026 04:06:10 -0800 Subject: [PATCH 6/6] fix(cli): carried digest rows don't take wake capacity from the next poll CodeRabbit on #3511: a greeting carried with nine digest rows made the next poll ask for one event, so a later mention could wait a turn. Only carried wake events count against the page now. The two-pod hold test now delivers the greetings on successive polls, as a real one-pod page would. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MDs9DT6tbhKm6UhsmFhLk9 --- cli/__tests__/inbox-join-priority.test.mjs | 21 ++++++++++++++++++++- cli/src/commands/agent.js | 5 ++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/cli/__tests__/inbox-join-priority.test.mjs b/cli/__tests__/inbox-join-priority.test.mjs index a2eac101c6..f6348da774 100644 --- a/cli/__tests__/inbox-join-priority.test.mjs +++ b/cli/__tests__/inbox-join-priority.test.mjs @@ -256,8 +256,9 @@ describe('a waiting person outranks the seat\'s own join turn', () => { test('a second pod\'s greeting does not spend the window early', async () => { const spawn = jest.fn(async () => ({ text: 'hello' })); const joinB = { ...joinEvent, _id: 'evt-join-b', podId: 'pod-other' }; + // A real page holds one pod, so the second greeting lands on the next poll. const { acked } = await runTicks({ - arrivals: [[joinEvent, joinB]], + arrivals: [[joinEvent], [joinB]], ticks: HOLD_POLLS, spawn, }); @@ -334,6 +335,24 @@ describe('a waiting person outranks the seat\'s own join turn', () => { expect(limits[1]).toBe(LIMIT - 1); }); + // CodeRabbit on #3511: digest rows carried with the greeting took wake + // capacity, so a greeting page full of digests shrank the next poll to one. + test('carried digest rows do not shrink the next poll', async () => { + const LIMIT = 10; + const spawn = jest.fn(async () => ({ text: 'ok' })); + const digests = Array.from({ length: 9 }, (_, i) => ({ + _id: `evt-d${i}`, type: 'chat.message', deliveryMode: 'digest', podId: POD, + agentName: 'my-stub', instanceId: 'default', payload: { content: `ambient ${i}`, messageId: `msg-d${i}` }, + })); + const { mockGet } = await runTicks({ + arrivals: [[joinEvent, ...digests]], ticks: 3, spawn, runOptions: { inboxBatchLimit: LIMIT }, + }); + const limits = mockGet.mock.calls + .filter(([route]) => String(route).includes('/events')) + .map(([, params]) => params.limit); + expect(limits[1]).toBe(LIMIT - 1); + }); + test('only the connect-time greeting is held: once it has run, a later one is not carried', async () => { const spawn = jest.fn(async () => ({ text: 'hi' })); const later = { ...joinEvent, _id: 'evt-join-2' }; diff --git a/cli/src/commands/agent.js b/cli/src/commands/agent.js index 5351144b16..5548db98ff 100644 --- a/cli/src/commands/agent.js +++ b/cli/src/commands/agent.js @@ -3489,7 +3489,10 @@ export const performRun = ({ // batch), so a carried event never pushes a full page past the prompt's // body cap and a busy pod can't keep the greeting out (CodeRabbit on // #3511). The overflow pass below stays as the backstop. - const carriedCount = heldRetry.length + heldGreeting.length; + // Only wake events count: the server's page cap is on wakes, and a + // carried digest row takes no body (CodeRabbit on #3511). + const carriedCount = [...heldRetry, ...heldGreeting] + .filter((event) => event.deliveryMode !== 'digest').length; const page = await client.get('/api/agents/runtime/events', { agentName, instanceId, limit: Math.max(1, batchLimit - carriedCount), ...(adapter?.name ? { reportedCli: adapter.name } : {}),