Skip to content

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.

Merge batch 11-07 kE: #3323 #3355 #3393 #3395 #3403 (#3517)

0xken1505d2b1e3a6b7
diff --git a/backend/src/superTabs/answers.test.ts b/backend/src/superTabs/answers.test.ts
index 4635f721e..26caeeaa7 100644
--- a/backend/src/superTabs/answers.test.ts
+++ b/backend/src/superTabs/answers.test.ts
@@ -120,3 +120,51 @@ describe('the PM\'s answer', () => {
expect(answered.map(a => a.id)).toEqual(asks.slice(2))
})
})
+
+// Task #3747 (anh Dee, 11-06: "i don't know which one you reply to which... why don't you answer in those replies as threads?"):
+// answers right below their asks stacked in the main chat and lost their questions. A project can answer every person's
+// message in its thread instead.
+describe('in a project that answers people in threads', () => {
+ function threaded() {
+ const s = setup()
+ const projectId = s.f.group('lead').projectId ?? 'lead'
+ s.f.run({ type: 'project.answers', projectId, inThread: true } as Command, s.f.as(s.f.lead))
+ return { ...s, projectId }
+ }
+
+ it('puts a plain answer and an answer to a person\'s main-chat message in its thread, and settles it', () => {
+ const { f, ask, answer, owed } = threaded()
+ const question = ask('Can the board show who works?')
+ const { sent } = answer(f.lead, question, 'Yes, from tonight.', { plain: true })
+ expect(sent.replyTo).toBe(question.id)
+ expect(owed()).toEqual([])
+ const second = ask('And the costs?')
+ const { sent: answered } = answer(f.lead, second, 'Tomorrow.')
+ expect(answered.replyTo).toBe(second.id)
+ expect(f.group('lead').answered?.find(a => a.id === second.id)).toMatchObject({ answerId: answered.id, thread: second.id })
+ })
+
+ it('leaves a post that answers nothing in the main chat, and an answer to an agent below it', () => {
+ const { f } = threaded()
+ const news = f.run({ type: 'message.send', conversationId: 'lead', text: 'v1.4.23 is out.', replyTo: null, recipientIds: [] }, f.as(f.lead))
+ expect(news.messages.find(m => m.text === 'v1.4.23 is out.')).toMatchObject({ replyTo: null })
+ const agent = { kind: 'agent', id: f.dev, name: 'dev' } as Author
+ const effects = f.run({ type: 'message.send', conversationId: 'lead', text: 'The login fix ships tonight.', replyTo: null, recipientIds: [], answers: 'agent-line' } as Command,
+ f.as(f.lead), { reply: { id: 'agent-line', conversationId: 'lead', author: agent, createdAt: 0, thread: null } })
+ expect(effects.messages.find(m => m.text === 'The login fix ships tonight.')!.replyTo).toBeNull()
+ })
+
+ it('is set by the project\'s coordinator or a person who manages it, and turned off again; nobody else', () => {
+ const { f, projectId, refusal } = threaded()
+ expect(f.state.projects?.find(p => p.id === projectId)?.answersInThread).toBe(true)
+ expect(refusal(() => f.run({ type: 'project.answers', projectId, inThread: false } as Command, f.as(f.dev)))?.code).toBe('COORDINATOR_REQUIRED')
+ f.run({ type: 'project.answers', projectId, inThread: false } as Command, owner)
+ expect(f.state.projects?.find(p => p.id === projectId)?.answersInThread).toBeUndefined()
+ })
+
+ it('other projects answer right below, as before', () => {
+ const { f, ask, answer } = setup()
+ const question = ask('Can the board show who works?')
+ expect(answer(f.lead, question, 'Yes.', { plain: true }).sent.replyTo).toBeNull()
+ })
+})
diff --git a/backend/src/superTabs/buddyModel.test.ts b/backend/src/superTabs/buddyModel.test.ts
index f7f825f94..8ef973b48 100644
--- a/backend/src/superTabs/buddyModel.test.ts
+++ b/backend/src/superTabs/buddyModel.test.ts
@@ -9,6 +9,7 @@ import { swarmBuddyChatId } from './buddies.js'
import { sweepLiveness } from './liveness.js'
import { withoutMachineNames } from './store.js'
import { BUDDY_MODEL_GONE_MS, BUDDY_MODEL_LEASE_MS } from './tidy.js'
+import { expiredModelRequests, unservedBuddyModels } from './buddyModel.js'
const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
const peer: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'peer', email: '[email protected]' }
@@ -61,6 +62,17 @@ function setup(options: { buddyCapabilities?: string[] } = {}) {
const agent = () => state.agents.find(a => a.id === buddyId)!
return { run, grid, chat, buddyId, buddy, agent, get state() { return state } }
}
+/** A thread session of peer's Buddy, as its machine runs it (task #3810). */
+const addSession = (f: ReturnType<typeof setup>, id: string, harnessId: string, gridModel?: string) => {
+ const session = { ...structuredClone(f.agent()), id, harnessId, buddySession: { thread: id, from: 0 } }
+ delete session.modelRequest
+ if (gridModel) session.gridModel = gridModel
+ else delete session.gridModel
+ f.state.agents.push(session)
+ // A session is in its Buddy's chat, as a New session puts it (commands.ts routeBuddySession).
+ f.state.conversations.find(c => c.id === f.chat)!.agentIds.push(id)
+ return () => f.state.agents.find(a => a.id === id)!
+}
const code = (fn: () => unknown): string | undefined => {
try { fn() } catch (error) { return (error as { code?: string }).code }
return undefined
@@ -180,6 +192,19 @@ describe('the Buddy\'s machine reporting the switch', () => {
"peer's Buddy now runs on DeepSeek 4.1 Flash, which your machine serves."])
})
+ // Task #3810 (Diego, 11-06): a thread session the daemon refused to move was recorded on the model anyway, so costs and the
+ // serving member's "Used by" read it wrong.
+ it('records the model only on the thread sessions that moved: one that stayed is left on its owner\'s subscription', () => {
+ const { f, requestId } = asked()
+ const moved = addSession(f, 'moved', 'h-moved'), stayed = addSession(f, 'stayed', 'h-stayed')
+ f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId, ok: true, stayed: ['h-stayed'],
+ error: 'A thread session stayed where it was: it was answering' }, f.buddy())
+ expect(moved().gridModel).toBe(MODEL)
+ expect(stayed().gridModel).toBeUndefined()
+ // Nothing is owed for it: it runs on its owner's own subscription.
+ expect(stayed().homeOwed).toBeUndefined()
+ })
+
it('says which of its thread sessions stayed where they were', () => {
const { f, requestId } = asked()
const effects = f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId, ok: true,
@@ -297,6 +322,73 @@ describe('a Buddy coming home by itself', () => {
expect(f.agent().gridModel).toBeUndefined()
})
+ // Task #3810: a thread session left on the member's model by a limit was never moved home, so the limit stopped holding.
+ it('keeps a thread session that stayed on the member\'s model where it runs, and sends it home on the next sweep', () => {
+ const f = onModel()
+ const session = addSession(f, 'session', 'h-session', MODEL)
+ f.run({ type: 'agent.alert', agentId: f.buddyId, alert: 'limit', active: true }, f.buddy())
+ f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId: f.agent().modelRequest!.id, ok: true, stayed: ['h-session'],
+ error: 'A thread session stayed where it was: it was answering' }, f.buddy())
+ expect(f.agent().gridModel).toBeUndefined()
+ expect(session().gridModel).toBe(MODEL)
+ expect(session().homeOwed).toEqual({ reason: 'limit', tries: 1 })
+ unservedBuddyModels(f.state, NOW, () => 'follow-up')
+ expect(f.agent().modelRequest).toMatchObject({ id: 'follow-up', gridModel: null, sessionsOnly: true, reason: 'limit' })
+ const done = f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId: 'follow-up', ok: true }, f.buddy())
+ expect(done.messages.map(m => m.text)).toEqual(["Your Buddy's thread sessions are back on your subscription too."])
+ expect(session().gridModel).toBeUndefined()
+ expect(session().homeOwed).toBeUndefined()
+ unservedBuddyModels(f.state, NOW, () => 'again')
+ expect(f.agent().modelRequest).toBeUndefined()
+ })
+
+ it('stops sending a thread session home after three tries that it stayed, and tells its owner', () => {
+ const f = onModel()
+ const session = addSession(f, 'session', 'h-session', MODEL)
+ f.run({ type: 'agent.alert', agentId: f.buddyId, alert: 'limit', active: true }, f.buddy())
+ f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId: f.agent().modelRequest!.id, ok: true, stayed: ['h-session'] }, f.buddy())
+ let last: ReturnType<typeof f.run> | undefined
+ for (let i = 1; i <= 3; i++) {
+ unservedBuddyModels(f.state, NOW, () => `follow-up-${i}`)
+ last = f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId: `follow-up-${i}`, ok: true, stayed: ['h-session'],
+ error: 'A thread session stayed where it was: it was answering' }, f.buddy())
+ }
+ expect(session().homeOwed).toBeUndefined()
+ expect(session().gridModel).toBe(MODEL)
+ expect(last!.messages.map(m => m.text)).toEqual([
+ 'A thread session is still on DeepSeek 4.1 Flash: it was answering. End that thread\'s session to bring it back to your subscription.'])
+ unservedBuddyModels(f.state, NOW, () => 'again')
+ expect(f.agent().modelRequest).toBeUndefined()
+ })
+
+ it('counts a sessions-only move home its machine never answered as a try, and says nothing for it', () => {
+ const f = onModel()
+ const session = addSession(f, 'session', 'h-session', MODEL)
+ f.run({ type: 'agent.alert', agentId: f.buddyId, alert: 'limit', active: true }, f.buddy())
+ f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId: f.agent().modelRequest!.id, ok: true, stayed: ['h-session'] }, f.buddy())
+ unservedBuddyModels(f.state, NOW, () => 'follow-up')
+ expect(expiredModelRequests(f.state, NOW + BUDDY_MODEL_LEASE_MS)).toEqual([])
+ expect(f.agent().modelRequest).toBeUndefined()
+ expect(session().homeOwed).toEqual({ reason: 'limit', tries: 2 })
+ })
+
+ // Review of #3393: the last unanswered follow-up dropped the session's follow-up with no word to its owner.
+ it('tells the owner when follow-ups its machine never answered run out, and asks no more', () => {
+ const f = onModel()
+ const session = addSession(f, 'session', 'h-session', MODEL)
+ f.run({ type: 'agent.alert', agentId: f.buddyId, alert: 'limit', active: true }, f.buddy())
+ f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId: f.agent().modelRequest!.id, ok: true, stayed: ['h-session'] }, f.buddy())
+ const said: string[][] = []
+ for (let i = 1; i <= 3; i++) {
+ unservedBuddyModels(f.state, NOW, () => `follow-up-${i}`)
+ said.push(expiredModelRequests(f.state, NOW + BUDDY_MODEL_LEASE_MS).map(line => line.text))
+ }
+ expect(said).toEqual([[], [], ["A thread session is still on DeepSeek 4.1 Flash: its computer didn't answer. End that thread's session to bring it back to your subscription."]])
+ expect(session().homeOwed).toBeUndefined()
+ unservedBuddyModels(f.state, NOW, () => 'again')
+ expect(f.agent().modelRequest).toBeUndefined()
+ })
+
it('goes back when the model keeps failing', () => {
const f = onModel()
f.run({ type: 'agent.alert', agentId: f.buddyId, alert: 'model', active: true }, f.buddy())
@@ -400,4 +492,19 @@ describe('switching one of several Buddies', () => {
expect(f.agent().modelRequest).toBeUndefined()
expect(code(() => f.run({ type: 'buddy.model', gridModel: MODEL, conversationId: 'lead' } as Command))).toBe('NOT_FOUND')
})
+
+ // Task #3810 with #3818: a thread session a move home left on a shared model is moved by its own Buddy's machine request, never
+ // by another of its owner's Buddies, whose chat does not hold it.
+ it('asks only the Buddy whose thread session stayed on a shared model to move it home', () => {
+ const { f, second, agent } = two()
+ f.run({ type: 'buddy.model', gridModel: MODEL })
+ f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId: f.agent().modelRequest!.id, ok: true }, f.buddy())
+ const session = addSession(f, 'session', 'h-session', MODEL)
+ f.run({ type: 'agent.alert', agentId: f.buddyId, alert: 'limit', active: true }, f.buddy())
+ f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId: f.agent().modelRequest!.id, ok: true, stayed: ['h-session'] }, f.buddy())
+ expect(session().homeOwed).toEqual({ reason: 'limit', tries: 1 })
+ unservedBuddyModels(f.state, NOW, buddy => `follow-up-${buddy.id}`)
+ expect(f.agent().modelRequest).toMatchObject({ gridModel: null, sessionsOnly: true })
+ expect(agent(second).modelRequest).toBeUndefined()
+ })
})
diff --git a/backend/src/superTabs/buddyModel.ts b/backend/src/superTabs/buddyModel.ts
index a1537d937..4169e1461 100644
--- a/backend/src/superTabs/buddyModel.ts
+++ b/backend/src/superTabs/buddyModel.ts
@@ -22,6 +22,8 @@ export const BUDDY_MODEL_CAPABILITY = 'buddyModel'
export const BUDDY_MODEL_LEASE_MS = 10 * 60_000
/** How long nobody serves the model a Buddy runs on before it is sent home: a machine's reading may lapse for a moment. */
export const BUDDY_MODEL_GONE_MS = 2 * 60_000
+/** How many times a thread session may stay on a shared model when sent home before its owner is told to end it (#3810). */
+export const HOME_TRIES = 3
/** One line the switch writes: in a Buddy chat, naming the machines a Buddy reading it must not learn (store.ts
* withoutMachineNames). */
@@ -119,7 +121,7 @@ function hiddenMachines(state: SuperTabState, buddy: Agent, request: NonNullable
/** The Buddy's machine reports the switch it carried out: the Buddy is on the model, or stays where it was. The first line is
* the owner's; then one for each other member who serves the model it landed on. */
export function buddyModelResult(state: SuperTabState, actor: Actor,
- command: { agentId: string; requestId: string; ok: boolean; fresh?: boolean; error?: string }, now: number): ModelLine[] {
+ command: { agentId: string; requestId: string; ok: boolean; fresh?: boolean; error?: string; stayed?: string[] }, now: number): ModelLine[] {
const buddy = state.agents.find(a => a.id === command.agentId)
if (!buddy || actor.kind !== 'agent' || actor.agentId !== buddy.id || !isSwarmBuddy(buddy)) fail('BUDDY_FORBIDDEN', 'Only the Buddy\'s machine reports its switch.', 403)
const request = buddy.modelRequest
@@ -136,11 +138,32 @@ export function buddyModelResult(state: SuperTabState, actor: Actor,
}
delete buddy.gridModelUnservedSince
// Its machine moved its thread sessions with it (cli superTabs/buddyModel.ts): what they run on is recorded the same way, so
- // costs and the serving member's "Used by" read it right.
+ // costs and the serving member's "Used by" read it right. One it could not move (`stayed`) runs where it was, and is
+ // recorded there (task #3810); left on a shared model by a move home, it is owed one, which the liveness sweep asks for.
+ const stayedIds = new Set(command.stayed ?? []), words = clean(command.error ?? '')
const sessions = chat ? sessionAgentsOf(state, chat) : state.agents.filter(a => a.buddySession && a.buddyOf?.personId === owner.personId && a.buddyOf.generation === owner.generation)
+ const gaveUp: Agent[] = []
for (const session of sessions) {
- if (request.gridModel === null) delete session.gridModel
- else session.gridModel = request.gridModel
+ if (!stayedIds.has(session.harnessId)) {
+ if (request.gridModel === null) delete session.gridModel
+ else session.gridModel = request.gridModel
+ delete session.homeOwed
+ } else if (request.gridModel !== null || !session.gridModel) delete session.homeOwed
+ else {
+ const tries = (session.homeOwed?.tries ?? 0) + 1
+ if (tries > HOME_TRIES) { delete session.homeOwed; gaveUp.push(session) }
+ else session.homeOwed = { ...request.reason ? { reason: request.reason } : {}, tries }
+ }
+ }
+ if (request.sessionsOnly) {
+ if (gaveUp.length) {
+ const on = gaveUp[0]!.gridModel!
+ // The host's words name why (cli superTabs/buddyModel.ts), after its own lead-in, which this line says differently.
+ const why = words.replace(/^(?:A thread session stayed where it was|\d+ thread sessions stayed where they were): /, '')
+ return mine(stillOn(state, on, why || 'its computer could not move it', now, request.name))
+ }
+ // Another try is owed while one stays; its owner hears once it lands or gives up, not at every try.
+ return stayedIds.size ? [] : mine('Your Buddy\'s thread sessions are back on your subscription too.')
}
if (request.gridModel === null) {
delete buddy.gridModel
@@ -187,14 +210,44 @@ export function expiredModelRequests(state: SuperTabState, now: number): Array<{
const request = buddy.modelRequest
if (!request || !buddy.buddyOf || now < Date.parse(request.at) + BUDDY_MODEL_LEASE_MS) continue
delete buddy.modelRequest
- out.push({ buddy, requestId: request.id, conversationId: buddyChatOf(state, buddy)?.id ?? swarmBuddyChatId({ id: buddy.buddyOf.personId, generation: buddy.buddyOf.generation }),
+ const conversationId = buddyChatOf(state, buddy)?.id ?? swarmBuddyChatId({ id: buddy.buddyOf.personId, generation: buddy.buddyOf.generation })
+ // A sessions-only move home its machine never answered counts as a try, said only when it gives up (task #3810; review of
+ // #3393: the last one gave up without a word).
+ if (request.sessionsOnly) {
+ const gaveUp = owedHome(state, buddy).filter(countTry)
+ if (gaveUp.length) out.push({ buddy, requestId: request.id, machines: hiddenMachines(state, buddy, request, now), conversationId,
+ text: stillOn(state, gaveUp[0]!.gridModel!, 'its computer didn\'t answer', now, request.name) })
+ continue
+ }
+ out.push({ buddy, requestId: request.id, conversationId,
machines: hiddenMachines(state, buddy, request, now),
text: `Couldn't switch your Buddy: its computer didn't answer. It is still on ${current(state, buddy, now)}.` })
}
return out
}
-/** Buddies on a model nobody has served for BUDDY_MODEL_GONE_MS are sent home; one served again is unmarked. */
+/** [buddy]'s thread sessions a move home left on a shared model (task #3810): those in its own chat, as buddyModelResult moves
+ * them (task #3818: a person may have several Buddies), else all of its owner's. */
+function owedHome(state: SuperTabState, buddy: Agent): Agent[] {
+ const chat = buddyChatOf(state, buddy)
+ const sessions = chat ? sessionAgentsOf(state, chat)
+ : state.agents.filter(a => a.buddySession && a.buddyOf?.personId === buddy.buddyOf!.personId && a.buddyOf.generation === buddy.buddyOf!.generation)
+ return sessions.filter(a => a.homeOwed && a.gridModel)
+}
+/** One more try at moving [session] home; true when that was the last, and its follow-up is dropped. */
+function countTry(session: Agent): boolean {
+ const tries = session.homeOwed!.tries + 1
+ if (tries <= HOME_TRIES) { session.homeOwed = { ...session.homeOwed!, tries }; return false }
+ delete session.homeOwed
+ return true
+}
+/** The owner's line when a thread session stays on [model] after its last try home: what to do about it. [known]: the name the
+ * request recorded, for when no machine serves the model by now. */
+const stillOn = (state: SuperTabState, model: string, why: string, now: number, known?: string) =>
+ `A thread session is still on ${served(state, model, now)?.name ?? known ?? model}: ${why}. End that thread's session to bring it back to your subscription.`
+
+/** Buddies on a model nobody has served for BUDDY_MODEL_GONE_MS are sent home; one served again is unmarked. A Buddy at home
+ * whose thread session a move home left on a shared model asks its machine to move that session home (task #3810). */
export function unservedBuddyModels(state: SuperTabState, now: number, requestId: (buddy: Agent) => string): void {
for (const buddy of state.agents) {
if (!buddy.gridModel || buddy.buddySession || !isSwarmBuddy(buddy)) continue
@@ -204,6 +257,13 @@ export function unservedBuddyModels(state: SuperTabState, now: number, requestId
sendBuddyHome(state, buddy, 'gone', requestId(buddy), now)
if (buddy.modelRequest) delete buddy.gridModelUnservedSince
}
+ for (const buddy of state.agents) {
+ if (buddy.buddySession || !isSwarmBuddy(buddy) || buddy.gridModel || buddy.modelRequest) continue
+ const owed = owedHome(state, buddy)[0]
+ if (!owed || !switchable(state, buddy, now).ok) continue
+ buddy.modelRequest = { id: requestId(buddy), gridModel: null, sessionsOnly: true, name: served(state, owed.gridModel!, now)?.name ?? owed.gridModel!,
+ ...owed.homeOwed!.reason ? { reason: owed.homeOwed!.reason } : {}, requestedBy: buddy.buddyOf!.personId, at: new Date(now).toISOString() }
+ }
}
/** A Buddy thread session's model (commands.ts message.send newSession): the shared one its Buddy runs on while it is served, or
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 60e6b3fb0..97361ffa0 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -293,6 +293,8 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('note.remove'), projectId: id, noteId: id }).strict(),
// What the project calls its coordinator, as its instructions say (instructions.ts coordinatorNameOf).
z.object({ type: z.literal('project.coordinatorName'), projectId: id, name: roleNameSchema }).strict(),
+ // Whether its agents answer each person's message in that message's thread (projects.ts answersInThread, task #3747).
+ z.object({ type: z.literal('project.answers'), projectId: id, inThread: z.boolean() }).strict(),
z.object({ type: z.literal('lead.start'), projectId: id, machineId: id.nullable(), engine: swarmEngine,
model: z.string().trim().min(1).max(200).optional(), effort: z.string().trim().min(1).max(80).optional(),
branchRef: z.string().max(1024).regex(/^refs\/(heads|remotes)\/[^\s\x00-\x1f\x7f]+$/).optional(), repositoryUrl: repositoryUrl.optional() }).strict(),
@@ -385,7 +387,8 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('buddy.model'), gridModel: z.string().trim().min(1).max(200).nullable(), conversationId: id.optional() }).strict(),
// What the Buddy's machine reports once it carried the request out: `fresh` when the conversation was too long for the model.
z.object({ type: z.literal('buddy.modelResult'), agentId: id, requestId: id, ok: z.boolean(), fresh: z.boolean().optional(),
- error: z.string().max(300).optional() }).strict(),
+ // The thread sessions its machine could not move, by harness id: they run where they were (buddyModel.ts, task #3810).
+ error: z.string().max(300).optional(), stayed: z.array(id).max(64).optional() }).strict(),
z.object({ type: z.literal('buddy.sessionEnd'), conversationId: id, thread: id, reason: z.enum(['ended', 'idle', 'stopped', 'maintenance']) }).strict(),
// The PM's private line to one person, in their Buddy chat of its project: Buddies replaced Chat with PM (Ken, 10-29).
z.object({ type: z.literal('person.tell'), personId: id, text: z.string().trim().min(1).max(32_000) }).strict(),
@@ -1088,13 +1091,25 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
/** An answer (answers.ts) to a reply inside a thread goes in that thread: a reply to it, never right below it in the main chat.
* Worked out before anything reads where the post goes, so it routes, settles and threads as that reply would. */
-function placeAnswer(command: Command, context: CommandContext): Command {
- if (command.type !== 'message.send' || !command.answer) return command
- if (!command.answers || command.replyTo) fail('VALIDATION_ERROR', 'An answer names the message it answers, and nothing else to reply to.', 400)
+function placeAnswer(command: Command, context: CommandContext, state: SuperTabState): Command {
+ if (command.type !== 'message.send') return command
+ // In a project that answers people in threads (task #3747), any post naming a person's message in the main chat goes in its
+ // thread, whatever the client sent: an older host's --answers, or an agent that skipped its reply line. A post naming
+ // nothing stays in the main chat, and an agent's message is answered as before.
const reply = context.reply
+ if (command.answers && !command.replyTo && reply?.id === command.answers && reply.author.kind === 'person' && !inThread(reply)
+ && answersInThread(state, command.conversationId)) return { ...command, replyTo: command.answers, answers: undefined }
+ if (!command.answer) return command
+ if (!command.answers || command.replyTo) fail('VALIDATION_ERROR', 'An answer names the message it answers, and nothing else to reply to.', 400)
return reply && reply.id === command.answers && inThread(reply) ? { ...command, replyTo: command.answers, answers: undefined } : command
}
+/** Whether [conversationId]'s project answers people in threads. Never throws: a conversation outside every project does not. */
+function answersInThread(state: SuperTabState, conversationId: string): boolean {
+ const group = state.conversations.find(c => c.id === conversationId)
+ try { return !!group && groupProject(state, group).answersInThread === true } catch { return false }
+}
+
/** The project `project.closeTab` may close (task #3929): a no-repo tab's, in the caller's own Personal Swarm, by that person.
* Desktop creates a tab's project with the request `personal-tab-…` (desktop personal_projects.dart personalProjectOperation),
* and `project.create` makes its id from that request and its sender (applyCommandOnce `operationId`), so [tabOperation]
@@ -1111,7 +1126,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
// A credential someone pasted, or an agent echoed from its terminal, is gone before anything is stored or delivered
// (Oct 2026: a Harness access token in a shared Lead chat). The sender's result says what went.
const removed: CredentialKind[] = []
- const command = placeAnswer(withoutCredentials(commandSchema.parse(input), removed), context)
+ const command = placeAnswer(withoutCredentials(commandSchema.parse(input), removed), context, original)
const state = cloneData(original)
numberConversations(state)
placeRules(state)
@@ -2485,6 +2500,17 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
if (noteIndex(command.noteId) > noteIndex(stored.processNote?.confirmed)) stored.processNote = { ...stored.processNote, confirmed: command.noteId }
break
}
+ case 'project.answers': {
+ // As its coordinator's name: the coordinator sets it, or a person who manages the project.
+ const project = readProject(state, actor, command.projectId)
+ if (actor.kind === 'agent') coordinatorOf(project)
+ else manageProject(state, actor, project.id)
+ mutableProjects(state)
+ const stored = projectOf(state, project.id)
+ if (command.inThread) stored.answersInThread = true
+ else delete stored.answersInThread
+ break
+ }
case 'project.digest': {
const project = readProject(state, actor, command.projectId)
const lead = conversation(state, project.leadConversationId).leadId
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index d82f23f44..0477e22f7 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -93,7 +93,12 @@ export interface Agent {
* window, the smallest any serving machine reported. One at a time; the result or the liveness sweep's lease drops it. */
modelRequest?: { id: string; gridModel: string | null; gridName?: string; name?: string; servedBy?: string[]; machines?: string[]; contextWindow?: number; requestedBy: string; at: string
/** Set when the Swarm sent the Buddy home by itself: the model hit a limit, kept failing, or nobody served it. */
- reason?: 'limit' | 'failing' | 'gone' }
+ reason?: 'limit' | 'failing' | 'gone'
+ /** Only its thread sessions move: a move home left one on a shared model (buddyModel.ts, task #3810). */
+ sessionsOnly?: true }
+ /** A Buddy thread session that stayed on a shared model when its Buddy went home (task #3810): why it was sent home, and how
+ * many times it stayed. The liveness sweep asks its machine to move it home again, three times at most (buddyModel.ts). */
+ homeOwed?: { reason?: 'limit' | 'failing' | 'gone'; tries: number }
/** When the liveness sweep first found nobody serving the Buddy's `gridModel` (ms): two minutes on, it is sent home. */
gridModelUnservedSince?: number
/** The name its owner was shown for the Buddy's `gridModel`, for the lines after nobody serves it any more. */
diff --git a/backend/src/superTabs/parts/touches.test.ts b/backend/src/superTabs/parts/touches.test.ts
index 3d1396192..00fcc6e6b 100644
--- a/backend/src/superTabs/parts/touches.test.ts
+++ b/backend/src/superTabs/parts/touches.test.ts
@@ -56,6 +56,7 @@ describe('the parts a command touches (design section 1.2, column T)', () => {
[{ type: 'note.add', projectId: 'lead', text: 'Not machine B.', askedBy: 'owner' }, {}],
[{ type: 'note.remove', projectId: 'lead', noteId: 'n1' }, { notes }],
[{ type: 'project.coordinatorName', projectId: 'lead', name: 'Lead engineer' }, {}],
+ [{ type: 'project.answers', projectId: 'lead', inThread: true }, {}],
// An older CLI's rule, a save to the instructions after the one above (project instructions, phase 4).
[{ type: 'rule.set', rule: { kind: 'preferIdle' }, text: 'Idle first.', askedIn: { conversationId: 'lead', messageId: 'm1' } },
{ askedIn: { author: { kind: 'person', id: 'owner', name: 'owner', membershipGeneration: 'g' }, source: false, createdAt: 0 },
diff --git a/backend/src/superTabs/parts/touches.ts b/backend/src/superTabs/parts/touches.ts
index f65daf159..0c52cf856 100644
--- a/backend/src/superTabs/parts/touches.ts
+++ b/backend/src/superTabs/parts/touches.ts
@@ -124,7 +124,7 @@ export function touchesFor(command: Command, actor: Actor, before: SuperTabState
break
case 'project.report': case 'project.repository':
// The coordinator's own writes check it leads the project, which a concurrent Lead change ends (review of phase 2).
- case 'instructions.save': case 'note.add': case 'note.remove': case 'project.coordinatorName':
+ case 'instructions.save': case 'note.add': case 'note.remove': case 'project.coordinatorName': case 'project.answers':
leadCheck(command.projectId)
break
// A rules save writes its own collection, no part of the project: by anyone, it guards on the project's Lead chat, which a
diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.ts
index c8d7e37ef..5b885e50a 100644
--- a/backend/src/superTabs/projects.ts
+++ b/backend/src/superTabs/projects.ts
@@ -114,6 +114,9 @@ export interface SwarmProject {
githubSeen?: GitHubSeen
/** What its coordinator is called; reads give "Product Manager" when absent (instructions.ts coordinatorNameOf). */
coordinatorName?: string
+ /** Agents answer every person's message in that message's thread, never right below it in the main chat (task #3747, anh
+ * Dee 11-06: "i don't know which one you reply to which"). Absent: as before. Set with `project.answers`. */
+ answersInThread?: true
/** Its owner's last "New repository" from New Project (task #1788): asked, then what GitHub's sign-in made of it. The
* app that asked starts the Product Manager in it once `created`; the next ask replaces it. */
repositoryCreation?: RepositoryCreation
diff --git a/cli/src/lib/agentShellGuard.ts b/cli/src/lib/agentShellGuard.ts
index f3a02d7aa..8ed79b3cf 100644
--- a/cli/src/lib/agentShellGuard.ts
+++ b/cli/src/lib/agentShellGuard.ts
@@ -34,7 +34,7 @@ export function claudeShellGuardArgs(platform: NodeJS.Platform = process.platfor
const hook = Array.isArray(quoted)
? { type: 'command', command: quoted[0], args: quoted.slice(1), timeout: TIMEOUT }
: { type: 'command', command: quoted, timeout: TIMEOUT }
- return ['--settings', JSON.stringify({ hooks: { PreToolUse: [{ matcher: CLAUDE_MATCHER, hooks: [hook] }] } })]
+ return ['--settings', JSON.stringify({ disableAllHooks: false, hooks: { PreToolUse: [{ matcher: CLAUDE_MATCHER, hooks: [hook] }] } })]
}
/** The guard as Codex runs it and hashes it: every tool, a POSIX line, or on Windows a PowerShell one. */
diff --git a/cli/src/lib/engineProbe.spec.ts b/cli/src/lib/engineProbe.spec.ts
new file mode 100644
index 000000000..c831add2e
--- /dev/null
+++ b/cli/src/lib/engineProbe.spec.ts
@@ -0,0 +1,52 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { probeEngines } from './engineProbe.js'
+import { engineAccount } from './engineAccount.js'
+import { commandAvailableInInteractiveShell } from './engineLaunch.js'
+
+vi.mock('./engineAccount.js', () => ({ engineAccount: vi.fn() }))
+vi.mock('./engineLaunch.js', () => ({ commandAvailableInInteractiveShell: vi.fn() }))
+vi.mock('./engineBin.js', () => ({
+ engineBin: (engine: string) => engine === 'terminal' ? '' : engine,
+ enginePathOverride: () => undefined,
+}))
+
+beforeEach(() => {
+ vi.mocked(commandAvailableInInteractiveShell).mockReset().mockResolvedValue(true)
+ vi.mocked(engineAccount).mockReset().mockResolvedValue({ signedIn: null, lastUsedAt: null })
+})
+
+describe('account availability for pane engines', () => {
+ it.each([true, false, null])('reports an installed Cursor account as %s without copying credential fields', async signedIn => {
+ vi.mocked(engineAccount).mockResolvedValue({ signedIn, lastUsedAt: 42, token: 'test-secret' } as never)
+ expect(await probeEngines(['cursor'], { accounts: true })).toEqual([
+ { engine: 'cursor', installed: true, command: 'cursor', installable: false, signedIn, lastUsedAt: 42 },
+ ])
+ })
+
+ it('leaves failed account reads unknown and does not expose their error', async () => {
+ vi.mocked(engineAccount).mockRejectedValue(new Error('test-secret'))
+ expect(await probeEngines(['cursor'], { accounts: true })).toEqual([
+ { engine: 'cursor', installed: true, command: 'cursor', installable: false, signedIn: null, lastUsedAt: null },
+ ])
+ })
+
+ it('does not turn malformed reader fields into signed-in readiness or expose them', async () => {
+ vi.mocked(engineAccount).mockResolvedValue({ signedIn: 'test-secret', lastUsedAt: 'test-secret' } as never)
+ expect(await probeEngines(['cursor'], { accounts: true })).toEqual([
+ { engine: 'cursor', installed: true, command: 'cursor', installable: false, signedIn: null, lastUsedAt: null },
+ ])
+ })
+
+ it('does not read accounts unless requested, installed, and a process engine', async () => {
+ await probeEngines(['claude', 'cursor'])
+ vi.mocked(commandAvailableInInteractiveShell).mockResolvedValue(false)
+ await probeEngines(['claude', 'cursor', 'terminal'], { accounts: true })
+ expect(engineAccount).not.toHaveBeenCalled()
+ })
+
+ it('keeps existing Claude and Codex account results', async () => {
+ vi.mocked(engineAccount).mockResolvedValue({ signedIn: true, lastUsedAt: 123 })
+ expect((await probeEngines(['claude', 'codex'], { accounts: true })).map(row => [row.engine, row.signedIn, row.lastUsedAt]))
+ .toEqual([['claude', true, 123], ['codex', true, 123]])
+ })
+})
diff --git a/cli/src/lib/engineProbe.ts b/cli/src/lib/engineProbe.ts
index 58b0ae1a2..bc7faf127 100644
--- a/cli/src/lib/engineProbe.ts
+++ b/cli/src/lib/engineProbe.ts
@@ -30,7 +30,7 @@
* reported as not installed, which is the state a plain `command -v` gets wrong.
*/
-import { ENGINES, type AgentEngine } from '../engines/types.js'
+import { ENGINES, isTerminalEngine, type AgentEngine } from '../engines/types.js'
import { engineBin, enginePathOverride } from './engineBin.js'
import { commandAvailableInInteractiveShell } from './engineLaunch.js'
import { engineInstallRecipe } from './engineInstall.js'
@@ -45,9 +45,9 @@ export interface EngineAvailability {
readonly command: string | null
/** Whether Harness can apply the official recipe without overriding a custom launch path. */
readonly installable: boolean
- /** Claude Code and Codex, when installed: is a credential there (engineAccount.ts). */
+ /** Installed process engines: credential presence, or null when the reader cannot say. */
readonly signedIn?: boolean | null
- /** Claude Code and Codex, when installed: the engine's latest session activity, ms. */
+ /** Installed process engines: latest known session activity, ms; null when unavailable. */
readonly lastUsedAt?: number | null
}
@@ -112,18 +112,20 @@ export async function probeEngines(
installed = false
}
}
- // Lets the New Harness box open on the agent this person already uses (engineAccount.ts).
- // Only for the caller that shows it (the New Harness box): a login shell's environment, the
- // Keychain and the project folders are not what an installed-or-not question needs.
- const account = options.accounts && installed && (engine === 'claude' || engine === 'codex')
- ? await engineAccount(engine).catch(() => null)
- : null
+ // Account knowledge belongs to the engine reader, not this shared probe (#3839). An
+ // unsupported reader answers unknown; neither a failure nor an install proves sign-in.
+ const readAccount = options.accounts && installed && !isTerminalEngine(engine)
+ const account = readAccount ? await engineAccount(engine).catch(() => null) : null
results[index] = {
engine,
installed,
command,
installable: !installed && command !== null && recipe !== undefined,
- ...(account ? { signedIn: account.signedIn, lastUsedAt: account.lastUsedAt } : {}),
+ // Project only safe scalars: future readers must not leak credentials or error details.
+ ...(readAccount ? {
+ signedIn: typeof account?.signedIn === 'boolean' ? account.signedIn : null,
+ lastUsedAt: typeof account?.lastUsedAt === 'number' && Number.isFinite(account.lastUsedAt) ? account.lastUsedAt : null,
+ } : {}),
}
}
}
diff --git a/cli/src/lib/machineEngines.spec.ts b/cli/src/lib/machineEngines.spec.ts
index ab42b56e2..69671987f 100644
--- a/cli/src/lib/machineEngines.spec.ts
+++ b/cli/src/lib/machineEngines.spec.ts
@@ -48,7 +48,7 @@ describe('harness machines engines (#1788)', () => {
const lines: string[] = []
const code = await runMachinesEngines(['office', '--engine', 'hermes', '--engine', 'hermes', '--json'], '/tmp', 1, probe, (line) => lines.push(line))
expect(code).toBe(0)
- expect(asked).toEqual([{ machine: 'office', payload: { engines: ['hermes'] } }])
+ expect(asked).toEqual([{ machine: 'office', payload: { engines: ['hermes'], accounts: true } }])
expect(lines.map((line) => JSON.parse(line))).toEqual([
{ machineId: OFFICE, engine: 'hermes', installed: true, signedIn: null, installable: true, firstPrompt: true },
])
@@ -57,7 +57,7 @@ describe('harness machines engines (#1788)', () => {
it('asks for every engine when none is named', async () => {
const { asked, probe } = probing({ engines: [] })
expect(await runMachinesEngines(['office', '--json'], '/tmp', 1, probe, () => {})).toBe(0)
- expect(asked[0].payload).toEqual({})
+ expect(asked[0].payload).toEqual({ accounts: true })
})
it('refuses an engine it does not know, a missing machine and an unknown flag, asking nothing', async () => {
diff --git a/cli/src/lib/machineEngines.ts b/cli/src/lib/machineEngines.ts
index 0192bf140..01e7e9848 100644
--- a/cli/src/lib/machineEngines.ts
+++ b/cli/src/lib/machineEngines.ts
@@ -16,7 +16,7 @@ export interface EngineReadiness {
/** `true`, or `null`: the probe reads a missing command, a login shell that timed out and a failed spawn
* all as not installed (engineProbe.ts), so only a failed start says an engine is missing. */
installed: true | null
- /** Read for claude and codex only, and only once installed; `null` for every other engine. */
+ /** Read only once installed; `null` when the engine's account reader cannot say. */
signedIn: boolean | null
installable: boolean | null
/** Whether that machine's Harness can start the engine with a first prompt; `null` from an older Harness. */
@@ -77,7 +77,7 @@ export async function runMachinesEngines(argv: string[], dataDir: string, port:
}
let answer: { machineId: string; reply: Record<string, unknown> }
try {
- answer = await probe(words[0], engines.length ? { engines } : {})
+ answer = await probe(words[0], { ...(engines.length ? { engines } : {}), accounts: true })
} catch (error) {
console.error((error as Error).message)
return 1
diff --git a/cli/src/lib/swarmEngineArgs.spec.ts b/cli/src/lib/swarmEngineArgs.spec.ts
index 75d7227ea..d2cf3a641 100644
--- a/cli/src/lib/swarmEngineArgs.spec.ts
+++ b/cli/src/lib/swarmEngineArgs.spec.ts
@@ -4,6 +4,7 @@ import { claudeShellGuardArgs, codexShellGuardArgs, shellGuardArgv } from './age
import { swarmEngineArgs } from './swarmEngineArgs.js'
const settingsOf = (args: string[]) => JSON.parse(args[args.indexOf('--settings') + 1]) as {
+ disableAllHooks?: boolean
hooks: { PreToolUse: { matcher: string; hooks: { type: string; command: string; args?: string[]; timeout: number }[] }[] }
}
@@ -21,6 +22,13 @@ describe('what the Swarm adds to an engine\'s argv', () => {
expect(blocks[0].hooks).toEqual([{ type: 'command', command: expect.stringContaining('__swarm-shell-guard'), timeout: 30 }])
})
+ it('re-enables hooks for a Swarm session even when inherited Claude settings disable all hooks', () => {
+ const inherited = { disableAllHooks: true }
+ const session = { ...inherited, ...settingsOf(swarmEngineArgs('claude')) }
+ expect(session.disableAllHooks).toBe(false)
+ expect(session.hooks.PreToolUse).toHaveLength(1)
+ })
+
it('runs it before each of a Swarm Codex session\'s tool calls, as a session flag', () => {
expect(swarmEngineArgs('codex')).toEqual(['-c', 'check_for_update_on_startup=false', ...codexShellGuardArgs()])
const [flag, value] = codexShellGuardArgs('darwin', ['/opt/node', '/x/cli.js', '__swarm-shell-guard'])
diff --git a/cli/src/superTabs/buddyModel.spec.ts b/cli/src/superTabs/buddyModel.spec.ts
index 94363794e..224ca9f5f 100644
--- a/cli/src/superTabs/buddyModel.spec.ts
+++ b/cli/src/superTabs/buddyModel.spec.ts
@@ -69,7 +69,46 @@ describe('carrying out a Buddy\'s model request', () => {
const f = fixture({ tokens: { 'h-main': 1_000, 'h-a': 120_000, 'h-b': 1_000 }, answers: [{ retargeted: true }, { retargeted: true }, { error: 'AGENT_BUSY' }] })
await f.runner.serve(main(), [thread('h-a'), thread('h-b')])
expect(f.frames.map(frame => [frame.agentId, frame.fresh ?? false])).toEqual([['h-main', false], ['h-a', true], ['h-b', false]])
- expect(f.posts).toEqual([expect.objectContaining({ ok: true, error: 'A thread session stayed where it was: it was answering' })])
+ expect(f.posts).toEqual([expect.objectContaining({ ok: true, stayed: ['h-b'], error: 'A thread session stayed where it was: it was answering' })])
+ })
+
+ // Task #3810 (Diego, 11-06): a send-home left a busy thread session on the member's model and reported ok, so its limit
+ // stopped holding. Linux test of #3393: the Buddy itself is reported at once, so the Swarm records it home and its owner
+ // may switch again; the session, reported as stayed, is waited for by the sessions-only follow-up the Swarm then asks for.
+ it('on a send-home, reports the Buddy at once and names a thread session that is answering as stayed', async () => {
+ const f = fixture({ answers: [{ retargeted: true }, { error: 'AGENT_BUSY' }] })
+ await f.runner.serve(main(request({ gridModel: null, gridName: undefined, reason: 'limit' })), [thread('h-a')])
+ expect(f.frames.map(frame => frame.agentId)).toEqual(['h-main', 'h-a'])
+ expect(f.posts).toEqual([expect.objectContaining({ ok: true, stayed: ['h-a'], error: 'A thread session stayed where it was: it was answering' })])
+ })
+
+ it('on the follow-up for the sessions alone, waits for one that is answering and moves it once its turn ends', async () => {
+ const f = fixture({ answers: [{ error: 'AGENT_BUSY' }, { retargeted: true }] })
+ const followUp = main(request({ gridModel: null, gridName: undefined, reason: 'limit', sessionsOnly: true }))
+ await f.runner.serve(followUp, [thread('h-a')])
+ expect(f.posts).toEqual([])
+ f.later(15_000)
+ await f.runner.serve(followUp, [thread('h-a')])
+ expect(f.frames.map(frame => frame.agentId)).toEqual(['h-a', 'h-a'])
+ expect(f.posts).toEqual([{ asAgentId: 'buddy', type: 'buddy.modelResult', agentId: 'buddy', requestId: 'req1', ok: true }])
+ })
+
+ it('reports a thread session that is still answering as stayed once the follow-up\'s lease is nearly over', async () => {
+ const f = fixture({ answers: [{ error: 'AGENT_BUSY' }, { error: 'AGENT_BUSY' }] })
+ const followUp = main(request({ gridModel: null, gridName: undefined, sessionsOnly: true, at: new Date(0).toISOString() }))
+ await f.runner.serve(followUp, [thread('h-a')])
+ // A follow-up after the person's own move home has no reason, and still waits: the Buddy is not in it.
+ expect(f.posts).toEqual([])
+ f.later(10 * 60_000)
+ await f.runner.serve(followUp, [thread('h-a')])
+ expect(f.posts).toEqual([expect.objectContaining({ ok: true, stayed: ['h-a'], error: 'A thread session stayed where it was: it was answering' })])
+ })
+
+ it('moves only the thread sessions for a request that is for them alone: the Buddy is already there', async () => {
+ const f = fixture()
+ await f.runner.serve(main(request({ gridModel: null, gridName: undefined, reason: 'limit', sessionsOnly: true })), [thread('h-a')])
+ expect(f.frames).toEqual([{ type: 'agent_retarget', agentId: 'h-a', clearGrid: true }])
+ expect(f.posts).toEqual([expect.objectContaining({ ok: true })])
})
it('says why a move was refused, in words its owner can act on', async () => {
diff --git a/cli/src/superTabs/buddyModel.ts b/cli/src/superTabs/buddyModel.ts
index 233628deb..1c08da5ac 100644
--- a/cli/src/superTabs/buddyModel.ts
+++ b/cli/src/superTabs/buddyModel.ts
@@ -22,14 +22,23 @@ export const FRESH_SHARE = 0.8
const MOVE_TIMEOUT_MS = 120_000
/** How soon a request that waits (a Buddy sent home mid-turn) or a report that failed is tried again. */
const RETRY_MS = 15_000
+/** How long the Swarm keeps a request before dropping it unanswered (backend superTabs/buddyModel.ts BUDDY_MODEL_LEASE_MS). */
+const LEASE_MS = 10 * 60_000
+/** A thread session the request moves (task #3810), by harness id, at most: the Swarm's own limit on what it records. */
+const MAX_STAYED = 64
-interface ModelRequest { id: string; gridModel: string | null; gridName?: string; name?: string; servedBy?: string[]; contextWindow?: number; reason?: string }
+interface ModelRequest { id: string; gridModel: string | null; gridName?: string; name?: string; servedBy?: string[]; contextWindow?: number; reason?: string
+ /** When the Swarm asked, in ms: a busy thread session is waited for only within the request's lease. */
+ at?: number
+ /** Only the thread sessions move: the Buddy is already there (backend superTabs/buddyModel.ts, task #3810). */
+ sessionsOnly?: true }
/** A Buddy agent's row as this machine's host reads it (backend read/hostRows.ts). */
export interface BuddyModelRow {
tabId: string
agent: { id: string; harnessId: string; buddyOf?: unknown; buddySession?: unknown; modelRequest?: unknown }
}
-interface Outcome { ok: boolean; fresh?: true; error?: string }
+/** `stayed`: the thread sessions that could not move, by harness id, so the Swarm records them where they still run (#3810). */
+interface Outcome { ok: boolean; fresh?: true; error?: string; stayed?: string[] }
export interface BuddyModelDeps {
dataDir: string
now: () => number
@@ -49,7 +58,9 @@ function requestOf(value: unknown): ModelRequest | null {
...(typeof r.name === 'string' ? { name: r.name } : {}),
...(Array.isArray(r.servedBy) ? { servedBy: r.servedBy.filter((s): s is string => typeof s === 'string') } : {}),
...(typeof r.contextWindow === 'number' && r.contextWindow > 0 ? { contextWindow: r.contextWindow } : {}),
- ...(typeof r.reason === 'string' ? { reason: r.reason } : {}) }
+ ...(typeof r.reason === 'string' ? { reason: r.reason } : {}),
+ ...(typeof r.at === 'string' && Number.isFinite(Date.parse(r.at)) ? { at: Date.parse(r.at) } : {}),
+ ...(r.sessionsOnly === true ? { sessionsOnly: true as const } : {}) }
}
/** Why a move was refused, in words its owner can act on: never the daemon's detail, which can name paths on this machine.
@@ -71,6 +82,8 @@ export class BuddyModelRequests {
/** Requests reported, or settled elsewhere: never carried out again by this process. */
private readonly done = new Set<string>()
private readonly waiting = new Map<string, { busy: boolean; retryAt: number }>()
+ /** What a request that waits has already moved, so a retry never moves the Buddy twice (task #3810). */
+ private readonly progress = new Map<string, { moved: Set<string>; fresh: boolean; since: number }>()
constructor(private readonly deps: BuddyModelDeps) {}
/** One poll of a main Buddy row of this machine, with its thread sessions' rows. */
@@ -84,9 +97,10 @@ export class BuddyModelRequests {
const recorded = this.recorded(row.agent.id)
let outcome = recorded?.requestId === request.id ? recorded.outcome : undefined
if (!outcome) {
- const carried = await this.carryOut(row, sessions, request)
+ const carried = await this.carryOut(row, sessions, request, now)
if (carried === 'wait') { this.waiting.set(request.id, { busy: false, retryAt: now + RETRY_MS }); return }
outcome = carried
+ this.progress.delete(request.id)
this.record(row.agent.id, { requestId: request.id, outcome })
}
try {
@@ -104,7 +118,9 @@ export class BuddyModelRequests {
}
}
- private async carryOut(row: BuddyModelRow, sessions: readonly BuddyModelRow[], request: ModelRequest): Promise<Outcome | 'wait'> {
+ private async carryOut(row: BuddyModelRow, sessions: readonly BuddyModelRow[], request: ModelRequest, now: number): Promise<Outcome | 'wait'> {
+ const progress = this.progress.get(request.id) ?? { moved: new Set<string>(), fresh: false, since: now }
+ this.progress.set(request.id, progress)
const daemon = await this.deps.open()
try {
const move = async (harnessId: string): Promise<{ error?: string; detail?: string; fresh: boolean }> => {
@@ -115,20 +131,35 @@ export class BuddyModelRequests {
return { ...(typeof reply.error === 'string' ? { error: reply.error } : {}),
...(typeof reply.detail === 'string' ? { detail: reply.detail } : {}), fresh }
}
- const moved = await move(row.agent.harnessId)
- if (moved.error) {
- // Sent home by the Swarm (a limit, a model gone) while it answers: moved once the turn ends, within the request's lease.
- if (moved.error === 'AGENT_BUSY' && request.reason) return 'wait'
- return { ok: false, error: refusal(moved.error, request, moved.detail) }
+ if (!request.sessionsOnly && !progress.moved.has(row.agent.harnessId)) {
+ const moved = await move(row.agent.harnessId)
+ if (moved.error) {
+ // Sent home by the Swarm (a limit, a model gone) while it answers: moved once the turn ends, within the request's lease.
+ if (moved.error === 'AGENT_BUSY' && request.reason) return 'wait'
+ return { ok: false, error: refusal(moved.error, request, moved.detail) }
+ }
+ progress.moved.add(row.agent.harnessId)
+ progress.fresh = moved.fresh
}
- const stayed: string[] = []
+ // A thread session that is answering never holds up the Buddy's own result: it is reported as stayed, and the Swarm records
+ // the Buddy where it now runs at once (Linux test of #3393). The sessions-only follow-up the Swarm then asks for waits
+ // for its turn to end, until shortly before the Swarm drops the request; then it is reported as stayed again (#3810).
+ const deadline = (request.at ?? progress.since) + LEASE_MS - 2 * RETRY_MS
+ const stayed: Array<{ harnessId: string; why: string }> = []
+ let busy = false
for (const session of sessions) {
- const result = await move(session.agent.harnessId)
- if (result.error) stayed.push(result.error === 'AGENT_BUSY' ? 'it was answering' : refusal(result.error, request, result.detail))
+ const harnessId = session.agent.harnessId
+ if (progress.moved.has(harnessId)) continue
+ const result = await move(harnessId)
+ if (!result.error) { progress.moved.add(harnessId); continue }
+ if (result.error === 'AGENT_BUSY' && request.sessionsOnly && now < deadline) { busy = true; continue }
+ stayed.push({ harnessId, why: result.error === 'AGENT_BUSY' ? 'it was answering' : refusal(result.error, request, result.detail) })
}
- return { ok: true, ...(moved.fresh ? { fresh: true as const } : {}),
- ...(stayed.length === 1 ? { error: `A thread session stayed where it was: ${stayed[0]}` }
- : stayed.length ? { error: `${stayed.length} thread sessions stayed where they were: ${stayed[0]}` } : {}) }
+ if (busy) return 'wait'
+ return { ok: true, ...(progress.fresh ? { fresh: true as const } : {}),
+ ...(stayed.length ? { stayed: stayed.slice(0, MAX_STAYED).map(s => s.harnessId) } : {}),
+ ...(stayed.length === 1 ? { error: `A thread session stayed where it was: ${stayed[0]!.why}` }
+ : stayed.length ? { error: `${stayed.length} thread sessions stayed where they were: ${stayed[0]!.why}` } : {}) }
} finally { daemon.close() }
}
@@ -151,8 +182,9 @@ export class BuddyModelRequests {
try {
const row = object(JSON.parse(readPrivateStateFile(file, 4_096))), outcome = object(row.outcome)
if (!identifier(row.requestId) || typeof outcome.ok !== 'boolean') return null
+ const stayed = Array.isArray(outcome.stayed) ? outcome.stayed.filter(identifier).slice(0, MAX_STAYED) : []
return { requestId: row.requestId, outcome: { ok: outcome.ok, ...(outcome.fresh === true ? { fresh: true } : {}),
- ...(typeof outcome.error === 'string' ? { error: outcome.error.slice(0, 300) } : {}) } }
+ ...(typeof outcome.error === 'string' ? { error: outcome.error.slice(0, 300) } : {}), ...(stayed.length ? { stayed } : {}) } }
} catch { return null }
}
private record(agentId: string, value: { requestId: string; outcome: Outcome }): void {
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index 6bef67e19..ec5e12c2d 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -789,7 +789,11 @@ describe('Super Tab native delivery handoff', () => {
})
}
await host.reconcileReceipts()
- for (let i = 0; i < 400; i++) { t.wait(5 * 60_000); await host.reconcileReceipts() }
+ // Backoff cadence is checked above. Jump across the deadline instead of doing 400 disk-backed journal retries,
+ // which timed out under concurrent affected checks on the Team Mac (#3845).
+ t.wait(23 * 60 * 60_000); await host.reconcileReceipts()
+ expect(t.saved().entries.delivery.stage).toBe('delivered')
+ t.wait(60 * 60_000); await host.reconcileReceipts()
expect(t.saved().entries).toEqual({})
expect(t.log).toHaveBeenCalledWith(expect.stringContaining(`Gave up acknowledging delivery delivery to agent agent in Swarm tab after a day: ${dropped ?? 'The Swarm is busy.'}`))
expect(vi.mocked(t.log).mock.calls.filter(([line]) => String(line).startsWith('Gave up'))).toHaveLength(1)
@@ -997,6 +1001,22 @@ describe('Super Tab native delivery handoff', () => {
expect(prompt).toContain('In task #12 "Fix login" (conversation g12).\nYou are assigned task #12 "Fix login" (working).\n')
expect(prompt.indexOf('You are assigned')).toBeLessThan(prompt.indexOf('Message message from'))
})
+ // Task #3747 (anh Dee, 11-06: "i don't know which one you reply to which"): in a project that answers people in threads,
+ // a person's message is answered in its thread, and the rules say so; an agent's, and other projects', as before.
+ it('says --reply-to for a person\'s main-chat message in a project that answers in threads', async () => {
+ const THREADED = { ...SWARM, projects: [{ ...SWARM.projects[0], answersInThread: true }] }
+ const person = { kind: 'person', id: 'p1', name: 'Dee' }
+ const line = (prompt: string) => prompt.split('\n').find(l => l.startsWith('Reply there: '))!
+ const threaded = await delivered(wired({ author: person, text: 'Is login fixed?', thread: 'message' }, {}, () => THREADED).t)
+ expect(line(threaded)).toMatch(/ --reply-to 'message'$/)
+ expect(threaded).toContain('Answer every person\'s message in its own thread (--reply-to)')
+ expect(threaded).not.toContain('answered right below it (--answers)')
+ const agent = await delivered(wired({ author: { kind: 'agent', id: 'a0000000000000000000000b', name: 'Birch' }, text: 'Which branch is it on?', thread: 'message' }, {}, () => THREADED).t)
+ expect(line(agent)).toMatch(/ --answers 'message' --to 'a0000000000000000000000b'$/)
+ const plain = await delivered(wired({ author: person, text: 'Is login fixed?', thread: 'message' }).t)
+ expect(line(plain)).toMatch(/ --answers 'message'$/)
+ expect(plain).toContain('A message in the main chat is answered right below it (--answers)')
+ })
// Task #3057 (Ken, 11-05): the reply line carried --to <sender>, and agents copied --to the PM into their own task, so
// 29 of 55 acknowledgements still reached it. In its own task or step a coordinator's message gets the plain form.
describe('the reply line to the coordinator in the reader\'s own task (#3057)', () => {
diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.ts
index ef17015e2..49e54dc50 100644
--- a/cli/src/superTabs/host.ts
+++ b/cli/src/superTabs/host.ts
@@ -502,6 +502,20 @@ const SUPER_TAB_REPLY_STYLE = 'Write to the people in this tab like a helpful co
+ 'If you have already answered a message, do not post again. '
+ 'When you hand over finished work, give the result with the revision and links they need.'
+/** The same rules in a project that answers people in threads (task #3747, anh Dee 11-06: "i don't know which one you reply to
+ * which"): every person's message is answered in its thread. */
+const SUPER_TAB_REPLY_STYLE_THREADED = SUPER_TAB_REPLY_STYLE.replace(
+ 'A message in the main chat is answered right below it (--answers); one in a thread, inside its thread (--reply-to). Open a thread only for a back-and-forth on one topic, or to answer something far up the chat. ',
+ 'Answer every person\'s message in its own thread (--reply-to), never as a new line in the main chat; the main chat is only for news the whole team needs. ')
+
+/** Whether [groupId]'s project answers people in threads (backend projects.ts answersInThread). A group from before projects is
+ * in the first. */
+export function answersInThread(state: Record<string, unknown>, groupId: string): boolean {
+ const group = (Array.isArray(state.conversations) ? state.conversations.map(object) : []).find(c => c.id === groupId)
+ const project = group && (Array.isArray(state.projects) ? state.projects.map(object) : []).find(p => p.id === (group.projectId ?? 'lead'))
+ return project?.answersInThread === true
+}
+
/** Owns only the handoff between a durable backend claim and the core's native input.
* A process restart never interprets a lost acknowledgement as permission to type twice. */
export class SuperTabHost {
@@ -546,6 +560,8 @@ export class SuperTabHost {
private readonly contexts = new Map<string, string>()
/** Deliveries whose message is the coordinator's in the reader's own task or step, with no question to answer (#3057). */
private readonly plainReplies = new Set<string>()
+ /** Deliveries of a person's message in a project that answers in threads (task #3747): answered with --reply-to. */
+ private readonly threadAnswers = new Set<string>()
/** The tasks and steps where a coordinator's delivery carried their state (#3114), by Swarm, agent and conversation: a later
* one there reads its latest messages beside the Swarm read, not after it (review 1, AGENTS.md standard 4). The
* newest KNOWN_TASKS_MAX. */
@@ -1442,7 +1458,7 @@ export class SuperTabHost {
for (const deliveryId of this.files.keys()) if (!this.journal.entries[deliveryId]) this.files.delete(deliveryId)
for (const deliveryId of [...this.downloads.keys()]) if (!this.journal.entries[deliveryId]) this.dropDownload(deliveryId)
for (const deliveryId of this.quotes.keys()) if (!this.journal.entries[deliveryId]) this.quotes.delete(deliveryId)
- for (const deliveryId of this.contexts.keys()) if (!this.journal.entries[deliveryId]) { this.contexts.delete(deliveryId); this.plainReplies.delete(deliveryId) }
+ for (const deliveryId of this.contexts.keys()) if (!this.journal.entries[deliveryId]) { this.contexts.delete(deliveryId); this.plainReplies.delete(deliveryId); this.threadAnswers.delete(deliveryId) }
for (const deliveryId of this.replyPages.keys()) if (!this.journal.entries[deliveryId]) this.replyPages.delete(deliveryId)
for (const entry of Object.values(this.journal.entries)) {
const id = typedId(entry)
@@ -2548,6 +2564,7 @@ export class SuperTabHost {
const author = object(message.author)
if (author.kind === 'agent' && identifier(author.id) && !asksQuestion(message.text)
&& coordinatorInOwnTask(state, group, author.id, entry.agentId)) this.plainReplies.add(entry.deliveryId)
+ if (author.kind === 'person' && answersInThread(state, group)) this.threadAnswers.add(entry.deliveryId)
lines.push(placeLine(state, group))
// "Release urgent" in #3022 reached the PM with its place alone, while its pull request had passed review with CI green,
// and the PM answered about something else: its state, and what was said just before, come with it.
@@ -2647,7 +2664,9 @@ export class SuperTabHost {
const author = object(message.author)
const to = author.kind === 'agent' && identifier(author.id) ? ` --to ${shellQuote(author.id)}` : ''
// A thread reply is answered in its thread, and a Buddy session's thread stays its own; any other message right below it.
- const threaded = (identifier(message.thread) && message.thread !== message.id) || message.buddySession === true
+ // In a project that answers people in threads, a person's message too (task #3747); the server threads an --answers there anyway.
+ const threadAnswer = this.threadAnswers.has(entry.deliveryId)
+ const threaded = (identifier(message.thread) && message.thread !== message.id) || message.buddySession === true || threadAnswer
// Task #3057 (Ken, 11-05): 29 of 55 agent posts to the PM still did not name it, mostly an assignee writing in its own task,
// because this line carried --to <sender> and the PM sends the briefs. The coordinator's message in the reader's own task or
// step, with no question, shows the plain form: in a task it reaches no agent, and the people see it. To acknowledge, react.
@@ -2660,7 +2679,7 @@ export class SuperTabHost {
+ `Read its state: ${command} status\nRead this conversation: ${command} messages ${shellQuote(group)}\n`
+ replyLine
+ `Manage agreed work and delegation: ${command} help.\n`
- + `Ask questions and post results in this conversation. ${SUPER_TAB_REPLY_STYLE} Replies to these delivered instructions must be posted here explicitly.\n\n`
+ + `Ask questions and post results in this conversation. ${threadAnswer ? SUPER_TAB_REPLY_STYLE_THREADED : SUPER_TAB_REPLY_STYLE} Replies to these delivered instructions must be posted here explicitly.\n\n`
+ context + native + reply + said
}
diff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.ts
index 0ff91653e..a4c39c8a8 100644
--- a/cli/src/superTabs/machines.spec.ts
+++ b/cli/src/superTabs/machines.spec.ts
@@ -64,6 +64,69 @@ function fixture(env: NodeJS.ProcessEnv = {}, privacy: () => PrivacyObservation
stamp: (next: string) => { stamp = next } }
}
+// Ken's 2026-11-06 scan: a stale failed-start report was refused 581 times, even after CLI updates.
+describe('a failed-start report', () => {
+ function reporting(refuse: () => void) {
+ const f = fixture(), original = f.backend.getMockImplementation()!
+ let elapsed = 0
+ const attempts: Array<{ at: number; body: unknown }> = []
+ f.prepare.mockRejectedValue(new Error('Could not prepare the checkout.'))
+ f.backend.mockImplementation(async (core, method, path, body) => {
+ if (method === 'POST' && (body as { command?: { type?: string } })?.command?.type === 'agent.startFailed') {
+ attempts.push({ at: elapsed, body: structuredClone(body) })
+ refuse()
+ return { result: {} }
+ }
+ return original(core, method, path, body)
+ })
+ return { f, attempts, pass: async (ms = 0) => { elapsed += ms; f.step(ms); await f.machine.tick() } }
+ }
+
+ it('drops NOT_FOUND once without relaunching or logging server text, and leaves other starts free', async () => {
+ const h = reporting(() => { throw new SuperTabHostError('NOT_FOUND', 'fixture-secret-server-text', 404) })
+ await h.pass()
+ for (let i = 0; i < 10; i++) await h.pass(15_000)
+ expect(h.attempts).toHaveLength(1)
+ expect(h.f.prepare).toHaveBeenCalledTimes(1)
+ const lines = h.f.log.mock.calls.flat().join('\n')
+ expect(lines).not.toContain('fixture-secret-server-text')
+ expect(lines.match(/no longer has this start/g)).toHaveLength(1)
+ h.f.pool.starts.push({ id: 'another', dispatched: false })
+ h.f.prepare.mockResolvedValue(undefined)
+ await h.pass(15_000)
+ expect(h.f.start).toHaveBeenCalledTimes(1)
+ expect((h.f.start.mock.calls as unknown[][])[0]![0]).toMatchObject({ startId: 'another' })
+ expect(h.attempts).toHaveLength(1)
+ })
+
+ it.each([
+ ['a lost reply', () => { throw new Error('fixture-secret-transport') }],
+ ['a server failure', () => { throw new SuperTabHostError('BACKEND_UNAVAILABLE', 'fixture-secret-server', 503) }],
+ ['another refusal', () => { throw new SuperTabHostError('CONFLICT', 'fixture-secret-refusal', 409) }],
+ ])('backs off with a five-minute cap after %s and retains the original report', async (_name, refuse) => {
+ const h = reporting(refuse)
+ await h.pass()
+ for (let i = 0; i < 72; i++) await h.pass(15_000)
+ expect(h.attempts.map(a => a.at)).toEqual([0, 15_000, 45_000, 105_000, 225_000, 465_000, 765_000, 1_065_000])
+ expect(h.attempts.every(a => JSON.stringify(a.body) === JSON.stringify(h.attempts[0]!.body))).toBe(true)
+ expect(h.f.prepare).toHaveBeenCalledTimes(1)
+ expect(h.f.start).not.toHaveBeenCalled()
+ expect(h.f.log.mock.calls.flat().join('\n')).not.toContain('fixture-secret')
+ })
+
+ it('reports a real failure once, including when a retry recovers', async () => {
+ for (const failFirst of [false, true]) {
+ let fail = failFirst
+ const h = reporting(() => { if (fail) { fail = false; throw new Error('lost reply') } })
+ await h.pass()
+ for (let i = 0; i < 5; i++) await h.pass(15_000)
+ expect(h.attempts).toHaveLength(failFirst ? 2 : 1)
+ expect(h.attempts[0]!.body).toEqual({ operationId: 'prepare-failed-start', command: { type: 'agent.startFailed', startId: 'start', error: 'Could not prepare the checkout.' } })
+ expect(h.f.prepare).toHaveBeenCalledTimes(1)
+ }
+ })
+})
+
// Second review of #1991: a start in a Swarm this host is cleaning up could write into a folder the cleanup then deleted.
describe('a Swarm this host is cleaning up', () => {
const homes: string[] = []
@@ -410,12 +473,12 @@ describe('contributed machine executor', () => {
const withEngines = (f: ReturnType<typeof fixture>) => {
const usage = f.request.getMockImplementation()!
f.request.mockImplementation(async (type, ...rest) => type === 'engines_probe'
- ? { engines: [{ engine: 'claude', installed: true, signedIn: false }, { engine: 'codex', installed: true }, { engine: 'cursor', installed: true }] }
+ ? { engines: [{ engine: 'claude', installed: true, signedIn: false }, { engine: 'codex', installed: true }] }
: usage(type, ...rest as []))
}
const probes = (f: ReturnType<typeof fixture>) => f.request.mock.calls.filter(c => c[0] === 'engines_probe')
- it('says whether each engine is installed and signed in, probing again only after ten minutes', async () => {
+ it('probes only engines with account readers periodically, and repeats only after ten minutes', async () => {
const f = fixture()
withEngines(f)
await f.machine.tick()
@@ -430,6 +493,25 @@ describe('contributed machine executor', () => {
expect(probes(f)).toHaveLength(2)
})
+ it.each([true, false, null])('reports another installed engine account as %s, without copying secrets or unknown engine names', async signedIn => {
+ const f = fixture()
+ const usage = f.request.getMockImplementation()!
+ f.request.mockImplementation(async (type, ...rest) => type === 'engines_probe'
+ ? { engines: [
+ { engine: 'cursor', installed: true, signedIn, token: 'test-secret' },
+ { engine: 'hermes', installed: false, signedIn: true },
+ { engine: 'copilot', installed: true, signedIn: 'test-secret' },
+ { engine: 'terminal', installed: true, signedIn: true },
+ { engine: 'invented', installed: true, signedIn: true },
+ ] } : usage(type, ...rest as []))
+ await f.machine.tick()
+ expect(readings(f)[0]!.readiness?.engines).toEqual([
+ { engine: 'cursor', installed: true, signedIn },
+ { engine: 'hermes', installed: null, signedIn: null },
+ { engine: 'copilot', installed: true, signedIn: null },
+ ])
+ })
+
it('reads an engine the probe calls not installed as unknown, since a timed-out shell probe says the same (review of #1743)', async () => {
const f = fixture()
const usage = f.request.getMockImplementation()!
diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.ts
index c85cdec4e..6c4e73406 100644
--- a/cli/src/superTabs/machines.ts
+++ b/cli/src/superTabs/machines.ts
@@ -1,4 +1,5 @@
import { createHash } from 'node:crypto'
+import { PROCESS_ENGINES } from '../engines/types.js'
import { spawn } from 'node:child_process'
import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'
import { homedir } from 'node:os'
@@ -211,6 +212,9 @@ export class ContributedMachines {
/** A pass or one of its publishes failed: the next one waits a whole beat, as every pass once did. */
private failed = false
private readonly cursors = new Map<string, number>()
+ /** A stale host feed kept reporting a missing failed start 581 times (Ken, 2026-11-06). Keep its one report until the feed
+ * drops the start: terminal after acceptance/NOT_FOUND, otherwise retry its original receipt without launching again. */
+ private readonly failureReports = new Map<string, { path: string; input: Record<string, unknown>; failures: number; nextAt: number; done: boolean }>()
private repairTrust?: ReturnType<typeof createSwarmCloneTrustRepair>
/** Per tab, when its observation was last sent and what it said that matters to a reader: the harnesses
* running and stopped, whether new work is paused, and which starts are waiting. A change in any of them is
@@ -306,12 +310,14 @@ export class ContributedMachines {
}
/** The engines' own installs and sign-ins, probed again once [READINESS_MS] old. */
private async ownEngines(local: { request: (type: string, payload: Record<string, unknown>, timeoutMs: number) => Promise<unknown> }, now: number): Promise<ReadyEngine[] | null> {
+ // Periodic work asks only engines with account readers. Add a vendor here when its reader lands;
+ // unsupported engines would spawn login shells just to return unknown (#3839 security review).
const answer = await local.request('engines_probe', { engines: ['claude', 'codex'], accounts: true }, 20_000).catch(() => null)
const engines = object(answer).engines
// An engine that says nothing of its sign-in (an older daemon, an engine not installed) is unknown, never signed out.
// Not installed is unknown too: the probe answers the same for a login shell that timed out (lib/engineProbe.ts), and
// such a machine fails its first start loudly instead (review of #1743).
- const value = Array.isArray(engines) ? list(engines).filter(e => e.engine === 'claude' || e.engine === 'codex')
+ const value = Array.isArray(engines) ? list(engines).filter(e => (PROCESS_ENGINES as readonly unknown[]).includes(e.engine))
.map((e): ReadyEngine => ({ engine: String(e.engine), installed: e.installed === true ? true : null,
signedIn: e.installed === true && typeof e.signedIn === 'boolean' ? e.signedIn : null })) : null
this.engineRead = { value, until: now + (value ? READINESS_MS : READINESS_RETRY_MS) }
@@ -422,6 +428,29 @@ export class ContributedMachines {
this.waiting.set(startId, reason)
this.log(`Swarm start ${startId} is waiting: ${reason}`)
}
+ private async reportStartFailure(startId: string, path: string, input: Record<string, unknown>): Promise<void> {
+ let report = this.failureReports.get(startId)
+ if (!report) {
+ report = { path, input: { operationId: input.operationId, command: input.command }, failures: 0, nextAt: 0, done: false }
+ this.failureReports.set(startId, report)
+ }
+ if (report.done || this.deps.now() < report.nextAt) return
+ try {
+ await this.deps.backend(this.core, 'POST', report.path, report.input)
+ report.done = true
+ if (report.failures) this.log(`Swarm start ${startId}: its failed-start report reached the server.`)
+ } catch (error) {
+ if (error instanceof SuperTabHostError && error.code === 'NOT_FOUND') {
+ report.done = true
+ this.log(`Swarm start ${startId}: the server no longer has this start; dropped its failed-start report.`)
+ return
+ }
+ // Error bodies may contain private server text; only the report's state belongs in this log.
+ if (!report.failures) this.log(`Swarm start ${startId}: could not report its failure; retrying with backoff capped at five minutes.`)
+ report.failures = Math.min(report.failures + 1, 6)
+ report.nextAt = this.deps.now() + Math.min(15_000 * 2 ** (report.failures - 1), 300_000)
+ }
+ }
/** Diego's Mac, 2026-10-28: 410 reading timeouts in two days, none of them in the log. */
private noteReading(tabId: string, error: unknown) {
const was = this.readingFailures.get(tabId)
@@ -493,8 +522,9 @@ export class ContributedMachines {
private async poll(began: number) {
const where = { dataDir: this.core.dataDir, port: this.core.daemon.port, machineId: this.machineId }
const pools = list((await this.sources.feed.current(POOLS_FRESH_MS)).pools).filter(row => identifier(row.tabId) && object(row.machine).machineId === this.machineId && identifier(object(row.machine).generation))
- if (this.stopped || pools.length === 0) { this.published.clear(); this.lastSent.clear(); this.waiting.clear(); this.readingFailures.clear(); return }
+ if (this.stopped || pools.length === 0) { this.published.clear(); this.lastSent.clear(); this.waiting.clear(); this.readingFailures.clear(); this.failureReports.clear(); return }
const pendingIds = new Set(pools.flatMap(row => startsOf(row).map(start => start.id)))
+ for (const id of this.failureReports.keys()) if (!pendingIds.has(id)) this.failureReports.delete(id)
for (const id of this.waiting.keys()) if (!pendingIds.has(id)) this.waiting.delete(id)
for (const id of this.refusedSince.keys()) if (!pendingIds.has(id)) this.refusedSince.delete(id)
for (const id of this.preparing) if (!pendingIds.has(id)) this.preparing.delete(id)
@@ -691,17 +721,30 @@ export class ContributedMachines {
const round = pending.length ? [...pending.slice(cursor % pending.length), ...pending.slice(0, cursor % pending.length)].slice(0, 2) : []
for (const start of round) {
if (this.stopped) return
- if (!identifier(start.id) || ((row.paused || pool.paused) && !start.dispatched)) continue
+ if (!identifier(start.id)) continue
+ const report = this.failureReports.get(start.id)
+ if (report) {
+ await this.reportStartFailure(start.id, report.path, report.input)
+ // A dispatched receipt may already own a native session: retain its existing reconciliation/abandoned cleanup.
+ if (!report.done || !start.dispatched) continue
+ }
+ if ((row.paused || pool.paused) && !start.dispatched) continue
if (this.cleaningTabs.has(String(row.tabId))) { this.noteWaiting(start.id, CLEANING_WAIT); continue }
const launched = this.startInFlight(String(row.tabId))
try {
const path = `/api/super-tabs/hosts/${this.machineId}/starts/${row.tabId}/${start.id}`
// The start endpoint reads this start and takes its commands, nothing else. Any other read went out as an empty
// command, which the backend refused with a 400 at every start (prod logs 2026-10-28).
- const scoped: ScopedRequest = async input => input.action !== 'startStatus' && input.action !== 'command'
- ? { error: 'HOST_UNSUPPORTED', detail: 'A contributed machine reads only its own starts.' }
- : { ok: true, value: await this.deps.backend(this.core, input.action === 'startStatus' ? 'GET' : 'POST', path,
+ const scoped: ScopedRequest = async input => {
+ if (input.action !== 'startStatus' && input.action !== 'command') return { error: 'HOST_UNSUPPORTED', detail: 'A contributed machine reads only its own starts.' }
+ if (input.action === 'command' && object(input.command).type === 'agent.startFailed') {
+ await this.reportStartFailure(String(start.id), path, input)
+ // The host owns this queued report now; the launch path can finish its existing cleanup.
+ return { ok: true, value: {} }
+ }
+ return { ok: true, value: await this.deps.backend(this.core, input.action === 'startStatus' ? 'GET' : 'POST', path,
input.action === 'startStatus' ? undefined : { operationId: input.operationId, command: input.command }) }
+ }
try {
// The Harness Team account is not private (its owner's home folder opened again, say): a new start is refused
// here as well as by routing, and never moved to the owner's account instead.
diff --git a/cli/src/superTabs/shellGuard.spec.ts b/cli/src/superTabs/shellGuard.spec.ts
index 2aff205d5..1a24d4efd 100644
--- a/cli/src/superTabs/shellGuard.spec.ts
+++ b/cli/src/superTabs/shellGuard.spec.ts
@@ -55,13 +55,19 @@ describe('shell guard: kill by name', () => {
describe('shell guard: kill -1, every process the account can reach', () => {
it.each([
+ 'kill -1',
+ 'kill -4242',
+ 'kill -- -4242',
+ 'kill -TERM -4242',
+ 'kill -s TERM -4242',
+ 'kill -n 9 -4242',
+ 'kill -- 0',
'kill -9 -1',
'kill -- -1',
'kill -KILL -1',
'kill -s TERM -1',
'/bin/kill -1 -1',
'kill 4242 -1',
- 'kill -1',
'/bin/kill -9 -1 ; true',
])('refuses %s', (command) => {
expect(refused(command)).toBe(GUARD_REASONS.killAll)
@@ -69,7 +75,6 @@ describe('shell guard: kill -1, every process the account can reach', () => {
it.each([
'kill -1 4242',
- 'kill -- -4242',
'kill -l',
])('lets %s through', (command) => {
expect(refused(command)).toBeNull()
@@ -145,6 +150,29 @@ describe('shell guard: heredocs', () => {
})
})
+describe('shell guard: temporary paths in simple variables', () => {
+ it.each([
+ 'OUT=/tmp; echo hi > "$OUT/shared.txt"',
+ 'OUT=/tmp; cat ${OUT}/shared.txt',
+ 'OUT=/private; OUT="$OUT/tmp"; touch "$OUT/shared.txt"',
+ 'OUT=/tmp; NEXT=$OUT; curl -o "$NEXT/shared.txt" https://example.com',
+ 'export OUT=/tmp; tee "$OUT/shared.txt"',
+ "bash -c 'OUT=/tmp; echo hi > \"$OUT/shared.txt\"'",
+ ])('refuses %s', command => {
+ expect(refused(command)).toBe(GUARD_REASONS.fixedTmp)
+ })
+
+ it.each([
+ 'OUT=/work; echo hi > "$OUT/shared.txt"',
+ 'OUT=/tmp; OUT=/work; echo hi > "$OUT/shared.txt"',
+ "OUT=/tmp; echo '$OUT/shared.txt'",
+ "OUT=/tmp; echo \\$OUT/shared.txt",
+ 'OUT=$(mktemp -d); echo hi > "$OUT/shared.txt"',
+ ])('allows %s', command => {
+ expect(refused(command)).toBeNull()
+ })
+})
+
describe('shell guard: fixed names in /tmp', () => {
it.each([
'echo hi > /tmp/out.txt',
diff --git a/cli/src/superTabs/shellGuard.ts b/cli/src/superTabs/shellGuard.ts
index 0663a1fb3..aab5278fd 100644
--- a/cli/src/superTabs/shellGuard.ts
+++ b/cli/src/superTabs/shellGuard.ts
@@ -22,7 +22,7 @@ const PREFIX = 'Harness shell guard:'
export const GUARD_REASONS = {
killByName: `${PREFIX} stop only processes you started, by the process id you recorded; never by name or pattern `
+ '(pkill, killall, kill $(pgrep …), taskkill /IM).',
- killAll: `${PREFIX} kill -1 signals every process this account can reach, every other agent's work on a shared machine; `
+ killAll: `${PREFIX} nonpositive kill targets can signal other agents' process groups or every process this account can reach; `
+ 'stop only processes you started, by the process id you recorded.',
systemWide: `${PREFIX} no sudo and no system-wide installs on a shared machine; put the tools you need in your session folder.`,
fixedTmp: `${PREFIX} a fixed name in /tmp can be read or planted by every account; make a folder with `
@@ -158,6 +158,7 @@ function programWords(words: string[]): string[] {
*/
function split(text: string, nested: string[]): Simple[] {
const out: Simple[] = []
+ const variables = new Map<string, string>()
let words: string[] = [], targets: string[] = []
let word = '', inWord = false, redirect = false
const heredocs: { delimiter: string; strip: boolean }[] = []
@@ -167,7 +168,15 @@ function split(text: string, nested: string[]): Simple[] {
if (!inWord) return
if (pendingHeredoc) { heredocs.push({ delimiter: word, strip: pendingHeredoc.strip }); pendingHeredoc = null }
else if (redirect) { targets.push(word); redirect = false }
- else words.push(word)
+ else {
+ // Only leading shell assignments and export declarations set values; an echo argument never does.
+ const assignment = word.includes('=') && /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s.exec(word)
+ if (assignment && words.every((value) => value === 'export' || /^[A-Za-z_][A-Za-z0-9_]*=/.test(value))) {
+ if (/[$`]/.test(assignment[2])) variables.delete(assignment[1])
+ else variables.set(assignment[1], assignment[2])
+ }
+ words.push(word)
+ }
word = ''; inWord = false
}
const endCommand = () => {
@@ -176,6 +185,15 @@ function split(text: string, nested: string[]): Simple[] {
words = []; targets = []; redirect = false
}
+ // Expand at the lexical position, so single quotes and escaped dollars remain literal and reassignments keep order.
+ const variableAt = (at: number): { value: string; end: number } | null => {
+ if (text[at] !== '$') return null
+ const match = /^\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/.exec(text.slice(at))
+ if (!match) return null
+ const value = variables.get(match[1] ?? match[2])
+ return value === undefined ? null : { value, end: at + match[0].length }
+ }
+
let i = 0
while (i < text.length) {
const c = text[i]
@@ -211,11 +229,15 @@ function split(text: string, nested: string[]): Simple[] {
if (text[i] === '\\' && '"\\$`\n'.includes(text[i + 1] ?? '')) { word += text[i + 1]; i += 2; continue }
const sub = substitution(text, i)
if (sub) { nested.push(sub.inner); word += text.slice(i, sub.end); i = sub.end; continue }
+ const variable = text[i] === '$' && variables.size ? variableAt(i) : null
+ if (variable) { word += variable.value; i = variable.end; continue }
word += text[i]; i++
}
i++
continue
}
+ const variable = text[i] === '$' && variables.size ? variableAt(i) : null
+ if (variable) { word += variable.value; inWord = true; i = variable.end; continue }
const sub = substitution(text, i)
if (sub) { nested.push(sub.inner); word += text.slice(i, sub.end); inWord = true; i = sub.end; continue }
if ((c === '<' || c === '>') && text[i + 1] === '(') {
@@ -358,22 +380,18 @@ function killsByName(commands: Simple[]): boolean {
return kills && looksUp
}
-/**
- * `kill … -1`: a target of -1 signals every process the account may signal (POSIX kill(2)), on a shared Team account every
- * other agent's work (Rowan's security review, 11-06). The first word after `kill` that starts with `-` is the signal
- * (`kill -1 4242` sends SIGHUP to 4242), unless it is `--`; every word after it is a target. A negative group id other than
- * -1 is a process group the agent started, by its id, and passes.
- */
+/** Negative and zero targets reach process groups or the whole account, not a single recorded process.
+ * A bare negative argument is refused even where a shell interprets it as a signal with a missing target. */
function killsAll({ words }: Simple): boolean {
if (programName(words[0]) !== 'kill') return false
- // A bare `kill -1` is a usage error to a shell's kill, but a kill program may take -1 as its target: never useful, so refused.
- if (words.length === 2 && words[1] === '-1') return true
let at = 1
if (words[at] === '-s' || words[at] === '-n') at += 2
else if (words[at] === '-l' || words[at] === '-L') return false
else if (words[at]?.startsWith('-') && words[at] !== '--') at += 1
if (words[at] === '--') at += 1
- return words.slice(at).includes('-1')
+ const targets = words.slice(at)
+ return (!targets.length && /^-\d+$/.test(words[1] ?? ''))
+ || targets.some((word) => /^-?\d+$/.test(word) && Number(word) <= 0)
}
const TMP_ROOTS = ['/tmp', '/private/tmp', '/var/tmp', '/private/var/tmp']
diff --git a/docs/plans/2026-11-06-answers-in-thread-plan.md b/docs/plans/2026-11-06-answers-in-thread-plan.md
new file mode 100644
index 000000000..1ca4da763
--- /dev/null
+++ b/docs/plans/2026-11-06-answers-in-thread-plan.md
@@ -0,0 +1,70 @@
+# Agents answer people in the message's thread: implementation plan
+
+> Written by the project's Engineer way of working (project instructions, Engineer): plan first, then each task test first,
+> the failing test committed before its code. No Execution Handoff.
+
+**Goal:** In a project set to answer in threads, every agent's answer to a person's message goes in that message's thread,
+so answers no longer stack in the main chat apart from their questions (task #3747, requested by Dee through Harness: "i
+don't know which one you reply to which... why don't you answer in those replies as threads?"). Other projects are unchanged.
+
+**Architecture:** A project setting, `SwarmProject.answersInThread` (projects.ts), set with a new command `project.answers`
+{ projectId, inThread } by the project's coordinator or a person who manages the project, as `project.coordinatorName` is.
+Three places follow it:
+
+1. The server (commands.ts `placeAnswer`): a `message.send` that `answers` a person's main-chat message in such a project is
+ posted as a reply in that message's thread (`replyTo`), so an older CLI's `--answers`, or an agent that ignores its reply
+ line, still lands in the thread. Owed asks keep the message's own id as their thread (pulse.ts `owe`), so the reply
+ settles it as an answer (`settleReply`), and `answer` records it.
+2. The host (cli host.ts): a person's message in such a project gets the reply line `--reply-to MESSAGE`, and its rules say to
+ answer every person's message in its thread.
+3. Reads: the project field passes through every state read (read/views.ts), so the host sees it with no new read.
+
+Main-chat posts that answer nothing (a release out, an outage) stay possible: only a post that names a person's message moves.
+
+**Tech Stack:** TypeScript backend and CLI, vitest.
+
+**Spec:** task #3747 brief.
+
+## Global Constraints
+
+- Per project; a project without the setting behaves exactly as before.
+- An agent's message is answered as before (right below it, or in its thread).
+- Swarm code stays out of cli/src/core.
+
+## Design
+
+- growth: one optional boolean on a project; nothing new grows.
+- concurrency: the command writes the project in the Swarm's usual write.
+- read cost: N/A because nothing new is read: the host reads the state it already reads per delivery.
+- scale: N/A because it is a per-project flag.
+- compatibility: an older host still writes `--answers`; the server puts it in the thread. An older server ignores nothing: the
+ command is new, so an older server refuses it as unknown, and the setting waits for the release.
+- migration + rollback: none; the flag is absent by default. Rollback leaves the flag stored and unread.
+- audience: only the coordinator or a person who manages the project sets it (the server checks).
+- identity: N/A because no new identity is used.
+- failure: a host that cannot read the state writes `--answers`, and the server still threads it.
+- platforms: backend and CLI; Desktop shows thread replies as it does.
+
+## Review Focus
+
+- Only a post answering a person's main-chat message moves; a post answering nothing stays in the main chat.
+- The moved post settles the owed ask and is recorded as the answer.
+
+## Task 1: the setting, and the server threads answers
+
+**Files:** backend/src/superTabs/projects.ts, backend/src/superTabs/commands.ts, backend/src/superTabs/answers.test.ts
+
+- [x] Test: in a project set to answer in threads, a plain `--answers` post and an `answer` on a person's main-chat message land
+ in its thread and settle it; an agent's message, a post answering nothing, and other projects behave as before; only the
+ coordinator or a manager sets it.
+- [x] Watch it fail; commit.
+- [x] Code; watch it pass; commit.
+
+## Task 2: the reply line says --reply-to
+
+**Files:** cli/src/superTabs/host.ts, cli/src/superTabs/host.spec.ts
+
+- [x] Test: in such a project a person's main-chat message gets `--reply-to MESSAGE` and the thread rule; other projects keep
+ `--answers`.
+- [x] Watch it fail; commit.
+- [x] Code; watch it pass; commit.
diff --git a/docs/plans/2026-11-06-buddy-session-stayed-plan.md b/docs/plans/2026-11-06-buddy-session-stayed-plan.md
new file mode 100644
index 000000000..6737d28a9
--- /dev/null
+++ b/docs/plans/2026-11-06-buddy-session-stayed-plan.md
@@ -0,0 +1,41 @@
+# A Buddy thread session that stayed put is recorded where it runs: Implementation Plan
+
+> Written by the project's Engineer by the writing-plans skill; implemented test first. The review step on the pull request
+> is its one independent review.
+
+**Goal:** During a Buddy model switch, a thread session the daemon refuses to move is recorded where it still runs, and one
+left on a member's shared model after a send-home is sent home again (Diego, 11-06, task #3810).
+
+**Architecture:**
+- CLI (`cli/src/superTabs/buddyModel.ts`): reports the sessions that stayed as `stayed: [harnessId]` next to the words. The
+ Buddy's own result is never held up by a busy session: it is reported at once, with the session in `stayed` (Linux test of
+ #3393). A `sessionsOnly` request moves the sessions alone, and waits for a busy one's turn to end within its lease,
+ remembering what already moved.
+- Backend (`backend/src/superTabs/buddyModel.ts`): `buddyModelResult` records the model only on sessions that moved. A session
+ left on a shared model by a move home is marked `homeOwed` ({reason, tries}). The liveness sweep (`unservedBuddyModels`)
+ asks the Buddy's machine for a sessions-only move home, at most three tries, then tells the owner to end that session.
+ `commands.ts` accepts `stayed` on `buddy.modelResult`.
+
+**Tech Stack:** TypeScript, zod, vitest.
+
+## Global Constraints
+- The main Buddy's behaviour is unchanged.
+- No secret in any report or log: harness ids and the existing fixed words only.
+
+## Design
+- growth: `homeOwed` lives on a session agent and goes when it moves, or after three tries.
+- concurrency: one request per Buddy, as before (`modelRequest`); a follow-up is asked only when none is pending.
+- read cost: none new. The sweep already walks the agents.
+- scale: per Buddy, so N/A.
+- compatibility: `stayed` and `sessionsOnly` are optional. An older host reports no `stayed`, so every session reads as moved, as
+ today, and it moves the main Buddy again on a sessions-only request, which is harmless. An older backend never sends
+ `sessionsOnly`.
+- migration and rollback: none.
+- audience and identity: unchanged (only the Buddy's own machine reports).
+- failure: a session that never moves is named to its owner after three tries.
+- platforms: CLI on every platform, and the backend.
+
+## Review Focus
+- A follow-up whose busy session outlasts the lease: reported in `stayed`, never left waiting for good.
+- The Buddy's own result is never held for a session.
+- A switch out with a session in `stayed`: left on its owner's subscription, nothing owed.
diff --git a/docs/plans/2026-11-06-engine-signin-plumbing-plan.md b/docs/plans/2026-11-06-engine-signin-plumbing-plan.md
new file mode 100644
index 000000000..591f2b153
--- /dev/null
+++ b/docs/plans/2026-11-06-engine-signin-plumbing-plan.md
@@ -0,0 +1,77 @@
+# Engine sign-in report plumbing implementation plan
+
+> Implement natively, task by task, with failing tests committed before their fixes.
+
+**Goal:** Carry installed pane engines' sign-in results through the shared probe and machine reports without admitting an unverified engine.
+
+**Architecture:** Let `engineAccount` own engine-specific knowledge; the shared probe calls it for every installed process engine and projects only boolean/null sign-in and numeric/null activity. Swarm readiness can preserve any known process-engine response, but its periodic request stays limited to engines with account readers (Claude/Codex today), and the owner relay can satisfy only those two. Existing start admission remains unchanged.
+
+**Tech Stack:** TypeScript, Node 22.23.2, Vitest.
+
+**Spec:** Task #3839, narrowed by River on 2026-11-06: shared probe/report plumbing and admission safeguards only. Vendor probes are deferred to small tasks on machines with those engines installed; no new engine becomes selectable in this change.
+
+## Global Constraints
+
+- No secret in any report or log. Same admission rules as today's two engines.
+- Owns `cli/src/`; no backend, Desktop or admission changes.
+- Never touch the person's real sign-in. Tests replace external shell/account boundaries.
+- No installs or new background processes. Existing four-worker probe limit stays.
+- Unknown sign-in is null, never true; uninstalled engines are not account-probed.
+
+## Design
+
+- Growth: reports remain bounded by the engine catalog; ten-minute readiness cache replaces old values.
+- Concurrency: existing four probe workers and readiness cache; no new shared state.
+- Read cost: opt-in account reads, installed process engines only; unsupported readers return unknown.
+- Scale: 10x engines increases bounded batches; probe duration is the first warning metric.
+- Compatibility: existing fields and tri-state semantics; old daemons remain unknown.
+- Migration/rollback: no persisted schema change; revert the plumbing.
+- Audience: existing authenticated machine report transport; server admission unchanged.
+- Identity: each machine's local account; owner's relay applies only to its two supported engines.
+- Failure: account read errors become unknown without forwarding error contents.
+- Platforms: shared TypeScript, no new process launch or platform-specific mechanism.
+
+## Review Focus
+
+- Credential-bearing reader results/errors must never be copied into reports (task 1).
+- A failed reader or older daemon must not appear signed in (tasks 1/2).
+- A healthy owner relay must not mark Cursor or another unsupported engine signed in (task 2).
+- Terminal/unknown catalog names must not enter Swarm readiness (task 2).
+- Existing Claude/Codex admission and relay recovery must still work (task 2).
+
+### Task 1: Generalize the opt-in account probe
+
+**Files:** `cli/src/lib/engineProbe.ts`, new `cli/src/lib/engineProbe.spec.ts`.
+
+**Interfaces:** consumes `engineAccount(engine): Promise<EngineAccount>` and the existing launch/install probes; produces unchanged `probeEngines(engines, { accounts })` availability rows.
+
+- [x] Add tests with controlled external launch/account boundaries: installed Cursor signed in/out/unknown; missing installs and accounts=false never read accounts; thrown errors become null; extra credential fields never escape.
+- [x] Run `npx vitest run src/lib/engineProbe.spec.ts --maxWorkers=1`, watch missing account fields fail, commit tests.
+- [x] Call the account reader for every installed process engine, explicitly project safe scalar fields, and return unknown on reader failure. Update field comments.
+- [x] Run affected probe/account tests and commit implementation.
+
+### Task 2: Carry process-engine readiness safely
+
+**Files:** `cli/src/superTabs/machines.ts`, `cli/src/superTabs/machines.spec.ts`, `cli/src/lib/machineEngines.ts`, `cli/src/lib/machineEngines.spec.ts`.
+
+**Interfaces:** consumes task 1 availability rows; produces existing machine readiness payload and `harness machines engines` rows. No new admission API.
+
+- [x] Test readiness includes signed-in/out/unknown other process engines, ignores terminal/unknown names, strips extra fields, and does not use Claude/Codex relay for them. Retain cache and relay recovery assertions. Test machine-engine requests include accounts=true so their sign-in column is populated.
+- [x] Run the two affected test files, observe failures, commit tests.
+- [x] Keep the periodic request at Claude/Codex until another account reader lands, filter responses to known process engines, and limit relay satisfaction to Claude/Codex. Ask for accounts in the machine-engine command and update comments. Keep the separate launch admission/install gate unchanged.
+- [x] Run those tests plus start/admission and account/probe tests; run CLI typecheck. Commit and push.
+
+## Validation
+
+Local: affected tests (`engineProbe`, `engineAccount`, `machineEngines`, `superTabs/machines`, `superTabs/start`) and importers of changed modules; CLI typecheck. Linux full CLI suite comes from automatic Ready PR CI. No native vendor sign-in evidence is claimed: vendor probes are outside the narrowed scope. Review checks the unchanged admission gate and scalar-only reports. Record red/green evidence in a PR comment before Ready.
+
+## Validation receipts
+
+- CLI Node 22.23.2: typecheck passed; affected/importer run 1087 passed, four existing 5s timeouts. Focused serial retry with 30s timeout: seven selected tests passed, including those four. No implementation changes between those runs.
+- Before/after test commits and exact commands are in the PR red/green comment. Linux CLI suite remains automatic Ready PR CI evidence.
+
+## Security review correction
+
+The initial implementation requested all fifteen engines periodically. Security review identified unused idle login-shell work, so the periodic request returns to Claude/Codex and its original 20-second deadline. A regression test first fails on the fifteen-engine request, then passes on the bounded request. On-demand account probing remains generic for vendor-reader follow-ups.
+
+With periodic reports still containing only two requested engines, the backend row-bound change is unnecessary and removed, along with its added test. The final diff is CLI-only and needs no backend-first rollout. The earlier backend test/implementation commits remain in history to explain their reversal. Minor unsupported-reader early-return cleanup is deferred as the project review rules require.
diff --git a/docs/plans/2026-11-06-failed-start-report-retries-plan.md b/docs/plans/2026-11-06-failed-start-report-retries-plan.md
new file mode 100644
index 000000000..cf459adf3
--- /dev/null
+++ b/docs/plans/2026-11-06-failed-start-report-retries-plan.md
@@ -0,0 +1,56 @@
+# Failed-start report retries implementation plan
+
+> Native implementation, task by task, test first; independent review of the complete pull request.
+
+**Goal:** Stop repeating a failed-start report the server refuses as missing, while real failures reach the server and transient reporting failures retry with capped backoff.
+
+**Architecture:** Keep one report state per currently listed start inside ContributedMachines. The existing scoped host request intercepts every agent.startFailed path. A queued report is retried directly, without preparing or launching again. NOT_FOUND and accepted reports are terminal until the feed drops that start; all other failures retry after 15, 30, 60, 120, 240 then 300 seconds, capped at 300 seconds.
+
+**Tech Stack:** TypeScript and Vitest; existing host feed, backend request timeout and monotonic injected clock; no dependency or backend/schema change.
+
+**Spec:** Task #3845, Ken's production scan and River's brief: missing-start report sent once, other failures back off with a cap; real failure still reported; no secret in logs.
+
+## Global Constraints
+
+- Swarm code stays outside cli/src/core; stop only processes started here, by id.
+- No real sign-in, daemon, tmux or home-folder writes in tests; use existing fake Core and injected backend.
+- No error bodies or report text in new diagnostic logs; fixed messages only.
+- Local affected tests/importers and CLI typecheck; automatic PR CI supplies the full unit suite.
+- PR body starts `Requested by 0xKen15 through Harness.`
+
+## Design
+
+- **Growth/lifecycle:** One in-memory entry per feed-listed start, removed when it disappears or the host has no contributions. No persistent data, collection or index. Reports retain only existing command input, operation id and retry timing.
+- **Concurrency:** Existing single-flight tick serializes report attempts; preserve the original operation id on every retry.
+- **Read cost/scale:** No extra reads/timers; reuse the existing host pass and bounded two-start round. A pending report skips preparation/native launch. At ten times pending starts memory grows linearly with the existing host feed; production warning count and local fixed retry/recovery logs expose failures.
+- **Compatibility/migration/rollback:** No wire change; existing NOT_FOUND is terminal for agent.startFailed only. Restart can resend an unacknowledged report with its original server receipt, as today. Rollback only restores old retry cadence.
+- **Audience/identity:** Existing machine-scoped endpoint and credentials unchanged. No new rights. Logs contain neither raw error text nor report bodies.
+- **Failure/platforms:** Report failures stay visible through a fixed pending/recovery diagnostic; transport and non-NOT_FOUND refusals retry indefinitely at a capped delay. TypeScript host behavior on macOS/Linux/Windows; no process creation or UI change.
+
+## Review Focus
+
+1. NOT_FOUND on another command must keep its existing behavior; terminate only failed-start reporting.
+2. Unknown and transient refusals must retain a real failure's original command and operation id.
+3. A completed failure report must never retry an undispatched launch on a stale feed; an already-dispatched receipt retains its existing reconciliation/abandoned cleanup.
+4. A missing start must not block a different pending start or pollute logs with server-provided text.
+5. Dropped contributions/start rows must release report state; cancellation/abandoned native cleanup stays independent.
+
+## Task 1: Bound failed-start reporting
+
+**Files:** Modify `cli/src/superTabs/machines.ts`; tests in `cli/src/superTabs/machines.spec.ts`. Importer checks: host.spec.ts, cloneTrust.spec.ts; adjacent start.spec.ts.
+
+**Interfaces:** Existing ScopedRequest and ContributedMachines.tick remain unchanged. Private report state stores original `{operationId,command}`, endpoint, attempts and nextAt/terminal state. Existing backend rejects with SuperTabHostError; do not change backend semantics.
+
+- [x] Commit failing tests: NOT_FOUND sends once over many passes with one fixed log; transport/other refusal attempts at 15/30/60/120/240/300-second intervals and repeats at cap; success reaches server once; retries preserve operation id, do not relaunch, and do not log fixture secret text; a second start still runs.
+- [x] Run `cd cli && npm test -- src/superTabs/machines.spec.ts -t 'failed-start report'`; observe behavior failures before production code.
+- [x] Intercept only agent.startFailed in the scoped host sender, retain/retry its report directly on later passes, terminally drop NOT_FOUND/accepted reports, prune state alongside feed rows, and use fixed diagnostics. Commit implementation.
+- [x] Run machines/start/host/cloneTrust affected tests and typecheck; record red/green and same-workload request reduction (including retries at cap), update plan and push.
+- [ ] Add evidence comment, mark ready, record exact head through work.status; keep stable during review/CI. Record done only after required reviews/tests pass.
+
+## Validation evidence
+
+- Plan first: `0a761c925`. Tests `371ca3880` produced five intended failures before `7c075426b`: NOT_FOUND sent 11 times instead of once; all three other-failure cases sent 73 times instead of eight; an accepted real failure was reported six times instead of once.
+- Same 18-minute injected-clock workload (73 host passes, same fixtures): transient report requests 73 → 8, and checkout preparation 73 → 1. The eight attempts occur at 0, 15, 45, 105, 225, 465, 765 and 1065 seconds; final two intervals stay capped at 300 seconds. No native launch is retried for an undispatched failed start. The missing-start workload sends 1 report across 11 passes, with one fixed diagnostic and no server text.
+- Focused regression check after implementation: 5 passed. An affected run caught two existing dispatched-receipt cases; `dce5ccea8` retains their reconciliation instead of treating them as undispatched starts. The seven targeted checks then passed; 410 machine/start/clone-trust checks passed in the broader run.
+- That broader run had one unrelated host acknowledgement test timeout (839 passed / 1 timed out). The test iterated 400 disk-backed retries. `3a9b8eb5a` keeps the expiry assertions and adds a still-retained check at 23 hours, then crosses 24 hours directly; cadence remains checked in its adjacent test. Both expiry cases passed, then all 430 host checks passed. This fixes the source of the timeout rather than retrying it green.
+- CLI typecheck passed after correcting callback narrowing. No real account, daemon, native session or sign-in was used. Full CLI suite runs automatically in PR CI; no local coverage gate applies because core/services/harnessd are unchanged.
diff --git a/docs/plans/2026-11-06-shell-guard-followup-plan.md b/docs/plans/2026-11-06-shell-guard-followup-plan.md
new file mode 100644
index 000000000..6eaa4b683
--- /dev/null
+++ b/docs/plans/2026-11-06-shell-guard-followup-plan.md
@@ -0,0 +1,57 @@
+# Shell guard follow-up implementation plan
+
+> Implement task by task in this Engineer session, test first, with independent security reviews of the completed PR.
+
+**Goal:** Close the three shell guard bypasses in task #3668.
+**Architecture:** Extend the existing parser and kill target check; force hooks enabled in Claude session settings. Keep personal sessions untouched.
+**Tech Stack:** TypeScript, Node, Vitest.
+**Spec:** Swarm task #3668, conversation 377527a961f39144696483d3; prerequisite PR #3304.
+
+## Global Constraints
+- Build on #3304; keep a draft until it merges, then merge main and target main.
+- Swarm code stays outside cli/src/core; no new dependencies.
+- Never execute dangerous commands in tests; parser inputs only. Isolate all filesystem fixtures.
+- Two independent security reviews. Record red/green evidence before Ready.
+
+## Review Focus
+- Signal options versus negative targets: allow SIGHUP to a positive PID, refuse process groups.
+- Bare negative numbers and explicit -- target separators.
+- Assignment chains, braces, concatenated paths, and reassignment.
+- Quoted or escaped dollar signs remain literal; unknown values stay unknown.
+- Claude session settings override disabled hooks without changing personal settings.
+
+### Task 1: Negative kill targets
+**Files:** cli/src/superTabs/shellGuard.ts; cli/src/superTabs/shellGuard.spec.ts.
+**Interfaces:** shellRefusal(command, facts): string | null, existing refusal result.
+- [x] Add failing cases for bare kill -1, negative groups after signal/--, and zero; retain positive signal targets.
+- [x] Run and commit failing tests.
+- [x] Refuse ambiguous bare negative targets and every nonpositive target after signal parsing.
+- [x] Run affected guard tests and commit implementation.
+
+### Task 2: Simple assignment expansion
+**Files:** cli/src/superTabs/shellGuard.ts; cli/src/superTabs/shellGuard.spec.ts.
+**Interfaces:** Existing shellRefusal API; split tracks command-local known assignment values.
+- [x] Add failing cases for /tmp root variables, chains, braced references and literal dollar signs.
+- [x] Run and commit failing tests.
+- [x] Expand known simple assignments in command order while preserving quotes and unknown substitutions.
+- [x] Run guard tests and commit implementation.
+
+### Task 3: Disabled hooks
+**Files:** cli/src/lib/agentShellGuard.ts; cli/src/lib/swarmEngineArgs.spec.ts.
+**Interfaces:** claudeShellGuardArgs(): string[], existing launch settings.
+- [x] Add a failing session-settings test requiring disableAllHooks false even over a disabled base.
+- [x] Run and commit failing test.
+- [x] Force disableAllHooks false in Swarm launch settings.
+- [x] Run affected tests, hook process/bundle tests and typecheck; commit implementation.
+
+## Validation
+Affected guard and launch tests on macOS; typecheck. Full CLI unit suite runs once in ready PR CI on Linux. Verify real engine settings precedence if the CLI is available; report unavailable native/platform checks. No coverage-gated directories changed. Reuse unchanged prerequisite evidence for its own behavior. Review and test steps run independently at final head.
+
+## Recorded evidence
+- Kill cases: ec2f4d10c failed 7 cases; b28e3c483 passed 141/141.
+- Variable cases: b6f7c4e4a failed 6 cases; 498595dc5 passed 152/152.
+- Disabled hooks: a1691d42a failed 1 case; e5144b477 passed the affected launch checks.
+- Combined hook, process and bundle checks: 5 files, 173 tests passed before integrating the latest prerequisite; subsequent guard/launch checks passed 167/167.
+- Node 22.23.2 macOS x64: typecheck passed.
+- Native Claude isolated HOME/config, dummy API key and unreachable local API: inherited disableAllHooks true suppresses SessionStart; session override false runs it. Both processes bounded at 8 seconds; personal sign-in never used.
+- Linux CI and native Windows remain pending; draft waits for #3304 to merge and main integration.