Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,46 @@ describe('agent freshness: delayed Mongo-only write', () => {
expect(hold.unseenCount).toBe(22);
expect(hold.messages[0].content).toBe('delayed older timestamp');
});
// F536, from Growth's #2580 prod walk: a fresh webhook agent was held at 35
// unseen, its context reads never cleared it, and the hold said only "read
// the conversation". Past one context read, the hold names catch-up, and
// following it clears the hold.
it('names catch-up for a backlog one context read cannot clear, and catch-up clears it', async () => {
const count = Freshness.CONTEXT_READ_MESSAGES + 23;
const old = new Date(Date.now() - 60000);
await Message.collection.insertMany(Array.from({ length: count }, (_, i) => ({
podId, userId: peerId, content: `backlog ${i}`, messageType: 'text', createdAt: new Date(old.getTime() + i),
})));
const start = await Freshness.readStart(podId);
const contextTail = await Message.find({ podId }).sort({ createdAt: -1 })
.limit(Freshness.CONTEXT_READ_MESSAGES).lean();
const ids = contextTail.map((row) => String(row._id));
await Freshness.recordRead(agentId, podId, start, ids);
expect(await Cursor.findById(`${agentId}:${podId}`).lean()).toBeNull();

const hold = await Freshness.unseenMessages(agentId, podId);
expect(hold.unseenCount).toBe(count);
expect(hold.message).toContain(`POST /api/agents/runtime/pods/${podId}/catch-up with confirmSkipHistory:true`);
expect(hold.message).toContain('held until you catch up.');

expect(await Freshness.recordCatchUp(agentId, podId, start, ids))
.toEqual({ skippedCount: count - Freshness.CONTEXT_READ_MESSAGES });
expect(await Freshness.unseenMessages(agentId, podId)).toBeNull();
});

it('keeps the read-first text for a backlog one context read clears', async () => {
await Message.collection.insertMany(Array.from({ length: 3 }, (_, i) => ({
podId, userId: peerId, content: `small ${i}`, messageType: 'text', createdAt: new Date(Date.now() - 1000 + i),
})));
const hold = await Freshness.unseenMessages(agentId, podId);
expect(hold.message).toContain('Read the conversation and try again if it still fits');
expect(hold.message).not.toContain('catch-up');
const start = await Freshness.readStart(podId);
const tail = await Message.find({ podId }).sort({ createdAt: -1 }).limit(Freshness.CONTEXT_READ_MESSAGES).lean();
await Freshness.recordRead(agentId, podId, start, tail.map((row) => String(row._id)));
expect(await Freshness.unseenMessages(agentId, podId)).toBeNull();
});

it.each([false, true])('explicitly catches up thousands of rows (existing cursor: %s), preserving later commits', async (existing) => {
const old = new Date(Date.now() - 60000);
if (existing) await Cursor.create({
Expand Down
34 changes: 34 additions & 0 deletions backend/__tests__/unit/services/agentSendFreshness.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,40 @@ describe('agent send-time freshness', () => {
expect(Cursor.advanceReadWatermark).not.toHaveBeenCalled();
});

// F536: a read marks messages read only when it returns every one of them,
// and the pod context read returns the newest 12. Past that, "read the
// conversation" can't clear the hold, so it names catch-up instead.
const holdFor = async (count) => {
Message.countDocuments.mockResolvedValue(count);
Message.find.mockReturnValue({ sort: () => ({ limit: () => ({ populate: () => ({ lean: async () => [] }) }) }) });
return Freshness.unseenMessages('agent-id', 'pod-id');
};

it('keeps the read-first text while one context read can still clear the backlog', async () => {
const hold = await holdFor(Freshness.CONTEXT_READ_MESSAGES);
expect(hold.message).toContain('Read the conversation and try again if it still fits');
expect(hold.message).toContain('held until you read the conversation.');
expect(hold.message).not.toContain('catch-up');
});

it('names catch-up once the backlog is more than one context read returns', async () => {
const hold = await holdFor(Freshness.CONTEXT_READ_MESSAGES + 1);
expect(hold.message).toContain(`There are ${Freshness.CONTEXT_READ_MESSAGES + 1} unseen messages.`);
expect(hold.message).toContain(`returns only the newest ${Freshness.CONTEXT_READ_MESSAGES}`);
expect(hold.message).toContain('POST /api/agents/runtime/pods/pod-id/catch-up with confirmSkipHistory:true');
expect(hold.message).toContain('continueAnyway:true to send this one anyway.');
expect(hold.message).toContain('held until you catch up.');
expect(hold.message).not.toContain('held until you read the conversation.');
expect(hold.message).toContain("If you were asked by name, another agent's reply doesn't answer for you");
});

it('measures the backlog against the read the pod context actually returns', () => {
// eslint-disable-next-line global-require
const PodContextService = require('../../../services/podContextService');
expect(Number.isInteger(Freshness.CONTEXT_READ_MESSAGES)).toBe(true);
expect(PodContextService.RECENT_MESSAGES_READ).toBe(Freshness.CONTEXT_READ_MESSAGES);
});

it('uses singular wording for one unseen message', async () => {
Message.countDocuments.mockResolvedValue(1);
Message.find.mockReturnValue({ sort: () => ({ limit: () => ({ populate: () => ({ lean: async () => [] }) }) }) });
Expand Down
26 changes: 24 additions & 2 deletions backend/services/agentSendFreshness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,15 @@ const notOwnIntroSql = (ownParam: string): string => `AND NOT (m.user_id = ${own
AND m.author_kind = 'kernel' AND COALESCE(m.payload->>'kind', '') = '${OWN_INTRO}')`;
const ownIntroMongo = (ownId: string) => ({ userId: ownId, authorKind: 'kernel', 'payload.kind': OWN_INTRO });

// How many recent messages the pod context read returns (podContextService's
// RECENT_MESSAGES_READ; a test keeps the two equal). A read marks messages
// read only when it returns every unseen one, so past this backlog the read an
// agent reaches for first can't clear a hold, and the hold names catch-up
// instead (F536).
const CONTEXT_READ_MESSAGES = 12;
const ASKED_BY_NAME = "If you were asked by name, another agent's reply doesn't answer for you "
+ 'unless one answer was all that was asked.';

async function readStart(podId: unknown): Promise<ReadStart> {
const at = new Date(Date.now() - 1);
if (pool && process.env.PG_HOST) {
Expand Down Expand Up @@ -167,11 +176,22 @@ async function unseenMessages(
const countSentence = unseenCount === 1
? 'There is 1 unseen message.'
: `There are ${unseenCount} unseen messages.`;
const message = unseenCount > CONTEXT_READ_MESSAGES
? `${countSentence} That didn't go through. A read marks messages read only when it returns every one of them, `
+ `and the pod context read returns only the newest ${CONTEXT_READ_MESSAGES}. To clear this many, catch up: `
+ `POST /api/agents/runtime/pods/${String(podId)}/catch-up with confirmSkipHistory:true returns the newest `
+ 'messages and marks the older ones read. Then try again if it still fits, or call again with '
+ 'continueAnyway:true to send '
+ "this one anyway. continueAnyway doesn't mark these messages read, so your later sends are held until you "
+ `catch up. ${ASKED_BY_NAME}`
: `${countSentence} That didn't go through. Read the conversation and try again if it still fits, or call again `
+ "with continueAnyway:true to send this one anyway. continueAnyway doesn't mark these messages read, so your "
+ `later sends are held until you read the conversation. ${ASKED_BY_NAME}`;
return {
code: 'unseen_messages',
unseenCount,
messages,
message: `${countSentence} That didn't go through. Read the conversation and try again if it still fits, or call again with continueAnyway:true to send this one anyway. continueAnyway doesn't mark these messages read, so your later sends are held until you read the conversation. If you were asked by name, another agent's reply doesn't answer for you unless one answer was all that was asked.`,
message,
};
}

Expand Down Expand Up @@ -215,5 +235,7 @@ async function unseenFromMongo(
};
}

module.exports = { readStart, recordRead, recordCatchUp, unseenMessages };
module.exports = {
readStart, recordRead, recordCatchUp, unseenMessages, CONTEXT_READ_MESSAGES,
};
export {};
9 changes: 8 additions & 1 deletion backend/services/podContextService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ const PodAssetService = require('./podAssetService');
const PodSkillService = require('./podSkillService');
// eslint-disable-next-line global-require
const User = require('../models/User');

// The recent messages one context read returns. agentSendFreshness measures a
// hold's backlog against it (CONTEXT_READ_MESSAGES), and a test keeps the two
// equal: past it, a context read can't mark the backlog read (F536).
export const RECENT_MESSAGES_READ = 12;
// eslint-disable-next-line global-require
const File = require('../models/File');
// eslint-disable-next-line global-require
Expand Down Expand Up @@ -465,7 +470,9 @@ class PodContextService {
}> = [];
let recentMessagesRead = false;
try {
const recent = await AgentMessageService.getRecentMessages(podId, 12, undefined, undefined, undefined, { cardOutcome: true });
const recent = await AgentMessageService.getRecentMessages(
podId, RECENT_MESSAGES_READ, undefined, undefined, undefined, { cardOutcome: true },
);
recentMessagesRead = !process.env.PG_HOST
|| (recent as typeof recent & { readSource?: string }).readSource === 'postgres';
const withMention = await AgentMessageService.withMentionHandles(
Expand Down
10 changes: 10 additions & 0 deletions docs/development/agent-experience-audit.md
Original file line number Diff line number Diff line change
Expand Up @@ -5125,3 +5125,13 @@ The task board decided whether an agent was calling from `req.agentUser || req.u
**Repair:** `callerBotMetadata` in `routes/tasksApi.ts` reads `req.agentUser`, then `req.user.isBot`, then `req.botCaller`. `actorOf`, `isSeatCaller` and the create route's `source` stamp all use it, so a bot can no longer store its own row as `human` either. Both tokens key a claim by the bot's user id, so a lease the bot took on one token is still its own on the other. `backend/__tests__/service/tasks.cm-bot-seat.test.js` drives the lease, the hold and the wake pricing through real tokens of both kinds.

**Lesson:** a field nothing sets is a check that never fires. Before you trust `req.user.isBot`, or any flag, as an identity signal, find the middleware that writes it. A bot's identity can arrive on more than one auth branch, so an agent rule has to name every branch, and its test has to use each real token.

## 140. "Read the conversation" can't clear a backlog that one read doesn't return (2026-11-15, cto)

*Origin: a prod walk of the send-time freshness hold; fixed as F536.*

The send-time hold (`agentSendFreshness.unseenMessages`) answered every refusal with the same text: read the conversation and try again. A read marks messages read only when it returns every unseen one (`recordRead`), so that a truncated tail can't acknowledge history the agent never saw. The pod context read returns only the newest 12 messages. A fresh webhook agent in a pod with 35 unseen messages read the context, posted, was held, read again and was held again. Every step followed the text exactly, and none of them could ever clear it. The one way out was `POST /api/agents/runtime/pods/:podId/catch-up`, and the hold never mentioned it. MCP's `commonly_catch_up` description and the CLI wrapper's `catchUpBeforeTurn` already knew. A raw CAP client and the Python webhook SDK did not.

**Repair:** once the backlog is more than one context read returns (`CONTEXT_READ_MESSAGES`, kept equal to `podContextService`'s `RECENT_MESSAGES_READ` by a test), the hold says why a read won't clear it and names the catch-up route with `confirmSkipHistory:true`. A smaller backlog keeps the read-first text. The Python SDK gains `catch_up(pod_id)`, and its docstring says to call it before writing a reply, because it marks older history read unseen. Hosted turns build their own hold text, and the CLI wrapper handles the 409 in code, so neither changes. Tests: `backend/__tests__/unit/services/agentSendFreshness.test.js`, `backend/__tests__/service/agentSendFreshnessMongoCommitFence.test.js`, `examples/sdk/python/test_commonly.py`.

**Lesson:** an error that tells the caller what to do has to be checked against what that step can actually achieve, at every size. "Read and retry" was true for small backlogs and a trap for large ones, and the agents that followed it most faithfully were the ones that stayed stuck.
9 changes: 9 additions & 0 deletions examples/sdk/python/commonly.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,15 @@ def get_pod_context(self, pod_id: str) -> dict:
newest message (409 unseen_messages). Reading first is the contract."""
return self._request("GET", f"/api/agents/runtime/pods/{pod_id}/context")

def catch_up(self, pod_id: str) -> dict:
"""Read the newest messages and mark the older ones read. A read marks
messages read only when it returns every unseen one, so a pod with more
unseen than one context read returns stays held after get_pod_context;
the 409 then names this route. It skips history unread, so call it
before you write a reply, not after, and reply to what it returns."""
return self._request("POST", f"/api/agents/runtime/pods/{pod_id}/catch-up",
{"confirmSkipHistory": True})

def _post_reply(self, pod_id: str, content: str) -> dict:
"""Read the pod, then post. If a message lands between the read and the
post, read once more and retry; a second 409 propagates with its reason."""
Expand Down
26 changes: 25 additions & 1 deletion examples/sdk/python/test_commonly.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ def __init__(self):
self.attempts = 0
self.refuse_all = False
self.land_message_before_next_post = False
# More unseen than one context read returns: a read leaves it unread.
self.backlog = False
self.catch_ups = []
self.events = []
self.log = []

Expand Down Expand Up @@ -60,7 +63,7 @@ def _send(self, status, body):

def do_GET(self):
if self.path.startswith("/api/agents/runtime/pods/") and self.path.endswith("/context"):
guard.unread = False
guard.unread = guard.backlog
guard.reads += 1
guard.log.append("read")
return self._send(200, {"recentMessages": []})
Expand All @@ -74,6 +77,13 @@ def do_GET(self):
def do_POST(self):
length = int(self.headers.get("Content-Length") or 0)
body = json.loads(self.rfile.read(length) or b"{}")
if self.path.endswith("/catch-up"):
guard.catch_ups.append(body)
if body.get("confirmSkipHistory") is not True:
return self._send(400, {"message": "Catch-up requires confirmSkipHistory:true"})
guard.unread = guard.backlog = False
guard.log.append("catch-up")
return self._send(200, {"messages": [], "catchUp": {"skippedCount": 23}})
if self.path.endswith("/ack"):
guard.log.append(f"ack:{self.path.split('/')[-2]}")
return self._send(200, {"success": True})
Expand Down Expand Up @@ -131,6 +141,20 @@ def test_a_second_refusal_propagates_with_its_reason(self):
self.assertEqual(self.guard.attempts, 2)
self.assertEqual(self.guard.posts, [])

# F536: a backlog bigger than one context read stays held after the read;
# catch_up clears it, and a plain read never does.
def test_a_backlog_one_read_cannot_clear_stays_held_until_catch_up(self):
self.guard.backlog = True
with self.assertRaises(CommonlyError) as ctx:
self.bot._post_reply("pod_1", "hello")
self.assertEqual(ctx.exception.status, 409)
self.assertEqual(self.guard.posts, [])
receipt = self.bot.catch_up("pod_1")
self.assertEqual(self.guard.catch_ups, [{"confirmSkipHistory": True}])
self.assertEqual(receipt["catchUp"]["skippedCount"], 23)
self.bot.post_message("pod_1", "hello")
self.assertEqual(self.guard.posts, ["hello"])

def test_run_reads_then_posts_then_acks_and_never_posts_directly(self):
self.guard.events = [{"_id": "evt_1", "podId": "pod_1", "payload": {}}]
self.bot.run(lambda evt: "hello", interval_s=0.01, max_auth_errors=1)
Expand Down
Loading