The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Merge batch 11-06 train-0420: #3313 (#3328)
harness-for-autonomous[bot]4feb25b644e9
diff --git a/backend/integration/superTabProjectChatWorkers.test.ts b/backend/integration/superTabProjectChatWorkers.test.tsindex 0c98ee558..e423c08f4 100644--- a/backend/integration/superTabProjectChatWorkers.test.ts+++ b/backend/integration/superTabProjectChatWorkers.test.ts@@ -86,3 +86,24 @@ describe('an agent with a task in the project, in its project chat', () => {expect(above[0]!.docsExamined).toBeLessThanOrEqual(20)})})+++describe('project chat limits under transactional writes', () => {+ it('counts a retry once and serializes competing second posts', async () => {+ const { tab, engineer } = await working()+ const asked = String((await run(tab, post('Please fix login.'))).result.messageId)+ const envelope = { operationId: randomUUID(), command: { ...post('I can fix login.'), answers: asked } }+ const first = await store.execute(host, tab, envelope, engineer)+ const retry = await store.execute(host, tab, envelope, engineer)+ expect(retry.result.messageId).toBe(first.result.messageId)+ const results = await Promise.allSettled([+ run(tab, { ...post('Login now works offline.', String(first.result.messageId)), alsoSend: true }, host, engineer),+ run(tab, { ...post('Expired tokens work again.', String(first.result.messageId)), alsoSend: true }, host, engineer),+ ])+ expect(results.filter(r => r.status === 'fulfilled')).toHaveLength(1)+ expect(results.find(r => r.status === 'rejected')).toMatchObject({ reason: { code: 'CHAT_MAIN_LIMIT' } })+ const rows = (await store.messages(owner, tab, 'lead', {})).messages+ expect(rows.filter(m => m.author.kind === 'agent' && !m.source)).toHaveLength(2)+ expect((await store.read(owner, tab)).state.conversations.find(c => c.id === 'lead')).not.toHaveProperty('chatLimits')+ })+})diff --git a/backend/integration/superTabProjectRules.test.ts b/backend/integration/superTabProjectRules.test.tsindex 76f3b6ed7..cba644312 100644--- a/backend/integration/superTabProjectRules.test.ts+++ b/backend/integration/superTabProjectRules.test.ts@@ -85,7 +85,7 @@ describe('a project\'s rules record', () => {it('lets the PM save only with a person\'s own chat message, recording it', async () => {const { tab, lead } = await swarm()expect(await refusal(run(tab, set(0, rules('10:00')), host, lead))).toMatchObject({ code: 'RULES_ASKED_IN_REQUIRED', status: 400 })- const own = await run(tab, { type: 'message.send', conversationId: 'lead', text: 'Status: all good.', replyTo: null, recipientIds: [] }, host, lead)+ const own = await run(tab, { type: 'message.send', conversationId: 'lead', text: 'The release is available.', replyTo: null, recipientIds: [] }, host, lead)const agentMessage = own.result.messageId as stringexpect(await refusal(run(tab, set(0, rules('10:00'), { askedIn: { conversationId: 'lead', messageId: agentMessage } }), host, lead))).toMatchObject({ code: 'RULES_ASKED_IN_REQUIRED' })diff --git a/backend/src/superTabs/answers.test.ts b/backend/src/superTabs/answers.test.tsindex 7451fe1fe..4635f721e 100644--- a/backend/src/superTabs/answers.test.ts+++ b/backend/src/superTabs/answers.test.ts@@ -82,11 +82,11 @@ describe('the PM\'s answer', () => {expect(refusal(() => answer(f.lead, question, 'Rowan, on a Team account.'))?.code).toBe(ALREADY_ANSWERED)})- it('a plain post right below an answered ask still goes out: only the answer command refuses', () => {+ it('refuses a second plain answer below the same project ask', () => {const { f, ask, answer, refusal } = setup()const question = ask('Is CI green?')answer(f.lead, question, 'Green.')- expect(refusal(() => answer(f.lead, question, 'Still green after the batch.', { plain: true }))).toBeNull()+ expect(refusal(() => answer(f.lead, question, 'Still green after the batch.', { plain: true }))?.code).toBe(ALREADY_ANSWERED)})it('to a message nobody owed is posted in its place and recorded, so a second one is refused', () => {@@ -98,13 +98,13 @@ describe('the PM\'s answer', () => {expect(refusal(() => answer(f.lead, question, 'Again.'))?.code).toBe(ALREADY_ANSWERED)})- it('by an agent that is not the PM is posted in its place but neither settles nor blocks the PM\'s answer', () => {+ it('by an Engineer leaves PM owed settlement alone but blocks a second answer', () => {const { f, ask, answer, owed, refusal } = setup()const question = ask('Is the fix in?')// The Engineer has work in the project, so it posts in its chat without joining it.answer(f.dev, question, 'I pushed it.')expect(owed()).toEqual([question.id])- expect(refusal(() => answer(f.lead, question, 'Merged at 21:00.'))).toBeNull()+ expect(refusal(() => answer(f.lead, question, 'Merged at 21:00.'))?.code).toBe(ALREADY_ANSWERED)})it('needs the message it answers', () => {diff --git a/backend/src/superTabs/answers.ts b/backend/src/superTabs/answers.tsindex bfb3cdaab..447d6afc0 100644--- a/backend/src/superTabs/answers.ts+++ b/backend/src/superTabs/answers.ts@@ -3,7 +3,8 @@* `answer`, the CLI's `answer` command) goes where the ask was made: in its thread when it is a reply in one, else right below* it in the main chat. The PM's answers are recorded on the conversation (`Conversation.answered`), by `answer` or by any post* that settles an owed ask (pulse.ts), and a second `answer` to the same message is refused with where the first one is. A- * plain post is never refused: only the command that says "this is the answer" is.+ * plain post in a task/private chat is never refused by this helper. Project chats extend this to every agent and explicit+ * answer link or person reply mirrored into main (chatLimits.ts, task #3598).*/import type { CommandContext } from './commands.js'import { fail, type Conversation, type SuperTabState } from './model.js'@@ -30,8 +31,8 @@ export function leadsGroup(state: SuperTabState, group: Conversation, agentId: sconst clock = (at: number): string => new Date(at).toISOString().slice(11, 16)/** Refuses an answer to [messageId] when [group] records one, saying where it is. */-export function requireUnanswered(group: Conversation, messageId: string): void {- const first = group.answered?.find(a => a.id === messageId)+export function requireUnanswered(group: Conversation, messageId: string, recorded?: AnsweredAsk): void {+ const first = recorded ?? group.answered?.find(a => a.id === messageId)if (!first) returnconst where = first.thread ? 'in its thread' : 'right below it'fail(ALREADY_ANSWERED, `Answered already ${where} at ${clock(first.at)} UTC (message ${first.answerId}). Add to it there if something changed.`, 409,diff --git a/backend/src/superTabs/chatLimits.test.ts b/backend/src/superTabs/chatLimits.test.tsnew file mode 100644index 000000000..e9c8bbb22--- /dev/null+++ b/backend/src/superTabs/chatLimits.test.ts@@ -0,0 +1,212 @@+import { describe, expect, it } from 'vitest'+import type { Command, CommandContext } from './commands.js'+import { owner, stepsFixture } from './steps.test-support.js'++function setup() {+ const f = stepsFixture()+ const send = (text: string, options: { person?: boolean; by?: string; group?: string; extra?: Record<string, unknown>; reply?: CommandContext['reply'] } = {}) =>+ f.run({ type: 'message.send', conversationId: options.group ?? 'lead', text, replyTo: null, recipientIds: [], ...options.extra } as Command,+ options.person ? owner : f.as(options.by ?? f.lead), options.reply ? { reply: options.reply } : {})+ const person = { kind: 'person' as const, id: owner.userId, name: owner.email, membershipGeneration: f.state.people[0]!.generation }+ const ask = () => {+ const id = send('Can you fix login?', { person: true }).result.messageId as string+ return { id, conversationId: 'lead', author: person, createdAt: f.now, thread: id }+ }+ return { f, send, ask }+}++describe('project chat content limits', () => {+ it.each(['Status: tests running.', 'Ready for review: PR #12.', 'On it: I am fixing login.', 'CI: 3 checks pending.', 'Progress update: branch pushed.'])(+ 'refuses the status line %j with thread guidance', text => {+ const { send } = setup()+ expect(() => send(text)).toThrow(expect.objectContaining({ code: 'CHAT_STATUS', message: expect.stringMatching(/thread|status/i) }))+ })++ it('does not let a file or person tag bypass a status refusal', () => {+ const { f, send } = setup()+ expect(() => send('Status: tests running.', { extra: { mentions: [owner.userId] } })).toThrow(expect.objectContaining({ code: 'CHAT_STATUS' }))+ expect(() => f.run({ type: 'message.send', conversationId: 'lead', text: 'Status: tests running.', replyTo: null, recipientIds: [], attachmentIds: ['file'] }, f.as(f.lead),+ { attachments: [{ id: 'file', name: 'evidence.txt', mime: 'text/plain', size: 12, url: 'https://files.invalid/evidence' }] }))+ .toThrow(expect.objectContaining({ code: 'CHAT_STATUS' }))+ })++ it('refuses a repeated pull request card pointer but allows new facts with its link', () => {+ const { f, send } = setup()+ const url = 'https://github.com/acme/repo/pull/12'+ f.group('lead').cards = { pullRequests: [{ url, messageId: 'card' }] }+ expect(() => send(url)).toThrow(expect.objectContaining({ code: 'CHAT_CARD_REPEAT', message: expect.stringMatching(/card|thread/i) }))+ expect(() => send(`PR #12: ${url}`)).toThrow(expect.objectContaining({ code: 'CHAT_CARD_REPEAT' }))+ expect(() => send('PR #12')).toThrow(expect.objectContaining({ code: 'CHAT_CARD_REPEAT' }))+ expect(() => send(`The login fix shipped in 2.3. ${url}`)).not.toThrow()+ expect(() => send('https://github.com/acme/repo/pull/13')).not.toThrow()+ })++ it('refuses an exact repeat of the task card title or number', () => {+ const { f, send } = setup()+ f.group(f.task).cards = { line: { messageId: 'task-card', conversationId: 'lead' } }+ expect(() => send(`#${f.group(f.task).number} ${f.group(f.task).title}`)).toThrow(expect.objectContaining({ code: 'CHAT_CARD_REPEAT' }))+ expect(() => send(`#${f.group(f.task).number}`)).toThrow(expect.objectContaining({ code: 'CHAT_CARD_REPEAT' }))+ expect(() => send('Login now works offline.')).not.toThrow()+ })++ it('preserves people, task posts, thread followups and substantive short answers', () => {+ const { f, send, ask } = setup()+ const question = ask()+ expect(() => send('Status: tests running.', { person: true })).not.toThrow()+ expect(() => send('Ready for review: PR #12.', { group: f.task, by: f.dev })).not.toThrow()+ expect(() => send('CI: 3 checks pending.', { extra: { replyTo: question.id }, reply: question })).not.toThrow()+ expect(() => send('Is CI green?')).not.toThrow()+ expect(() => send('The release is out; login works offline.')).not.toThrow()+ expect(() => send('Status: tests running.', { extra: { agentOnly: true, recipientIds: [f.lead] } })).not.toThrow()+ })++ it('lets a visible response to an agent-only notice stand on its own, while still checking main content', () => {+ const { f, send } = setup()+ const note: NonNullable<CommandContext['reply']> = { id: 'notice', conversationId: 'lead', author: { kind: 'agent' as const, id: f.lead, name: 'PM', membershipGeneration: f.state.agents.find(a => a.id === f.lead)!.membershipGeneration }, createdAt: f.now, thread: 'notice', agentOnly: true }+ expect(() => send('The worker has resumed.', { reply: note, extra: { replyTo: note.id } })).not.toThrow()+ expect(() => send('Status: worker resumed.', { reply: note, extra: { replyTo: note.id } })).toThrow(expect.objectContaining({ code: 'CHAT_STATUS' }))+ })++ it('checks status on a thread reply mirrored into main chat', () => {+ const { send, ask } = setup()+ const question = ask()+ expect(() => send('CI: still running.', { reply: question, extra: { replyTo: question.id, alsoSend: true } }))+ .toThrow(expect.objectContaining({ code: 'CHAT_STATUS' }))+ })+})++describe('two main posts per linked ask', () => {+ function exchange() {+ const f = setup(), question = f.ask()+ const answer = f.send('I can fix login.', { reply: question, extra: { answers: question.id } })+ const response = { ...question, id: String(answer.result.messageId), author: answer.messages[0]!.author }+ const mainReply = (text: string, by?: string) => f.send(text, { by, reply: response, extra: { replyTo: response.id, alsoSend: true } })+ return { ...f, question, response, mainReply }+ }++ it('shares the linked budget across agents and directs the third main post to the thread', () => {+ const { f, mainReply } = exchange()+ mainReply('Login now works offline.', f.dev)+ expect(() => mainReply('The fix also handles expired tokens.')).toThrow(expect.objectContaining({ code: 'CHAT_MAIN_LIMIT', message: expect.stringMatching(/two|2/i) }))+ })++ it('lets a new person ask have its own linked budget, without resetting an older one', () => {+ const { send, ask, mainReply } = exchange()+ mainReply('Login now works offline.')+ const next = ask()+ expect(() => send('I can fix logout too.', { reply: next, extra: { answers: next.id } })).not.toThrow()+ expect(() => mainReply('The old fix also handles expired tokens.')).toThrow(expect.objectContaining({ code: 'CHAT_MAIN_LIMIT' }))+ })++ it('allows thread followups but counts replies mirrored into main', () => {+ const { send, question, mainReply } = exchange()+ mainReply('Login now works offline.')+ expect(() => send('Expired tokens work too.', { reply: question, extra: { replyTo: question.id } })).not.toThrow()+ expect(() => mainReply('The mobile build also has the fix.')).toThrow(expect.objectContaining({ code: 'CHAT_MAIN_LIMIT' }))+ })++ it('does not let a thread person followup reset its root main budget', () => {+ const { send, question, mainReply } = exchange()+ mainReply('Login now works offline.')+ send('Does it work on phones?', { person: true, reply: question, extra: { replyTo: question.id } })+ expect(() => mainReply('Yes, on phones too.')).toThrow(expect.objectContaining({ code: 'CHAT_MAIN_LIMIT' }))+ })++ it('never limits person posts, task posts or agent-only notices', () => {+ const { f, send, mainReply } = exchange()+ mainReply('Login now works offline.')+ for (let i = 0; i < 3; i++) {+ expect(() => send(`Person followup ${i}`, { person: true })).not.toThrow()+ expect(() => send(`Task detail ${i}`, { group: f.task, by: f.dev })).not.toThrow()+ expect(() => send(`Private note ${i}`, { extra: { agentOnly: true, recipientIds: [f.lead] } })).not.toThrow()+ }+ })++ it('cannot reopen an evicted ask after 50 newer asks, and does not expose its ledger', async () => {+ const { f, send, ask, question } = exchange()+ for (let i = 0; i < 50; i++) { f.tick(1); ask() }+ expect(() => send('An old result.', { reply: question, extra: { answers: question.id } })).toThrow(expect.objectContaining({ code: 'CHAT_ASK_CLOSED' }))+ const { groupView } = await import('./read/views.js')+ expect(groupView(f.group('lead'), new Set())).not.toHaveProperty('chatLimits')+ })++ it('does not charge an outage or an older ask result to the newest full ask', () => {+ const { send, ask, mainReply } = exchange()+ const b = ask()+ const first = send('I can fix logout too.', { reply: b, extra: { answers: b.id } })+ const bAnswer = { ...b, id: String(first.result.messageId), author: first.messages[0]!.author }+ send('Logout now works.', { reply: bAnswer, extra: { replyTo: bAnswer.id, alsoSend: true } })+ expect(() => send('An outage is affecting sign-in; the team is restoring service.')).not.toThrow()+ expect(() => mainReply('The older login fix shipped in 2.3.')).not.toThrow()+ })+})++describe('one answer across main and thread', () => {+ it.each(['main', 'thread'] as const)('refuses a plain second answer after the first in %s, even by another agent', place => {+ const { f, send, ask } = setup()+ const question = ask()+ const first = send('Login works offline.', { by: f.dev,+ extra: place === 'main' ? { answers: question.id } : { answers: question.id, answer: true }, reply: place === 'main' ? question : { ...question, thread: 'topic-root' } })+ const messageId = first.result.messageId+ for (const extra of [{ answers: question.id }, { replyTo: question.id, alsoSend: true }]) {+ expect(() => send('Yes, it works offline.', { reply: question, extra }))+ .toThrow(expect.objectContaining({ code: 'ALREADY_ANSWERED', message: expect.stringContaining(String(messageId)) }))+ }+ })++ it('allows replying to an agent answer and answering a new person followup in that thread', () => {+ const { f, send, ask } = setup()+ const question = ask()+ const first = send('Login works offline.', { reply: question, extra: { answers: question.id } })+ const reply = { ...question, id: String(first.result.messageId), author: first.messages[0]!.author }+ expect(() => send('The phone build includes it too.', { reply, extra: { replyTo: reply.id } })).not.toThrow()+ const next = send('Does it handle expired tokens?', { person: true, reply, extra: { replyTo: reply.id } })+ const followup = { ...question, id: String(next.result.messageId) }+ expect(() => send('Expired tokens are refreshed.', { by: f.dev, reply: followup, extra: { answers: followup.id, answer: true } })).not.toThrow()+ expect(() => send('They are refreshed automatically.', { reply: followup, extra: { answers: followup.id, answer: true } }))+ .toThrow(expect.objectContaining({ code: 'ALREADY_ANSWERED' }))+ })++ it('preserves person answers and agent duplicates in a task chat', () => {+ const { f, send, ask } = setup()+ const question = ask()+ send('Login works offline.', { reply: question, extra: { answers: question.id } })+ for (let i = 0; i < 3; i++) expect(() => send(`Person answer ${i}`, { person: true, reply: question, extra: { answers: question.id } })).not.toThrow()+ const taskReply = { ...question, conversationId: f.task }+ for (let i = 0; i < 3; i++) expect(() => send(`Task answer ${i}`, { by: f.dev, group: f.task, reply: taskReply, extra: { answers: taskReply.id } })).not.toThrow()+ })++ it('does not reopen a formal answer after its ask has left the active ledger', () => {+ const { f, send, ask } = setup()+ const first = ask()+ send('Login works offline.', { by: f.dev, reply: first, extra: { answers: first.id, answer: true } })+ for (let i = 0; i < 51; i++) { f.tick(1); ask() }+ expect(() => send('Yes, offline works.', { reply: first, extra: { answers: first.id, answer: true } }))+ .toThrow(expect.objectContaining({ code: 'CHAT_ASK_CLOSED' }))+ })+})+++describe('thread discussion after an answer', () => {+ it('lets another agent post details in the ask thread after a main answer', () => {+ const { f, send, ask } = setup()+ const question = ask()+ send('Login now works offline.', { reply: question, extra: { answers: question.id } })+ expect(() => send('The phone flow also passes.', { by: f.dev, reply: question, extra: { replyTo: question.id } })).not.toThrow()+ expect(() => send('CI: all checks passed.', { by: f.dev, reply: question, extra: { replyTo: question.id } })).not.toThrow()+ })+})+++describe('answer recording at the ledger boundary', () => {+ it('records a main reply even when its new explicit answer target evicts the root ask', () => {+ const { f, send, ask } = setup()+ const question = ask()+ const first = send('Can the phone build use this fix?', { reply: question, extra: { answers: question.id } })+ const response = { ...question, id: String(first.result.messageId), author: first.messages[0]!.author }+ for (let i = 0; i < 49; i++) { f.tick(1); ask() }+ expect(() => send('Yes, the phone build can use it.', { reply: response, extra: { answers: response.id } })).not.toThrow()+ expect(() => send('Another main result.', { reply: question, extra: { replyTo: question.id, alsoSend: true } }))+ .toThrow(expect.objectContaining({ code: 'CHAT_ASK_CLOSED' }))+ })+})diff --git a/backend/src/superTabs/chatLimits.ts b/backend/src/superTabs/chatLimits.tsnew file mode 100644index 000000000..1cb38658c--- /dev/null+++ b/backend/src/superTabs/chatLimits.ts@@ -0,0 +1,99 @@+/** Deterministic project-chat limits (Dee 11-04/11-05, task #3598). Threads carry work details; main carries decisions/results. */+import type { Command, CommandContext } from './commands.js'+import { fail, type Conversation, type SuperTabState } from './model.js'+import { requireUnanswered, type AnsweredAsk } from './answers.js'+import { projectsOf } from './projects.js'++type Send = Extract<Command, { type: 'message.send' }>+type Reply = CommandContext['reply']++export const isProjectChat = (state: SuperTabState, group: Conversation): boolean => projectsOf(state).some(project => project.leadConversationId === group.id)+export const inMainChat = (command: Send, reply: Reply): boolean => !command.replyTo || !!reply?.agentOnly || !reply?.thread || !!command.alsoSend++// Anchored labels, not words like "CI" appearing in a real question or result. No semantic classifier on the posting path.+const STATUS = /^(?:status(?: update)?|progress(?: update)?|on it|working|ready for review|ready for (?:the )?batch|CI|review|test run|batch)\s*:/im+const plain = (text: string) => text.trim().replace(/[.!。]+$/, '').trim()++export function requireChatContent(state: SuperTabState, group: Conversation, text: string): void {+ if (STATUS.test(text)) fail('CHAT_STATUS', 'Keep status lines in the task status or the ask’s thread, not the main chat.', 400)+ const line = plain(text)+ const pr = line.match(/^(?:PR\s*#\d+\s*:?\s*)?(https:\/\/github\.com\/[^\s/]+\/[^\s/]+\/pull\/\d+)\/?$/i)?.[1]+ const prNumber = line.match(/^PR\s*#(\d+)$/i)?.[1]+ const repeatedPr = group.cards?.pullRequests?.some(card => (pr && card.url === pr) || (prNumber && card.url.endsWith(`/pull/${prNumber}`)))+ const task = line.match(/^(?:Task\s*)?#(\d+)(?:\s*[:—-]?\s*(.*))?$/i)+ const repeatedTask = task && state.conversations.some(g => g.number === Number(task[1]) && g.cards?.line?.conversationId === group.id+ && (!task[2] || plain(task[2]).toLowerCase() === plain(g.title).toLowerCase()))+ if (repeatedPr || repeatedTask) {+ fail('CHAT_CARD_REPEAT', 'This card is already in the chat. Add new details in its thread instead of repeating it.', 400)+ }+}++/** Private, bounded state read/written with the conversation part; removed with it. IDs only, never transcript content. */+export interface ChatAsk {+ id: string+ at: number+ main: string[]+ answer?: AnsweredAsk+}+export interface ChatLimits {+ asks: ChatAsk[]+ /** Evicted asks cannot become new asks again. Timestamp ties close conservatively; retained IDs always win. */+ closedThrough?: number+}+const MAX_ASKS = 50++function remember(group: Conversation, id: string, at: number): ChatAsk {+ const ledger = group.chatLimits ??= { asks: [] }+ const known = ledger.asks.find(ask => ask.id === id)+ if (known) return known+ const ask: ChatAsk = { id, at, main: [] }+ ledger.asks.push(ask)+ if (ledger.asks.length > MAX_ASKS) ledger.closedThrough = Math.max(ledger.closedThrough ?? 0, ledger.asks.shift()!.at)+ return ask+}++export function recordChatAsk(group: Conversation, id: string, at: number): void {+ remember(group, id, at)+}++function closedAsk(): never {+ fail('CHAT_ASK_CLOSED', 'This older ask’s main-chat budget is closed. Continue the discussion under its existing response in the thread.', 409)+}++/** Returns the main-budget owner, or null for thread-only posts and unlinked announcements. */+export function requireChatPost(group: Conversation, command: Send, reply: Reply): string | null {+ if (reply?.agentOnly || !inMainChat(command, reply) || !(command.replyTo || command.answers)) return null+ const ledger = group.chatLimits+ const linked = command.replyTo || command.answers ? reply : undefined+ const personAsk = linked?.author.kind === 'person' ? linked : undefined+ const askId = personAsk ? personAsk.thread ?? personAsk.id+ : linked ? ledger?.asks.find(ask => ask.main.includes(linked.id))?.id ?? linked.thread : undefined+ if (!askId) return null+ let ask = ledger?.asks.find(ask => ask.id === askId)+ if (!ask && personAsk && askId === personAsk.id && (ledger?.closedThrough === undefined || personAsk.createdAt > ledger.closedThrough)) {+ ask = remember(group, askId, personAsk.createdAt)+ }+ if (!ask) return closedAsk()+ if (ask.main.length >= 2) fail('CHAT_MAIN_LIMIT', 'At most two agent posts per ask in the main chat. Put follow-ups in its thread.', 409)+ return ask.id+}++export function recordChatPost(group: Conversation, askId: string | null, messageId: string): void {+ if (askId) group.chatLimits!.asks.find(ask => ask.id === askId)!.main.push(messageId)+}++/** Explicit answer links and person replies mirrored into main are answers; plain thread replies are discussion. */+export function requireChatAnswer(group: Conversation, command: Send, reply: Reply): string | null {+ if (!reply || reply.agentOnly || !(command.answers || command.answer || (command.replyTo && inMainChat(command, reply) && reply.author.kind === 'person'))) return null+ const ask = group.chatLimits?.asks.find(ask => ask.id === reply.id)+ requireUnanswered(group, reply.id, ask?.answer)+ if (!ask) {+ if (group.chatLimits?.closedThrough !== undefined && reply.createdAt <= group.chatLimits.closedThrough) return closedAsk()+ }+ return reply.id+}++export function recordChatAnswer(group: Conversation, askId: string | null, messageId: string, thread: string | null, at: number, askedAt: number): void {+ const ask = askId && remember(group, askId, askedAt)+ if (ask) ask.answer = { id: askId, answerId: messageId, thread, at }+}diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.tsindex a173f5591..91027243d 100644--- a/backend/src/superTabs/commands.test.ts+++ b/backend/src/superTabs/commands.test.ts@@ -2123,8 +2123,9 @@ describe('any agent of the project', () => {it('posts a top-level line and a thread reply there, joins nothing, and reaches the coordinator only by name (#2963)', () => {const { f, engineer, reviewer, chat } = working()const members = [...chat().agentIds]- const asked = f.run(post('Can someone check the login bug?')).messages[0]!for (const agentId of [engineer, reviewer]) {+ // Each routing case has a fresh ask: main chat now permits two posts per ask (#3598).+ const asked = f.run(post('Can someone check the login bug?')).messages[0]!const line = f.run(post('I am on it.'), actorOf(agentId)).messages.at(-1)!expect(line).toMatchObject({ conversationId: 'lead', author: { kind: 'agent', id: agentId }, replyTo: null, recipients: [] })const reply = f.run(post('Found it: the token expired.', asked.id), actorOf(agentId),diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 30a2201f3..905850a31 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -70,6 +70,7 @@ import { BUDDY_OWN_MACHINE_REFUSAL } from './buddyContract.js'import { askBuddyModel, buddyModelResult, sendBuddyHome, sessionModel } from './buddyModel.js'import { launchRefusedLine, leadArrived, LEAD_CLAIM_MS, leadEffort, leadJoined, leadOvertaken, leadStartFailed, leadStarting, leadHost, leadWaits, LEAD_CAPABILITY, placeLead } from './leadStart.js'import { ACK_ONLY_HINT, isAcknowledgement } from './acknowledgements.js'+import { isProjectChat, inMainChat, requireChatContent, requireChatPost, recordChatAsk, recordChatPost, requireChatAnswer, recordChatAnswer } from './chatLimits.js'import { allowedDrops, approvedDropNotice, droppedLines, MAX_APPROVALS, MAX_DROPPED_LINES, refuseOverBudget, refuseRepeats, type ApprovalRow, type DroppedLine } from './ruleGuard.js'import { appendRouting, coordinatorNameOf, routingSummary, FIRST_INSTRUCTIONS, FIRST_SUMMARY, instructionsHash, instructionsTextSchema, legacyRoleName, liveNotes, MAX_NOTES, noteTextSchema, roleNameSchema, summarySchema, type PmNote } from './instructions.js'import { repeatedRules } from './instructionsDiff.js'@@ -3815,7 +3816,13 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,if (command.answers && (command.replyTo || !context.reply || context.reply.id !== command.answers || context.reply.conversationId !== group.id)) {fail('INVALID_ANSWER', command.replyTo ? 'Answer a message right below it or reply in its thread, not both.' : 'Answer a message in this conversation.', 400)}- // A second answer to a message the PM answered is refused with where the first is; a plain post is not (answers.ts).+ const chatPost = actor.kind === 'agent' && !command.agentOnly && isProjectChat(state, group)+ const chatAsk = chatPost ? requireChatPost(group, command, context.reply) : null+ const chatAnswer = chatPost ? requireChatAnswer(group, command, context.reply) : null+ if (chatPost && inMainChat(command, context.reply)) {+ requireChatContent(state, group, command.text)+ }+ // The answer command also keeps its existing guard outside project chats (answers.ts).if (command.answer) requireUnanswered(group, (command.answers ?? command.replyTo)!)const replyAgent = context.reply?.author.kind === 'agent' ? context.reply.author.id : null// An agent's post reaches the agents it names, by --to or by @Name, the agent whose message it answers, and, when it names@@ -3924,7 +3931,10 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,if (!command.agentOnly) {const sent = effects.messages.find(m => m.id === operationId)!const root = command.replyTo && context.reply && !context.reply.agentOnly ? context.reply.thread ?? context.reply.id : null- if (actor.kind === 'person') owe(state, group, { id: sent.id, author: sent.author, recipients, thread: root, source: sent.source }, context.now)+ if (actor.kind === 'person') {+ owe(state, group, { id: sent.id, author: sent.author, recipients, thread: root, source: sent.source }, context.now)+ if (isProjectChat(state, group)) recordChatAsk(group, sent.id, context.now)+ }else {const owedBefore = group.owed ?? []settleReply(state, group, actor.agentId, { answers: command.answers ?? null, thread: root })@@ -3934,6 +3944,11 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,recordAnswered(group, [...settled, ...asked.filter(a => !settled.some(s => s.id === a.id))], sent.id, root, context.now)}}+ if (chatPost) {+ recordChatPost(group, chatAsk, operationId)+ const root = command.replyTo && context.reply && !context.reply.agentOnly ? context.reply.thread ?? context.reply.id : null+ recordChatAnswer(group, chatAnswer, operationId, root, context.now, context.reply?.createdAt ?? context.now)+ }if (actor.kind === 'agent') renewOwnTask(state, group, actor.agentId, context.now)// A post to an Engineer waiting on this review: its own step then waits for the new revision (liveness.ts waitingForRevision).if (actor.kind === 'agent') toldEngineer(state, group, actor.agentId, recipients, context.now)diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex b24fb4727..43a883949 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -512,6 +512,8 @@ export interface Conversation {/** The PM's answers here (answers.ts): each message it answered, where and by which message, at most MAX_ANSWERED, so a* second `answer` is refused with where the first is. Bookkeeping: never sent to readers. */answered?: import('./answers.js').AnsweredAsk[]+ /** Project-chat post limits: at most 50 asks, no text; bookkeeping hidden from readers (chatLimits.ts). */+ chatLimits?: import('./chatLimits.js').ChatLimits/** On a project's chat: its project's pulse as last worked out (pulse.ts recordPulse), which every read sends in `derived`. */pulse?: import('./pulse.js').Pulse}@@ -1150,6 +1152,7 @@ export function visibleState(state: SuperTabState, actor: Actor, now = Date.now(// A read never hands out the cleanup records it just applied (read/hostRows.ts delivers them to the machine's host).delete visible.machineCleanupsdelete visible.parkedConversations+ for (const group of visible.conversations) delete group.chatLimitsnumberConversations(visible)delete visible.retiredConversationNumberdelete visible.groupCounterdiff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.tsindex 42c175b64..6d06b1326 100644--- a/backend/src/superTabs/parts/light.test.ts+++ b/backend/src/superTabs/parts/light.test.ts@@ -40,6 +40,7 @@ const conversation: Required<Conversation> = {buddyName: 'Sparky',buddySessions: [],cards: {},+ chatLimits: { asks: [] },checks: [],codePullRequestUrls: [],dormant: false,diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.tsindex fe14cfca4..00417521e 100644--- a/backend/src/superTabs/parts/light.ts+++ b/backend/src/superTabs/parts/light.ts@@ -69,6 +69,7 @@ export const GROUP_FIELDS = {'buddyName','buddySessions','cards',+ 'chatLimits','checks','codePullRequestUrls','handOutLane',diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.tsindex b27ca4500..6ce598a17 100644--- a/backend/src/superTabs/read/contract.ts+++ b/backend/src/superTabs/read/contract.ts@@ -37,7 +37,7 @@ export type AgentView = Omit<Agent, 'downNamed' | 'downSince' | 'limitedUntil' |export interface Audience { people: Array<{ id: string; generation: string }> }/** A conversation with its own message counter (`lastMessageSequence` and message sequences compare within one group).* `dormant` is set only on a dormant group fetched on demand; `audience` only on a private conversation. */-export type GroupView = Omit<Conversation, 'messageSeq' | 'reportSeq' | 'dormant' | 'lastActivityAt' | 'audience' | 'ledger' | 'proposals'> & {+export type GroupView = Omit<Conversation, 'chatLimits' | 'messageSeq' | 'reportSeq' | 'dormant' | 'lastActivityAt' | 'audience' | 'ledger' | 'proposals'> & {/** A task's lane, as the crew dispatch hands it out (dispatch.ts laneOf: its PM's, else its owned paths'), null when no* lane owns its paths; absent on a chat or a step. From the group alone, so a change read's changed tasks keep every lane's* count whole on the reader's side (task #3400). Absent from an older backend. */diff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.tsindex 06dfe027d..768250dc2 100644--- a/backend/src/superTabs/read/views.ts+++ b/backend/src/superTabs/read/views.ts@@ -69,7 +69,7 @@ export const envelope = <T>(part: Pick<Part, 'key' | 'version' | 'changedAt'>, d/** A group as readers get it: its message counter, a dormant flag only when dormant, never the store's bookkeeping or the* leaderboard's (the leaderboard read sums it), except when it shipped. */export function groupView(group: Conversation, seenMachines: ReadonlySet<string>): GroupView {- const { messageSeq, reportSeq: _report, lastActivityAt: _activity, ledger, proposals: _proposals, owed: _owed, answered: _answered, pulse: _pulse, dormant, audience, ...rest } = withSeenRequirement(group, seenMachines)+ const { messageSeq, reportSeq: _report, lastActivityAt: _activity, ledger, proposals: _proposals, owed: _owed, answered: _answered, chatLimits: _chatLimits, pulse: _pulse, dormant, audience, ...rest } = withSeenRequirement(group, seenMachines)// A Buddy chat names its owner instead of an audience: an app from before Buddies takes a private chat of the reader// alone for their Chat with PM, and would send what they write for the PM to their Buddy instead (buddies.ts).const readers = isBuddyChat(group) ? { buddyOwnerId: audience!.people[0]!.id } : audience ? { audience } : {}diff --git a/docs/plans/2026-11-06-main-chat-limits-plan.md b/docs/plans/2026-11-06-main-chat-limits-plan.mdnew file mode 100644index 000000000..9744f407d--- /dev/null+++ b/docs/plans/2026-11-06-main-chat-limits-plan.md@@ -0,0 +1,96 @@+# Main-chat limits implementation plan++> Implement task by task in this session, test first, with one independent review of the pull request.++**Goal:** Keep project chats useful by refusing agent status/card repeats, a third main-chat post per ask, and duplicate answers, while leaving people untouched.++**Architecture:** Add a focused `chatLimits.ts` guard to `message.send`, beside ACK_ONLY. A bounded, private ledger on the conversation records the newest 50 person asks, their first answer and at most two main posts across all agents. Only explicit ask/thread links consume that ask’s main budget; unlinked announcements stay independent. Explicit answer links and person replies shown in main count as answers; plain thread replies remain discussion.++**Tech Stack:** Existing TypeScript, Vitest and transactional MongoDB conversation parts; no dependencies, collections, indexes or new queries.++**Spec:** Task #3598, inventory Table A #7; Dee's 11-04/11-05 chat decisions and 11-06 rules-as-code decision.++## Global Constraints++- Only project chats; people, private/Buddy chats, task chats and agent-only notices retain their behavior.+- Main-chat status labels and pure repeats of existing cards are refused with the next step. Substantive factual results remain allowed.+- Two posts across all agents per ask; newline wrapping does not consume another post. Thread mirrors consume a main post.+- One formal answer per message across agents and main/thread locations. Plain thread replies, including replies to the person’s ask itself, continue discussion.+- Commit failing tests before implementation; push each completed task. Run only affected local checks; full backend unit and Super Tab integration suites run in ready PR CI.+- Temp files only in mktemp directories. Never sign out the real CLI or stop another process.++## Design++- **Growth:** At most 50 ask entries per project chat, each two post IDs and one answer. Eviction records an age watermark: an old ask cannot reopen a main budget or a formal answer. Its thread remains readable and plain thread discussion remains available. No text is stored in this ledger. Conversation removal deletes it.+- **Concurrency:** Existing optimistic conversation-part transaction serializes each post and counter together; operation receipts make retries idempotent.+- **Read cost:** Reuse the conversation and existing reply lookup. No message-history scan, new query or index. Hide bookkeeping from reader views/light loads.+- **Scale:** At 10x traffic state stays fixed at 50 asks; benchmark guard and full apply path. PRODUCT.md delivery target is p95 <=1s; algorithm timing alone cannot establish delivery latency.+- **Compatibility:** Older clients use the same message.send and see named refusals; no new client fields. Existing conversations initialize on their next person ask; their existing answered ledger still guards prior recorded answers.+- **Migration/rollback:** Optional JSON field, no schema migration. Rollback ignores it, preserving transcript; re-upgrade reuses it.+- **Audience/identity:** Existing access checks run first; no cross-account reading or execution added. Bookkeeping never carries content.+- **Failure/platforms:** Named refusals give thread/reaction guidance. Server behavior is common to every client platform; tests run on macOS and CI Linux.++## Review Focus++- A different agent must not bypass an ask's shared budget (Task 2).+- Main/thread mirrors and direct legacy post links must not bypass limits (Tasks 2/3).+- A new person's ask gets a fresh budget, and old ask links cannot reset after eviction (Task 2).+- Files/tags must not bypass the status/card guard; meaningful questions/results must pass (Task 1).+- People and non-project conversations stay unchanged; ledger never enters reader payloads (Tasks 1/2/3).++### Task 1: Refuse main-chat status and card-only repeats++**Files:** Create `backend/src/superTabs/chatLimits.ts`, `chatLimits.test.ts`; modify `commands.ts`.+**Interfaces:** `requireChatContent(state, group, text): void`, called only for visible agent main posts in a project chat.++- [x] Commit command-level tests for status labels, known PR/task card repeats, attachments/tags, person/task/thread exemptions, and meaningful results.+- [x] Run `npm test -- src/superTabs/chatLimits.test.ts`; verify the expected refusal tests fail.+- [x] Implement conservative, anchored status and exact card-pointer checks; integrate after existing reply validation.+- [x] Run own tests and `acknowledgements.test.ts`; commit and push green implementation.++### Task 2: Two main posts per ask++**Files:** Modify `chatLimits.ts`, `chatLimits.test.ts`, `commands.ts`, `model.ts`, `read/views.ts`, `read/contract.ts`, `parts/light.ts`, `parts/light.test.ts`; integration coverage in `integration/superTabProjectChatWorkers.test.ts`.+**Interfaces:** `Conversation.chatLimits?: ChatLimits`; `recordChatAsk(group, id, at)` and `requireChatPost(group, command, reply)` / `recordChatPost(...)` reuse trusted context.++- [x] Commit failing command tests for third post across agents, new/old asks, thread-only followups, mirrors, eviction and private reader bookkeeping; add transactional integration test for competing third posts and retry.+- [x] Run focused tests and observe missing refusals.+- [x] Implement fixed-size ask ledger, monotonic eviction watermark and atomic post recording; classify/hide the new field in readers.+- [x] Run affected tests plus focused integration; commit and push.++### Task 3: One answer across agents and locations++**Files:** Modify `chatLimits.ts`, `chatLimits.test.ts`, `answers.test.ts`, `commands.ts`.+**Interfaces:** Store first answer on each ask; explicit `answers` or `answer` and direct person replies shown in main are answers; plain thread replies are discussion. Existing PM owed settlement remains independent.++- [x] Commit failing tests: plain second answer, Engineer then PM, main then thread and thread then main, distinct person followups, and reply-to-agent continuation. Update the two old expectations superseded by this task.+- [x] Run focused tests; confirm duplicate-answer refusals are missing.+- [x] Implement common guard and record first answer only; preserve task/Buddy legacy behavior.+- [x] Run affected command/answer/read tests, typecheck, diff check and hot-path comparison; post red/green evidence, mark ready for CI and request one independent review.+++## Evidence++- Content guard: `3ac59da35` produced 9 failures / 1 pass; `07f9488c8` passed content + acknowledgement checks (48 tests).+- Main budget: `2cc8137d5` produced 5 failures / 11 passes. Its transactional test let both competing posts through (expected only one). `fd3520c32` passed the focused integration file (3 tests), including replay and concurrent writes.+- Duplicate answers: `bfbf589f4` produced 6 failures / 25 passes; `bd4cf457a` fixed them. Formal answer links remain guarded; the review fixes below preserve ordinary discussion under the ask root.+- Card-number bypass: `e3e37988f` failed on a repeated `PR #12` without its URL; `e274001c7` passed it. File/tag status bypasses are also covered.+- Current-main merge: `d299e264e`; initial affected run passed 575 tests across 9 files; backend typecheck passed. Focused store integration passed 3 tests. Ready PR CI supplies full backend unit/integration evidence.+- Linked-answer posting benchmark vs main `bb34f2907`: 2,000 tasks and 50 active asks, 20 warmup pairs + 200 interleaved measured pairs. Median 4.025 -> 3.973 ms; p95 4.733 -> 4.488 ms. This measures applyCommand only, not delivery/database latency. No query/index changed.+- Empty-answer ledger with 50 asks is 2,710 JSON bytes. Each entry adds at most two 24-character post IDs and one first-answer record. The ledger stays bounded well below the conversation part's 4 MiB cap and disappears with the conversation. Production count/size/growth measurements could not be collected: the required read-only environment file is absent on this Team machine. No production access or write attempted; bounded local payload measurement replaces that evidence for this optional JSON field.+- Rollout: existing chats initialize with the next person ask; existing recorded PM answers still apply. The ledger retains 50 asks. After eviction older main budgets and formal answers close conservatively, including equal-timestamp unknown asks; plain thread discussion remains available under the ask or an existing response. No transcript is removed. Revert the backend change to roll back; no schema migration.+- Independent review and ready PR CI are the remaining delivery gates, owned by their steps/CI after submission.++### Review and CI corrections++- [x] Commit review regressions (`5ed2b2931`): three failures / 20 passes. An outage and older result after a full newer ask must pass; a second agent’s plain thread follow-up must pass.+- [x] Implement linked-only budgets and formal-answer distinction (`95f0527db`); 551 affected unit tests and three transactional integration tests passed.+- [x] Reproduce ready CI’s Buddy scope failure: three failures / 144 passes in buddies/buddyModel. Detect project chats by project lead-conversation ID without resolving a Swarm-wide Buddy’s nonexistent project (`c54f6e4ac`); 147 passes. The two affected activity/Buddy integration cases pass (92 unrelated cases skipped).+- [x] Commit boundary regression (`f2d3b7390`): answering an earlier agent response with 50 retained asks evicted its main-budget entry before recording the post and threw. Record the main slot before adding an answer target (`ac48a1dad`); 34 focused tests pass.+- [x] Final affected run: 651 tests across seven files, typecheck clean, three project-chat transactional integration tests pass. Reviewer’s light-load note requires no code change: chatLimits is in GROUP_FIELDS.unread and removed by both reader views.+- [ ] Same independent reviewer reads the corrected head; ready PR CI supplies complete backend and integration evidence.++### Notice-reply CI follow-up++- Ready CI at `c060ffe8b` found two visible responses to agent-only notices incorrectly treated as closed asks; those notices have no person-ask budget. The same two integration cases fail locally. Command regression `39e5ab996` fails (one failure / 24 passes); `17109530b` exempts the linked private notice from ask budgeting while keeping main content checks. Focused chatLimits/answers now pass 35 tests; typecheck passes after completing the test’s author context.+- The third CI failure is the project-rules fixture posting `Status: all good.` in main. Its agent-identity test now uses a substantive release line, preserving its original purpose and the new status guard.