Skip to content

Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.

TypeScript

fix(agent): let an agent deliver the work it announced, in the same turn (#268)

Xialie Zhuang4da88e337e6a
diff --git a/server/src/__integration__/agent-anti-duplicate.test.ts b/server/src/__integration__/agent-anti-duplicate.test.ts
index 5251a1b..f2339b9 100644
--- a/server/src/__integration__/agent-anti-duplicate.test.ts
+++ b/server/src/__integration__/agent-anti-duplicate.test.ts
@@ -306,25 +306,42 @@ test('[integration] the relay delivers that result, body intact', async () => {
assert.equal(rows[0].body, body, 'the answer must arrive whole, not empty')
})
-test('[integration] the bypass flag has to come after the body', async () => {
+test('[unit] the bypass flag has to come after the body', async () => {
// parseArgs reads `--continue <token>` as a VALUE flag, so putting the flag
- // before the body consumes the body: the gate is bypassed and an EMPTY
- // message is posted. Pin the ordering, because moving the flag to the front
- // reads like a harmless tidy-up.
+ // before the body consumes the body and posts an EMPTY message. Pin the
+ // ordering, because moving the flag to the front reads like a tidy-up.
+ //
+ // Asserted on parseArgs directly and unconditionally. The first version of
+ // this test wrapped its assertion in `if (wrongOrder.ok)`, which meant it
+ // could pass without checking anything — thanks to @yetone for catching it.
+ const { parseArgs } = await import('../agents/cli-parse.js')
+
+ const wrong = parseArgs(['reply', 'g-1', '--continue', 'the actual answer'])
+ assert.equal(wrong.flags.continue, 'the actual answer',
+ 'parseArgs takes the next token as the flag VALUE')
+ assert.deepEqual(wrong.positional, ['reply', 'g-1'],
+ 'so the body is gone entirely — flag-before-body posts an empty message')
+
+ const right = parseArgs(['reply', 'g-1', 'the actual answer', '--continue'])
+ assert.equal(right.flags.continue, true, 'trailing flag parses as a boolean')
+ assert.deepEqual(right.positional, ['reply', 'g-1', 'the actual answer'],
+ 'and the body survives')
+})
+
+test('[integration] flag-before-body does not post the body', async () => {
+ // The same trap through the real CLI, asserted unconditionally this time.
const { agentA, convoId } = await seedGroupWithTwoAgents()
await runCli(['--as', agentA, 'reply', convoId, 'Drafting the email now — ~30s'])
- const wrongOrder = await runCli(['--as', agentA, 'reply', convoId, '--continue', 'the actual answer'])
+ await runCli(['--as', agentA, 'reply', convoId, '--continue', 'the actual answer'])
const { rows } = await pool.query<{ body: string }>(
`SELECT body FROM messages WHERE conversation_id = $1 ORDER BY sequence DESC LIMIT 1`,
[convoId],
)
- if (wrongOrder.ok) {
- assert.notEqual(
- rows[0].body, 'the actual answer',
- 'flag-before-body must not be adopted: parseArgs eats the body as the flag value',
- )
- }
+ assert.notEqual(
+ rows[0].body, 'the actual answer',
+ 'flag-before-body must never be adopted: parseArgs eats the body as the flag value',
+ )
})
test('[integration] a plain second post is still refused', async () => {
@@ -350,3 +367,117 @@ test('[unit] the declared relay carries the bypass, last', async () => {
'the declared relay no longer bypasses the anti-monologue gate — after the intent message the rules require, the agent\'s answer is refused and the room gets a failure notice instead',
)
})
+
+// ─── announce, then deliver, in the same turn ──────────────────────
+//
+// The operating rules require an intent message before long work, posted as a
+// SEPARATE `cumora reply`, then the result "in this SAME turn". In a group of
+// three or more that intent message is the room's last message and seconds
+// old, which is exactly what the gate refuses — so the flow the product
+// mandates was the flow it rejected, and the answer was lost.
+//
+// #263 fixed the runtime's own auto-relay by giving it --continue. It could
+// not fix this one: `postedReplyViaTool` is set the moment the intent message
+// lands and never reset within a turn, and the relay branch is guarded on
+// `!postedReplyViaTool`, so once the agent announces, the relay is switched
+// off for the rest of that turn. The second post is the model calling
+// `cumora reply` itself, and it reached the gate with nothing to distinguish
+// it from a monologue.
+//
+// The run id is that distinction, and it now reaches the CLI as CUMORA_RUN_ID.
+
+async function withRunId<T>(runId: string | null, fn: () => Promise<T>): Promise<T> {
+ const previous = process.env.CUMORA_RUN_ID
+ if (runId === null) delete process.env.CUMORA_RUN_ID
+ else process.env.CUMORA_RUN_ID = runId
+ try {
+ return await fn()
+ } finally {
+ if (previous === undefined) delete process.env.CUMORA_RUN_ID
+ else process.env.CUMORA_RUN_ID = previous
+ }
+}
+
+test('[integration] the mandated announce-then-deliver flow goes through', async () => {
+ const { agentA, convoId } = await seedGroupWithTwoAgents()
+ const runId = `run-${randomUUID().slice(0, 8)}`
+
+ await withRunId(runId, async () => {
+ const intent = await runCli(['--as', agentA, 'reply', convoId, 'Drafting the email now — ~30s'])
+ assert.equal(intent.ok, true, `the intent message the rules require must post: ${intent.text}`)
+
+ // …30 seconds of work later, the result. Same turn, so same run.
+ const answer = await runCli(['--as', agentA, 'reply', convoId, 'Here is the draft: subject, three paragraphs, CTA.'])
+ assert.equal(answer.ok, true, `the answer the intent message promised must post: ${answer.text}`)
+ })
+
+ const { rows } = await pool.query<{ body: string }>(
+ `SELECT body FROM messages WHERE conversation_id = $1 AND author_id = $2 ORDER BY sequence`,
+ [convoId, agentA],
+ )
+ assert.equal(rows.length, 2, 'the room should have the intent message and the answer')
+ assert.match(rows[1].body, /Here is the draft/)
+})
+
+test('[integration] a later run is still refused — that is the gate doing its job', async () => {
+ // The whole point of the gate: "each wake-up is a fresh 'should I respond?'
+ // decision with no global stop-signal". A different run is a different
+ // decision, however recently the last message landed.
+ const { agentA, convoId } = await seedGroupWithTwoAgents()
+
+ await withRunId(`run-${randomUUID().slice(0, 8)}`, async () => {
+ const first = await runCli(['--as', agentA, 'reply', convoId, 'first'])
+ assert.equal(first.ok, true)
+ })
+ await withRunId(`run-${randomUUID().slice(0, 8)}`, async () => {
+ const second = await runCli(['--as', agentA, 'reply', convoId, 'a fresh decision to talk again'])
+ assert.equal(second.ok, false, 'a new wake-up must not inherit the previous turn\'s exemption')
+ assert.match(second.text, /you already posted in/)
+ })
+})
+
+test('[integration] a third post in one turn is monologuing again', async () => {
+ // Announce + deliver is two. The exemption is capped there on purpose.
+ const { agentA, convoId } = await seedGroupWithTwoAgents()
+ const runId = `run-${randomUUID().slice(0, 8)}`
+
+ await withRunId(runId, async () => {
+ assert.equal((await runCli(['--as', agentA, 'reply', convoId, 'on it'])).ok, true)
+ assert.equal((await runCli(['--as', agentA, 'reply', convoId, 'here it is'])).ok, true)
+ const third = await runCli(['--as', agentA, 'reply', convoId, 'and one more thought'])
+ assert.equal(third.ok, false, 'the exemption must not become an unlimited licence')
+ assert.match(third.text, /you already posted in/)
+ })
+})
+
+test('[integration] a continuation is still checked against a room that moved', async () => {
+ // The guard rail that separates this from --continue. That flag also
+ // disables the freshness preflight; this exemption must not, or an agent
+ // could deliver a stale answer a peer already gave while it was working.
+ const { agentA, agentB, convoId } = await seedGroupWithTwoAgents()
+ const runId = `run-${randomUUID().slice(0, 8)}`
+
+ await withRunId(runId, async () => {
+ assert.equal((await runCli(['--as', agentA, 'reply', convoId, 'on it — ~30s'])).ok, true)
+ })
+ // A peer delivers the same thing while A works.
+ assert.equal((await runCli(['--as', agentB, 'reply', convoId, 'The answer is 42.'])).ok, true)
+
+ await withRunId(runId, async () => {
+ const late = await runCli(['--as', agentA, 'reply', convoId, 'The answer is 42.'])
+ assert.equal(late.ok, false, 'the freshness preflight must still apply to a same-turn delivery')
+ assert.match(late.text, /HELD/)
+ })
+})
+
+test('[integration] with no run id the gate behaves exactly as before', async () => {
+ // The CLI, replay and boot paths carry no CUMORA_RUN_ID. They must not get
+ // an exemption they cannot justify.
+ const { agentA, convoId } = await seedGroupWithTwoAgents()
+ await withRunId(null, async () => {
+ assert.equal((await runCli(['--as', agentA, 'reply', convoId, 'first'])).ok, true)
+ const second = await runCli(['--as', agentA, 'reply', convoId, 'second'])
+ assert.equal(second.ok, false, 'no run id means no exemption')
+ assert.match(second.text, /you already posted in/)
+ })
+})
diff --git a/server/src/agents/cli.ts b/server/src/agents/cli.ts
index ebcbf4b..03be578 100644
--- a/server/src/agents/cli.ts
+++ b/server/src/agents/cli.ts
@@ -176,7 +176,10 @@ import { resolveAs } from './cli-identity.js'
*/
import { inprocClient as worklogClient } from './runtime/inproc-client.js'
import type { WorkTaskType, WorklogEntry } from './runtime/client.js'
-import { recordSeen, getSeen, recordHold, consumeHold, clearHold } from './seen-boundary.js'
+import {
+ recordSeen, getSeen, recordHold, consumeHold, clearHold,
+ readTurnPost, recordTurnPost, MAX_POSTS_PER_TURN_PER_CONVERSATION,
+} from './seen-boundary.js'
function tenantScopeKey(companyId: string): string {
return `tenant:${companyId}`
@@ -1872,7 +1875,32 @@ async function cmdReply(parsed: ParsedArgs): Promise<CliResult> {
// forces the agent to commit deliberately rather than absent-
// mindedly continuing to monologue.
const monologueBypass = Boolean(parsed.flags.continue || parsed.flags.also)
- if (!monologueBypass && cv[0].actor_is_agent && cv[0].member_count > 2) {
+ // Announce-then-deliver. The operating rules REQUIRE an intent message
+ // before long work ("Drafting the email now"), posted as a SEPARATE
+ // `cumora reply`, then the result in the SAME turn. In a group of three or
+ // more that intent message is the room's last message and seconds old,
+ // which is exactly what the gate below refuses — so the flow the product
+ // mandates was the flow it rejected, and the answer was lost.
+ //
+ // A second post from the SAME run is that delivery. A post from a LATER run
+ // is the agent waking up and deciding to talk again, which is what the gate
+ // was built to stop ("each wake-up is a fresh 'should I respond?' decision
+ // with no global stop-signal"). The run id is the only thing that tells them
+ // apart, so it now reaches this process as CUMORA_RUN_ID.
+ //
+ // Capped at two posts per turn per conversation: announce + deliver. A third
+ // is monologuing again and still needs --continue.
+ //
+ // Deliberately NOT folded into `monologueBypass`: that flag also disables
+ // the freshness preflight further down, and a continuation must still be
+ // checked against a room that moved while we were working.
+ const turnRunId = (process.env.CUMORA_RUN_ID ?? '').trim()
+ const sameTurnDelivery = !monologueBypass && turnRunId && cv[0].actor_is_agent
+ ? await readTurnPost(me, convoId).then(
+ (rec) => Boolean(rec && rec.runId === turnRunId && rec.posts < MAX_POSTS_PER_TURN_PER_CONVERSATION),
+ )
+ : false
+ if (!monologueBypass && !sameTurnDelivery && cv[0].actor_is_agent && cv[0].member_count > 2) {
const { rows: lastMsg } = await pool.query<{ author_id: string; created_at: string }>(
`SELECT author_id, created_at FROM messages
WHERE conversation_id = $1
@@ -2406,6 +2434,10 @@ async function cmdReply(parsed: ParsedArgs): Promise<CliResult> {
await recordSeen(me, convoId, sequence).catch((error) => {
console.warn(`[reply] message ${messageId} committed but seen-boundary update failed`, error)
})
+ // Remember which run posted this, so the announce-then-deliver exemption
+ // above can recognise the delivery that follows an intent message — and
+ // stop recognising it after the second post.
+ if (turnRunId) await recordTurnPost(me, convoId, turnRunId)
// Drop any lingering hold token: this send committed WITHOUT the
// override, so a hold acknowledged-but-unused must not arm a later
// preemptive --send-anyway in this conversation.
diff --git a/server/src/agents/runtime/pod-tools.ts b/server/src/agents/runtime/pod-tools.ts
index b18fcdc..4fe4589 100644
--- a/server/src/agents/runtime/pod-tools.ts
+++ b/server/src/agents/runtime/pod-tools.ts
@@ -53,6 +53,9 @@ interface DispatchArgs {
* with no payoff. turn.ts uses this to interrupt a long-running
* bash when a user steer arrives mid-tool. */
signal?: AbortSignal
+ /** The run this tool call belongs to. Only `bash` uses it, to reach
+ * `cumora reply` as CUMORA_RUN_ID — see the anti-monologue gate. */
+ runId?: string
}
function noNamespace(name: string, _wanted: string): ToolResult {
@@ -83,7 +86,7 @@ export async function executePodTool(args: DispatchArgs): Promise<ToolResult> {
switch (args.name) {
case 'shell':
case 'bash':
- return tBash(parsed, args.agentId, args.ns ?? null, args.signal)
+ return tBash(parsed, args.agentId, args.ns ?? null, args.signal, args.runId)
case 'set_turn_status':
return tSetTurnStatus(parsed)
case 'read_file':
diff --git a/server/src/agents/seen-boundary.ts b/server/src/agents/seen-boundary.ts
index bf24dd0..aefe757 100644
--- a/server/src/agents/seen-boundary.ts
+++ b/server/src/agents/seen-boundary.ts
@@ -271,3 +271,88 @@ export async function clearHold(agentId: string, scope: string): Promise<void> {
/* fail-open — TTL will reclaim it */
}
}
+
+// ─── same-turn continuation ────────────────────────────────────────
+//
+// The anti-monologue gate asks "is my own last message in this room something
+// I decided to post, or the intent message of the work I am doing right now?"
+// It could not tell, because nothing recorded WHICH run posted a message.
+//
+// The operating rules require an intent message before long work ("Drafting
+// the email now"), a SEPARATE `cumora reply`, then the result in the SAME
+// turn. In a group of three or more the gate refused that second call, so the
+// flow the product mandates was the flow it rejected.
+//
+// A run id plus a count is enough to separate the two: a second post from the
+// SAME run is the announced work being delivered; a post from a LATER run is
+// the agent waking up and deciding to talk again, which is what the gate was
+// built to stop. The count caps it at announce-then-deliver — a third post in
+// one turn is monologuing again, and still needs `--continue`.
+
+const TURN_POST_TTL_SECONDS = 600 // matches the gate's 10-minute window
+const TURN_POST_PREFIX = 'cumora:turnpost'
+
+function turnPostKey(agentId: string, conversationId: string): string {
+ return `${TURN_POST_PREFIX}:${agentId}:${conversationId}`
+}
+
+/** Posts this run has already made in this conversation. */
+export interface TurnPostRecord {
+ runId: string
+ posts: number
+}
+
+/** Record that `runId` just posted in `conversationId`. Increments when the
+ * same run posts again, resets when a new run takes over. Fire-and-forget:
+ * a failure only costs the exemption, never a message. */
+export async function recordTurnPost(
+ agentId: string, conversationId: string, runId: string,
+): Promise<void> {
+ if (!agentId || !conversationId || !runId) return
+ try {
+ const key = turnPostKey(agentId, conversationId)
+ const existing = await redis.get(key)
+ const prior = parseTurnPost(existing)
+ const posts = prior && prior.runId === runId ? prior.posts + 1 : 1
+ await redis.set(key, `${runId}:${posts}`, 'EX', TURN_POST_TTL_SECONDS)
+ } catch (err) {
+ console.warn(
+ `[seen-boundary] recordTurnPost(${agentId}, ${conversationId}) failed`,
+ err instanceof Error ? err.message : err,
+ )
+ }
+}
+
+/** What this agent last posted in this conversation, and from which run.
+ * Returns null when unknown — the caller must then behave exactly as it did
+ * before this existed, which for the gate means refusing. FAIL-CLOSED on a
+ * Redis error: an infra hiccup must not hand out a monologue exemption. */
+export async function readTurnPost(
+ agentId: string, conversationId: string,
+): Promise<TurnPostRecord | null> {
+ if (!agentId || !conversationId) return null
+ try {
+ return parseTurnPost(await redis.get(turnPostKey(agentId, conversationId)))
+ } catch (err) {
+ console.warn(
+ `[seen-boundary] readTurnPost(${agentId}, ${conversationId}) failed — fail-closed`,
+ err instanceof Error ? err.message : err,
+ )
+ return null
+ }
+}
+
+/** `<runId>:<posts>`. The run id itself never contains a colon (see
+ * createRun), so splitting on the LAST one is unambiguous either way. */
+export function parseTurnPost(raw: string | null | undefined): TurnPostRecord | null {
+ if (!raw) return null
+ const idx = raw.lastIndexOf(':')
+ if (idx <= 0) return null
+ const runId = raw.slice(0, idx)
+ const posts = Number.parseInt(raw.slice(idx + 1), 10)
+ if (!runId || !Number.isFinite(posts) || posts < 1) return null
+ return { runId, posts }
+}
+
+/** Announce-then-deliver is two posts. A third is monologuing again. */
+export const MAX_POSTS_PER_TURN_PER_CONVERSATION = 2
diff --git a/server/src/agents/tools-shared.ts b/server/src/agents/tools-shared.ts
index aad64fe..1a4dac5 100644
--- a/server/src/agents/tools-shared.ts
+++ b/server/src/agents/tools-shared.ts
@@ -398,6 +398,12 @@ export async function tBash(
* turn.ts's hop loop. Already-fired signals abort the spawn
* immediately so we never start a process the caller has cancelled. */
signal?: AbortSignal,
+ /** The run this bash call belongs to. Reaches `cumora reply` as
+ * CUMORA_RUN_ID so the anti-monologue gate can tell "I am delivering the
+ * work I announced this turn" from "I woke up and decided to talk again".
+ * Absent for the CLI/replay/boot paths, where the gate keeps its old
+ * behaviour. */
+ runId?: string,
): Promise<ToolResult> {
const t0 = Date.now()
const command = String(args.command ?? '').trim()
@@ -467,6 +473,7 @@ export async function tBash(
: {}),
CUMORA_PERSONA_DIR: ns?.rootDir ?? '',
CUMORA_CLI_RESULT_PATH: resultPath,
+ ...(runId ? { CUMORA_RUN_ID: runId } : {}),
}
const heavyOp = /--generate-image|web-(search|read)|skills\s+(install|search)/i.test(command)
diff --git a/server/src/agents/turn.ts b/server/src/agents/turn.ts
index 7f06611..23366c4 100644
--- a/server/src/agents/turn.ts
+++ b/server/src/agents/turn.ts
@@ -2928,6 +2928,7 @@ Mechanics:
}).catch(() => { /* observability best-effort */ })
try {
const result = await executePodTool({
+ runId,
agentId, name: tc.name, argsJson: tc.arguments, ns: namespace,
signal: batchAbortController.signal,
})
@@ -3254,6 +3255,7 @@ Mechanics:
// a value flag, so placing it before the body would consume the body and
// post an empty message.
const relay = await executePodTool({
+ runId,
agentId, name: 'bash',
argsJson: JSON.stringify({ command: `cumora reply ${target.conversationId} ${escaped} --continue` }),
ns: namespace,