The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Merge batch 11-04 b1447: #2956 #2932 #2946 #2918 (#2958)
0xken15c921dd344bcf
diff --git a/backend/integration/noDefaultDigest.test-support.ts b/backend/integration/noDefaultDigest.test-support.tsindex d6dfcabe2..4d341b73a 100644--- a/backend/integration/noDefaultDigest.test-support.ts+++ b/backend/integration/noDefaultDigest.test-support.ts@@ -22,3 +22,14 @@ vi.mock('../src/superTabs/digest.js', async original => {},}})++// The built-in PM schedule (pmSchedule.ts) stays off alike: its wake would be one more coordinator message on the first poll of+// every test with an unassigned task. A test about it calls wantSchedule().+const schedule = vi.hoisted(() => ({ wanted: false }))+export const wantSchedule = (): void => { schedule.wanted = true }+beforeEach(() => { schedule.wanted = false })++vi.mock('../src/superTabs/pmSchedule.js', async original => {+ const real = await original<typeof import('../src/superTabs/pmSchedule.js')>()+ return { ...real, scheduleRequest: (...args: Parameters<typeof real.scheduleRequest>) => schedule.wanted ? real.scheduleRequest(...args) : null }+})diff --git a/backend/integration/superTabInstructions.test.ts b/backend/integration/superTabInstructions.test.tsindex f1d482d6c..2ca3c7e5f 100644--- a/backend/integration/superTabInstructions.test.ts+++ b/backend/integration/superTabInstructions.test.ts@@ -18,6 +18,7 @@ import { roleVersion } from '../src/superTabs/projects.js'import { DEFAULT_ROUTING_POLICY } from '../src/superTabs/routingPolicy.js'import { INSTRUCTIONS_TEMPLATE } from '../src/superTabs/instructionsTemplate.js'import { rosterRows } from './hostRows.test-support.js'+import { PM_SCHEDULE_TEXT } from '../src/superTabs/pmSchedule.js'// A fresh loopback replica set, created here. This suite never reads DATABASE_URL or an existing database.// Project instructions, phase 2 (docs/plans/2026-10-30-project-instructions-plan.md): the document, its revisions, the@@ -253,6 +254,46 @@ describe('reading the instructions', () => {// An older client's saves (project instructions, phase 4, decision 3): a rule lands in the Routing section as a new revision;// a policy, a skill set or a role is answered and kept nowhere.+describe('the built-in PM schedule beside the instructions', () => {+ const doc = (tab: string, asAgentId?: string) => `/api/super-tabs/${tab}/projects/lead/instructions${asAgentId ? `?asAgentId=${asAgentId}` : ''}`+ const withWorker = async () => {+ const { tab, lead } = await withLead()+ const worker = (await run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId: randomUUID(),+ name: 'Worker', configuration: config, lead: false })).result.agentId as string+ return { tab, lead, worker }+ }++ it('is in the coordinator\'s read alone, and the document read is unchanged', async () => {+ const { tab, lead, worker } = await withWorker()+ const asLead = (await get(host, doc(tab, lead))).json().data+ expect(asLead.builtIn).toBe(PM_SCHEDULE_TEXT)+ expect(asLead).toMatchObject({ revision: 1, text: INSTRUCTIONS_TEMPLATE, hash: instructionsHash(INSTRUCTIONS_TEMPLATE) })+ for (const [user, as] of [[host, worker], [owner]] as Array<[AuthUser, string?]>) {+ const answer = await get(user, doc(tab, as))+ expect(answer.statusCode, answer.body).toBe(200)+ expect(answer.json().data).not.toHaveProperty('builtIn')+ }+ })++ it('moves the coordinator\'s roster row by its hash; no other agent\'s row carries one', async () => {+ const { tab, lead, worker } = await withWorker()+ const rows = (await rosterRows(store, host, 'test-host')).filter(r => r.tabId === tab) as Array<{ agent: { id: string }; instructions: Record<string, unknown> }>+ expect(rows.find(r => r.agent.id === lead)!.instructions.builtInHash).toBe(instructionsHash(PM_SCHEDULE_TEXT))+ expect(rows.find(r => r.agent.id === worker)!.instructions).not.toHaveProperty('builtInHash')+ })++ it('refuses a save holding the built-in section, and takes the document as read', async () => {+ const { tab, lead } = await withLead()+ const read = (await get(host, doc(tab, lead))).json().data+ await expect(run(tab, { type: 'instructions.save', projectId: 'lead', baseRevision: 1, text: `${read.text}\n\n${read.builtIn}`, summary: 'Copied',+ askedBy: owner.sub }, host, lead)).rejects.toMatchObject({ code: 'INSTRUCTIONS_BUILT_IN' })+ expect((await get(owner, doc(tab))).json().data.revision).toBe(1)+ await run(tab, { type: 'instructions.save', projectId: 'lead', baseRevision: 1, text: `${read.text}\nOne more line.`, summary: 'One more line',+ askedBy: owner.sub }, host, lead)+ expect((await get(owner, doc(tab))).json().data.revision).toBe(2)+ })+})+describe('an older client\'s saves', () => {it('takes an old Desktop\'s saves', async () => {const { tab, lead } = await withLead()diff --git a/backend/integration/superTabLiveness.test.ts b/backend/integration/superTabLiveness.test.tsindex 3235a2ddc..67e330014 100644--- a/backend/integration/superTabLiveness.test.ts+++ b/backend/integration/superTabLiveness.test.ts@@ -1789,8 +1789,9 @@ describe('the push for a new delivery', () => {// The Lead's alone, so it reads their order (people do not read them).const page = (await f.timed.messages(host, f.tab, 'lead', {}, f.lead)).messages.filter(row => expectedIds.includes(row.id))expect(page).toHaveLength(3)- expect(page[1]!.sequence).toBe(page[0]!.sequence + 1)- expect(page[2]!.sequence).toBe(page[1]!.sequence + 1)+ // In conversation order; each loss's Stuck reply in its task's thread is written between them (task #2693).+ expect(page[1]!.sequence).toBeGreaterThan(page[0]!.sequence)+ expect(page[2]!.sequence).toBeGreaterThan(page[1]!.sequence)expect(first.map(row => row.messageId)).toEqual(page.map(row => row.id))// Make the tie explicit, and store the rows later sequence first so insertion order cannot stand in for it, then read again.diff --git a/backend/integration/superTabPmSchedule.test.ts b/backend/integration/superTabPmSchedule.test.tsnew file mode 100644index 000000000..7e6db9ae9--- /dev/null+++ b/backend/integration/superTabPmSchedule.test.ts@@ -0,0 +1,276 @@+import { randomUUID } from 'node:crypto'+import { execFile } from 'node:child_process'+import { promisify } from 'node:util'+import { join } from 'node:path'+import { tmpdir } from 'node:os'+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'+import { PrismaClient } from '@prisma/client'+import type { AuthUser } from '../src/lib/ssoAuth.js'+import { SuperTabStore, transaction } from '../src/superTabs/store.js'+import { SwarmReads } from '../src/superTabs/read/service.js'+import type { Command } from '../src/superTabs/commands.js'+import { poolRows } from './hostRows.test-support.js'+import { settleStuckDeliveries } from '../src/superTabs/deliverySettle.js'+import { compactDeliveries } from '../src/superTabs/deliveryCompaction.js'+import { revokeNativeContexts } from '../src/superTabs/native.js'+import { stableId, type MessageDraft, type SuperTabState } from '../src/superTabs/model.js'+import { logger } from '../src/utils/logger.js'+import { wantSchedule } from './noDefaultDigest.test-support.js'+import { SCHEDULE_SLOT_MS, scheduleSlot } from '../src/superTabs/pmSchedule.js'++// Ken, 2026-11-04 (docs/plans/2026-11-04-pm-built-in-schedule-design.md): the coordinator's poll wakes it every 30 minutes for+// the built-in schedule when the sweep has something to do, in one message per poll. A fresh loopback replica set, created here.+let replica: MongoMemoryReplSet+let db: PrismaClient+const owner: AuthUser = { sub: '210000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const host: AuthUser = { sub: '210000000000000000000003', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const config = { engine: 'codex', model: 'fixture-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }+const MINUTE = 60_000+const DUE = 5 * MINUTE++beforeAll(async () => {+ replica = await MongoMemoryReplSet.create({ binary: { version: '7.0.24', downloadDir: join(tmpdir(), 'harness-super-tab-mongodb-binaries') },+ replSet: { count: 1, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })+ const uri = replica.getUri(`swarm_schedule_test_${randomUUID().replaceAll('-', '_')}`)+ await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], {+ env: { ...process.env, DATABASE_URL: uri }, timeout: 60000,+ })+ db = new PrismaClient({ datasources: { db: { url: uri } } })+ for (const user of [owner, host]) await db.user.create({ data: { id: user.sub, externalId: `fixture-${user.sub}`, email: user.email, autonomousEnv: user.autonomousEnv } })+ for (const machineId of ['lead-host', 'test-host']) {+ await db.machine.create({ data: { machineId, userId: host.sub, apiKey: `fixture-${machineId}`, managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })+ await db.machineShare.create({ data: { machineId, ownerId: host.sub, autonomousEnv: 'prod', emails: [owner.email] } })+ }+})+afterAll(async () => {+ await db?.$disconnect()+ await replica?.stop()+})++/** A Swarm whose coordinator runs on one machine and whose worker, on another, works on task "Ship the parser". The coordinator's+ * first update request (for the assignment) has gone, so nothing merges with a digest in the next 15 minutes, unless [fresh]. */+async function swarm({ fresh = false, told }: { fresh?: boolean; told?: string[] } = {}) {+ let now = Date.parse('2026-11-02T06:30:00.000Z')+ const timed = new SuperTabStore(db, () => now, null, told ? { deliveriesWaiting: w => { told.push(w.agentId) } } : {})+ const tab = (await timed.create(owner, randomUUID(), 'Digest', 'public')).id+ const execute = (command: Command, user = owner, asAgentId?: string) => timed.execute(user, tab, { operationId: randomUUID(), command }, asAgentId)+ const invitation = await execute({ type: 'invite.create', email: host.email, role: 'collaborator', conversationId: 'lead' })+ await execute({ type: 'invite.accept', inviteId: invitation.result.inviteId as string }, host)+ for (const [machineId, name] of [['lead-host', 'Lead Mac'], ['test-host', 'Worker Mac']]) {+ await execute({ type: 'machine.contribute', machineId: machineId!, name: name!, cwd: '/repo', engines: ['codex'], maxAgents: 4 }, host)+ }+ const generations = new Map<string, string>()+ for (const machineId of ['lead-host', 'test-host']) generations.set(machineId, (await poolRows(timed, host, machineId)).find(p => p.tabId === tab)!.machine.generation)+ const harnessOf = new Map<string, string>()+ const add = async (conversationId: string, machineId: string, name: string, lead = false) => {+ const harnessId = randomUUID()+ const agentId = String((await execute({ type: 'agent.add', conversationId, machineId, harnessId, name, configuration: config, lead })).result.agentId)+ harnessOf.set(machineId, harnessId)+ return agentId+ }+ const lead = await add('lead', 'lead-host', 'Lead', true)+ const group = String((await execute({ type: 'conversation.create', title: 'Ship the parser', brief: 'Implement it',+ checks: [] })).result.conversationId)+ const worker = await add(group, 'test-host', 'Worker')+ const assignmentId = String((await execute({ type: 'work.assign', conversationId: group, agentId: worker })).result.assignmentId)+ const clock = { get now() { return now }, set now(value: number) { now = value } }+ /** Its machines report, as live ones do. */+ const report = async () => {+ // Its own first: a machine's report also judges the others', and one not heard from in 2 minutes loses its work.+ for (const machineId of ['test-host', 'lead-host']) await timed.observeMachine(host, tab, machineId, { generation: generations.get(machineId)!,+ resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9, diskFreeBytes: 120e9, diskTotalBytes: 500e9, projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Fixture', os: 'macOS', gpuPercent: null },+ quotas: [], tools: {}, runningHarnessIds: [harnessOf.get(machineId)!], stoppedHarnessIds: [] })+ }+ const poll = async () => {+ // Its worker keeps saying where it is, as a live one does; a finished task refuses the line and nothing changes.+ await execute({ type: 'work.status', conversationId: group, assignmentId, status: 'working', result: randomUUID() }, host, worker).catch(() => {})+ await report()+ return timed.deliveries(host, tab, lead)+ }+ const status = (s: 'done' | 'blocked' | 'needs_human' | 'working', result = 'A result') =>+ execute({ type: 'work.status', conversationId: group, assignmentId, status: s, result }, host, worker)+ if (!fresh) {+ clock.now += DUE + 1_000+ await poll()+ const early = await rowsOf(tab, { status: 'gathered' })+ expect(await Promise.all(early.map(d => db.superTabMessage.findUnique({ where: { id: d.messageId } }).then(m => [m?.text, m?.source])))).toEqual([])+ }+ /** Writes one message as the store writes every message, for a notice no short command here sets off. */+ const write = async (source: Record<string, unknown> | undefined, recipient: string, conversationId = group, text = 'A notice.', as = worker) => {+ const id = randomUUID().replaceAll('-', '').slice(0, 24)+ await transaction(db, async tx => {+ const store = timed as unknown as { load(tx: unknown, user: AuthUser, tab: string, named?: unknown): Promise<{ state: SuperTabState }>+ writeMessages(tx: unknown, tab: string, state: SuperTabState, messages: MessageDraft[], sequences: Map<string, number>): Promise<void> }+ const { state } = await store.load(tx, host, tab, { groupIds: [conversationId] })+ const sender = state.agents.find(a => a.id === as)!+ await store.writeMessages(tx, tab, state, [{ id, conversationId, text, replyTo: null, recipients: [recipient], ...source ? { source } : {},+ author: { kind: 'agent', id: as, name: sender.name, displayName: sender.name, membershipGeneration: sender.membershipGeneration } } as MessageDraft],+ new Map([[id, 90_000 + Math.floor(Math.random() * 100_000)]]))+ })+ return id+ }+ return { timed, tab, execute, lead, group, worker, assignmentId, clock, poll, status, write, add }+}++const rowsOf = (tabId: string, where: Record<string, unknown> = {}) => db.superTabDelivery.findMany({ where: { tabId, ...where }, orderBy: { createdAt: 'asc' } })+const deliveryOf = (messageId: string, agentId: string) => db.superTabDelivery.findUniqueOrThrow({ where: { id: stableId(messageId, agentId) } })+const kindOf = (message: { source: unknown }) => (message.source as { kind?: string } | null)?.kind+const digests = async (tabId: string) => (await db.superTabMessage.findMany({ where: { tabId }, orderBy: { sequence: 'asc' } })).filter(m => kindOf(m) === 'notice-digest')++const schedules = async (tabId: string) => (await db.superTabMessage.findMany({ where: { tabId }, orderBy: { sequence: 'asc' } }))+ .filter(m => m.text.includes('Built-in schedule,'))+/** The head part's version and time: what every reader compares to know whether anything changed. */+const headOf = async (tabId: string) => db.swarmHead.findUniqueOrThrow({ where: { id: `${tabId}:head` }, select: { version: true, changedAt: true } })+const projectOf = async (f: Awaited<ReturnType<typeof swarm>>) => (await f.timed.read(host, f.tab, undefined, f.lead)).state.projects![0]!+/** A task with no agent: what the sweep is for. */+const unassigned = (f: Awaited<ReturnType<typeof swarm>>) => f.execute({ type: 'conversation.create', title: 'Nobody has this', brief: 'Do it', checks: [] })++describe('the built-in schedule on the coordinator\'s poll', () => {+ it('wakes the coordinator once per slot, as its own message when nothing else goes', async () => {+ const f = await swarm()+ wantSchedule()+ await unassigned(f)+ const inbox = await f.poll()+ const [wake] = await schedules(f.tab)+ expect(wake).toBeDefined()+ expect(kindOf(wake!)).toBe('schedule-request')+ expect(wake!.recipientIds).toEqual([f.lead])+ expect(inbox.map(d => d.messageId)).toContain(wake!.id)+ f.clock.now += MINUTE+ await f.poll()+ expect(await schedules(f.tab)).toHaveLength(1)+ expect((await projectOf(f)).schedule).toMatchObject({ lastSlot: scheduleSlot(f.clock.now) })+ })++ it('is the coordinator\'s alone: no person sees it in the chat, and no other agent reads it', async () => {+ const f = await swarm()+ wantSchedule()+ await unassigned(f)+ await f.poll()+ const [wake] = await schedules(f.tab)+ const page = async (user: AuthUser, asAgentId?: string) => (await f.timed.messages(user, f.tab, 'lead', { messageId: wake!.id }, asAgentId)).messages.map(m => m.id)+ expect(await page(host, f.lead)).toEqual([wake!.id])+ for (const user of [owner, host]) expect(await page(user)).toEqual([])+ expect(await page(host, f.worker)).toEqual([])+ })++ it('writes nothing to the Swarm\'s head and sends nothing when every task has an agent working on it', async () => {+ const f = await swarm()+ wantSchedule()+ await f.poll()+ f.clock.now += SCHEDULE_SLOT_MS+ // Every reader rereads a head that moved: a slot with nothing due must leave it as it was (#2946 review, 1).+ const before = await headOf(f.tab)+ await f.poll()+ expect(await schedules(f.tab)).toEqual([])+ expect(await headOf(f.tab)).toEqual(before)+ expect((await projectOf(f)).schedule).toBeUndefined()+ // Something to sweep later in the same slot wakes it once.+ await unassigned(f)+ await f.poll()+ expect(await schedules(f.tab)).toHaveLength(1)+ })++ it('keeps the slot out of the head readers get', async () => {+ const f = await swarm()+ wantSchedule()+ await unassigned(f)+ await f.poll()+ expect((await projectOf(f)).schedule).toMatchObject({ lastSlot: scheduleSlot(f.clock.now) })+ const reads = new SwarmReads(f.timed)+ for (const [user, asAgentId] of [[owner], [host], [host, f.lead]] as const) {+ const { head } = await reads.firstLoad(user, f.tab, asAgentId)+ expect(head.data.projects!.map(p => 'schedule' in p)).toEqual([false])+ }+ })++ it('sends no second wake while the first is unread, and still moves the slot', async () => {+ const f = await swarm()+ wantSchedule()+ await unassigned(f)+ await f.poll()+ f.clock.now += SCHEDULE_SLOT_MS+ await f.poll()+ expect(await schedules(f.tab)).toHaveLength(1)+ expect((await projectOf(f)).schedule).toMatchObject({ lastSlot: scheduleSlot(f.clock.now) })+ })++ it('sends no second wake over three slots while the first is unread', async () => {+ const f = await swarm()+ wantSchedule()+ await unassigned(f)+ await f.poll()+ for (const _ of [1, 2]) { f.clock.now += SCHEDULE_SLOT_MS; await f.poll() }+ expect(await schedules(f.tab)).toHaveLength(1)+ })++ it('sends no wake of its own while the update request that carried the last one is unread', async () => {+ const f = await swarm({ fresh: true })+ wantSchedule()+ await unassigned(f)+ f.clock.now += DUE+ await f.poll()+ f.clock.now += SCHEDULE_SLOT_MS+ await f.poll()+ expect((await schedules(f.tab)).map(kindOf)).toEqual(['update-request'])+ })++ it('goes in the update request when one is written in the same poll', async () => {+ // Fresh: the setup's own update request would still wait for its answer, and no second one goes meanwhile.+ const f = await swarm({ fresh: true })+ wantSchedule()+ await unassigned(f)+ f.clock.now += DUE+ await f.poll()+ const [wake] = await schedules(f.tab)+ expect(kindOf(wake!)).toBe('update-request')+ expect(wake!.source).toMatchObject({ kind: 'update-request', schedule: scheduleSlot(f.clock.now) })+ expect(wake!.text.indexOf('Work changed')).toBeLessThan(wake!.text.indexOf('Built-in schedule,'))+ expect((await db.superTabMessage.findMany({ where: { tabId: f.tab } })).filter(m => kindOf(m) === 'schedule-request')).toEqual([])+ })++ it('goes in the notice digest when one is written and no update request is', async () => {+ const f = await swarm()+ wantSchedule()+ await f.write({ kind: 'idle' }, f.lead)+ await unassigned(f)+ f.clock.now += DUE+ await f.poll()+ const [digest] = await digests(f.tab)+ expect(digest!.text).toContain('Built-in schedule,')+ expect(digest!.source).toMatchObject({ kind: 'notice-digest', schedule: scheduleSlot(f.clock.now) })+ expect(await schedules(f.tab)).toHaveLength(1)+ })++ it('does not go in an update request already stored under its id', async () => {+ const f = await swarm({ fresh: true })+ wantSchedule()+ await f.write({ kind: 'idle' }, f.lead)+ await unassigned(f)+ f.clock.now += DUE+ const { projectUpdateRequest } = await import('../src/superTabs/projectUpdates.js')+ const { state } = await f.timed.read(host, f.tab, undefined, f.lead)+ const draft = projectUpdateRequest(state, state.agents.find(a => a.id === f.lead)!, f.clock.now)!+ await db.superTabMessage.create({ data: { id: draft.id, tabId: f.tab, conversationId: draft.conversationId, sequence: 1, text: draft.text, replyTo: null, recipientIds: draft.recipients,+ mentions: [], thread: draft.id, source: draft.source as object, author: draft.author as object } })+ await f.poll()+ expect((await db.superTabMessage.findUniqueOrThrow({ where: { id: draft.id } })).text).not.toContain('Built-in schedule,')+ expect(await schedules(f.tab)).toHaveLength(1)+ })++ it('sends nothing in a paused Swarm, and one wake for the current slot once it resumes', async () => {+ const f = await swarm()+ wantSchedule()+ await unassigned(f)+ await f.execute({ type: 'tab.pause', paused: true })+ await f.poll()+ f.clock.now += 3 * SCHEDULE_SLOT_MS+ await f.poll()+ expect(await schedules(f.tab)).toEqual([])+ await f.execute({ type: 'tab.pause', paused: false })+ await f.poll()+ expect(await schedules(f.tab)).toHaveLength(1)+ expect((await projectOf(f)).schedule).toMatchObject({ lastSlot: scheduleSlot(f.clock.now) })+ })+})diff --git a/backend/integration/superTabTaskLines.test.ts b/backend/integration/superTabTaskLines.test.tsindex 2e44e5f55..382bf5b8b 100644--- a/backend/integration/superTabTaskLines.test.ts+++ b/backend/integration/superTabTaskLines.test.ts@@ -111,6 +111,21 @@ describe('a task\'s one message in its project chat', () => {await expect(s.as(P)({ type: 'conversation.create', title: 'Another', brief: '', checks: [], requestMessageId: 'missing' })).rejects.toThrow('own message')})+ // Diego, 2026-11-04 (task #2693): a stop its host confirms is no command, so its thread kept saying On it.+ it('says Not building this in the thread once when the host confirms the stop', async () => {+ const s = await swarm()+ const P = await s.add('Coordinator', 'lead', true)+ const T = String((await s.as(P)({ type: 'conversation.create', title: 'Offline drafts', brief: 'Keep drafts.', checks: [] })).result.conversationId)+ const root = (await s.page('lead')).lines[0]!.id+ const E = await s.add('Engineer', T)+ const assignmentId = String((await s.as(P)({ type: 'work.assign', conversationId: T, agentId: E })).result.assignmentId)+ await store.stopped(host, s.tab, assignmentId, 'fixture stop receipt')+ await store.stopped(host, s.tab, assignmentId, 'fixture stop receipt')+ const replies = (await store.messages(owner, s.tab, 'lead', { thread: root })).messages.filter(m => m.text.startsWith('Not building this'))+ expect(replies).toEqual([expect.objectContaining({ text: 'Not building this: The execution host confirmed that this harness stopped.',+ thread: root, replyTo: root, recipientIds: [], author: expect.objectContaining({ id: P }) })])+ })+it('posts none for a task\'s steps', async () => {const s = await swarm()const P = await s.add('Coordinator', 'lead', true)diff --git a/backend/src/github/app.test.ts b/backend/src/github/app.test.tsindex 05f00968b..48964c5e8 100644--- a/backend/src/github/app.test.ts+++ b/backend/src/github/app.test.ts@@ -144,6 +144,87 @@ describe('installation tokens', () => {await expect(app.createToken(77, repo)).rejects.toMatchObject({ code: 'GITHUB_UNAVAILABLE', status: 502 })})+ // Scholes, task #2755 (Ken approved): an agent's token also pushes workflow files and writes issues, where the+ // installation has granted them. Asking for one it has not granted would refuse every token on it.+ const today = { contents: 'write', pull_requests: 'write', checks: 'read', actions: 'read', metadata: 'read' } as const+ const minted = (github: ReturnType<typeof fakeGitHub>) => github.calls.filter(c => c.path.endsWith('/access_tokens')).map(c => c.body)++ it('asks for workflows and issues on an agent\'s token, for its one repository, where the installation granted them', async () => {+ const { app, github } = setup()+ github.grants.set(77, { ...today, workflows: 'write', issues: 'write' })+ expect((await app.createToken(77, repo)).token).toBe('ghs_fixture_1')+ expect(minted(github)).toEqual([{ repositories: ['app'], permissions: { ...today, workflows: 'write', issues: 'write' } }])+ expect(github.calls.filter(c => c.path === '/app/installations/77')).toHaveLength(1)+ })++ it('asks for no more than each granted level, and only what is granted', async () => {+ const { app, github } = setup()+ github.grants.set(77, { ...today, issues: 'read', administration: 'write' })+ await app.createToken(77, repo)+ expect(minted(github)).toEqual([{ repositories: ['app'], permissions: { ...today, issues: 'read' } }])+ })++ it('asks for today\'s set where workflows and issues are not granted, and still gets its token', async () => {+ const { app, github } = setup()+ github.grants.set(77, { ...today })+ expect((await app.createToken(77, repo)).token).toBe('ghs_fixture_1')+ expect(minted(github)).toEqual([{ repositories: ['app'], permissions: today }])+ })++ it('asks for today\'s set when GitHub does not say what the installation granted', async () => {+ const { app, github } = setup()+ // The fake answers 404 for an installation it lists no grants for.+ expect((await app.createToken(77, repo)).token).toBe('ghs_fixture_1')+ expect(minted(github)).toEqual([{ repositories: ['app'], permissions: today }])+ })++ it('remembers an installation\'s grant ten minutes', async () => {+ const { app, github, time } = setup()+ github.grants.set(77, { ...today, workflows: 'write' })+ await app.createToken(77, repo)+ await app.createToken(77, repo)+ expect(github.calls.filter(c => c.path === '/app/installations/77')).toHaveLength(1)+ github.grants.set(77, { ...today, workflows: 'write', issues: 'write' })+ time.advance(10 * 60_000 + 1)+ await app.createToken(77, repo)+ expect(github.calls.filter(c => c.path === '/app/installations/77')).toHaveLength(2)+ expect(minted(github).at(-1)).toEqual({ repositories: ['app'], permissions: { ...today, workflows: 'write', issues: 'write' } })+ })++ it('reads the grant again after a permission refusal, and asks once more with what is granted now', async () => {+ const { app, github } = setup()+ github.grants.set(77, { ...today, workflows: 'write', issues: 'write' })+ await app.createToken(77, repo)+ // An owner takes workflows away inside the ten minutes: the remembered grant is wrong.+ github.grants.set(77, { ...today, issues: 'write' })+ expect((await app.createToken(77, repo)).token).toBe('ghs_fixture_2')+ expect(minted(github).slice(1)).toEqual([+ { repositories: ['app'], permissions: { ...today, workflows: 'write', issues: 'write' } },+ { repositories: ['app'], permissions: { ...today, issues: 'write' } }])+ expect(github.calls.filter(c => c.path === '/app/installations/77')).toHaveLength(2)+ // The fresh grant is remembered.+ await app.createToken(77, repo)+ expect(github.calls.filter(c => c.path === '/app/installations/77')).toHaveLength(2)+ })++ it('still refuses, asking once, when even today\'s set is not granted and the fresh grant changes nothing', async () => {+ const { app, github } = setup()+ github.grants.set(77, { contents: 'read', metadata: 'read' })+ await expect(app.createToken(77, repo)).rejects.toMatchObject({ code: 'GITHUB_APP_PERMISSIONS', status: 409 })+ expect(minted(github)).toHaveLength(1)+ expect(github.calls.filter(c => c.path === '/app/installations/77')).toHaveLength(2)+ })++ it('never widens a narrow token, whatever the installation granted', async () => {+ const { app, github } = setup()+ github.grants.set(77, { ...today, workflows: 'write', issues: 'write' })+ await app.createToken(77, repo, PULL_READ_PERMISSIONS)+ await app.createToken(77, repo, PULL_WATCH_PERMISSIONS)+ await app.createToken(77, repo, ACTIONS_READ_PERMISSIONS)+ expect(minted(github).map(b => (b as { permissions: unknown }).permissions)).toEqual([PULL_READ_PERMISSIONS, PULL_WATCH_PERMISSIONS, ACTIONS_READ_PERMISSIONS])+ expect(github.calls.filter(c => c.path === '/app/installations/77')).toHaveLength(0)+ })+it('leaves the install link out when no app name is configured', async () => {const { app } = setup({ slug: null })expect(app.installUrl()).toBeNull()diff --git a/backend/src/github/app.ts b/backend/src/github/app.tsindex 9e4689a3f..16b4a6371 100644--- a/backend/src/github/app.ts+++ b/backend/src/github/app.ts@@ -14,6 +14,14 @@ import type { PullRequestWatch } from '../superTabs/pullRequestEvents.js'/** What a Swarm agent's token may do, and nothing more: push to and read the repository, open and update pull requests,* and read checks and workflow runs to see whether its pull request passes. */export const TOKEN_PERMISSIONS = { contents: 'write', pull_requests: 'write', checks: 'read', actions: 'read', metadata: 'read' } as const+/**+ * What an agent's token also asks for where the repository's installation has granted it, at no more than the granted level+ * (Scholes, task #2755, Ken approved): push changes to `.github/workflows`, which GitHub refuses without `workflows`, and+ * read and write issues. Never asked for where not granted: GitHub refuses a token that asks for a permission its+ * installation has not accepted, and every agent on it would lose its token. Ken accepted the risk: a workflow change runs+ * in CI with the repository's secrets, and Team-written branches are among the pushers.+ */+export const GRANTED_TOKEN_PERMISSIONS = { workflows: 'write', issues: 'write' } as const/** What preparing an agent's folder may do before the agent has a task: clone and fetch the repository, nothing more. */export const PREPARE_PERMISSIONS = { contents: 'read', metadata: 'read' } as const/** What the Swarm's tidying reads before it archives a finished group: whether its pull requests are merged or closed. */@@ -88,6 +96,8 @@ export type BranchProtection = 'pull_request' | 'classic' | 'none' | 'unknown'export interface DefaultBranch { branch: string | null; protection: BranchProtection }const base64url = (value: string | Buffer) => Buffer.from(value).toString('base64url')+const samePermissions = (a: TokenPermissions, b: TokenPermissions) =>+ Object.keys(a).length === Object.keys(b).length && Object.entries(a).every(([name, level]) => b[name] === level)const INSTALLATION_TTL_MS = 10 * 60_000const NOT_INSTALLED_TTL_MS = 60_000/** How often a person's "check again" may make the server ask GitHub again about one repository. */@@ -129,6 +139,8 @@ export class GitHubApp {/** The app's name, as GitHub answers it (botLogin). */private slug: string | null = nullprivate readonly installations = new Map<string, { id: number | null; until: number }>()+ /** What each installation has granted, by its id, for [GRANTED_TOKEN_PERMISSIONS]: null when GitHub did not say. */+ private readonly grants = new Map<number, { permissions: TokenPermissions | null; until: number }>()private readonly branches = new Map<string, { value: DefaultBranch; until: number }>()/** A repository's name now, by the name asked for (lower case): null when it was not renamed. */private readonly renames = new Map<string, { repository: GitHubRepository | null; until: number }>()@@ -321,8 +333,61 @@ export class GitHubApp {if (this.renames.get(key)?.repository === null) this.renames.delete(key)}- /** A token for [repository] alone, with TOKEN_PERMISSIONS alone. */- async createToken(installationId: number, repository: GitHubRepository, permissions: TokenPermissions = TOKEN_PERMISSIONS): Promise<{ token: string; expiresAt: string }> {+ /** What [installationId] has granted (GET /app/installations/{id}, with the app's JWT), remembered ten minutes; [fresh]+ * asks GitHub again. Null when GitHub does not say, remembered a minute: the token then asks for TOKEN_PERMISSIONS alone. */+ private async granted(installationId: number, fresh = false): Promise<TokenPermissions | null> {+ const known = this.grants.get(installationId)+ if (!fresh && known && known.until > this.now()) return known.permissions+ let permissions: TokenPermissions | null = null+ try {+ const answer = await this.call('GET', `/app/installations/${installationId}`, `Bearer ${this.jwt()}`)+ if (answer.status === 401) throw this.misconfigured()+ const listed = (answer.body as Record<string, unknown>).permissions+ if (answer.status === 200 && listed && typeof listed === 'object' && !Array.isArray(listed)) {+ permissions = Object.fromEntries(Object.entries(listed as Record<string, unknown>)+ .filter((entry): entry is [string, 'read' | 'write'] => entry[1] === 'read' || entry[1] === 'write'))+ }+ } catch (error) {+ if (!(error instanceof GitHubAppError) || error.code === 'GITHUB_APP_MISCONFIGURED') throw error+ // GitHub did not answer: today's set, asked again next time.+ return null+ }+ if (this.grants.size >= 1000) this.grants.delete(this.grants.keys().next().value!)+ this.grants.set(installationId, { permissions, until: this.now() + (permissions ? INSTALLATION_TTL_MS : NOT_INSTALLED_TTL_MS) })+ return permissions+ }++ /** An agent's token's permissions on [installationId]: TOKEN_PERMISSIONS, and each of GRANTED_TOKEN_PERMISSIONS the+ * installation granted, at the lower of the two levels. */+ private async agentPermissions(installationId: number, fresh = false): Promise<TokenPermissions> {+ const granted = await this.granted(installationId, fresh)+ const permissions: Record<string, 'read' | 'write'> = { ...TOKEN_PERMISSIONS }+ for (const [name, wanted] of Object.entries(GRANTED_TOKEN_PERMISSIONS)) {+ const level = granted?.[name]+ if (level) permissions[name] = level === 'write' && wanted === 'write' ? 'write' : 'read'+ }+ return permissions+ }++ /**+ * A token for [repository] alone. With [permissions] given, those alone; without, an agent's token: TOKEN_PERMISSIONS and+ * what of GRANTED_TOKEN_PERMISSIONS its installation granted. A permission refusal of an agent's token reads the grant+ * again and asks once more when that changes what to ask for: an owner took a permission away within the ten minutes.+ */+ async createToken(installationId: number, repository: GitHubRepository, permissions?: TokenPermissions): Promise<{ token: string; expiresAt: string }> {+ if (permissions) return this.mint(installationId, repository, permissions)+ const asked = await this.agentPermissions(installationId)+ try {+ return await this.mint(installationId, repository, asked)+ } catch (error) {+ if (!(error instanceof GitHubAppError) || error.code !== 'GITHUB_APP_PERMISSIONS') throw error+ const now = await this.agentPermissions(installationId, true)+ if (samePermissions(asked, now)) throw error+ return this.mint(installationId, repository, now)+ }+ }++ private async mint(installationId: number, repository: GitHubRepository, permissions: TokenPermissions): Promise<{ token: string; expiresAt: string }> {const answer = await this.call('POST', `/app/installations/${installationId}/access_tokens`, `Bearer ${this.jwt()}`,{ repositories: [repository.name], permissions })const body = answer.body as Record<string, unknown>diff --git a/backend/src/github/fakeGitHub.ts b/backend/src/github/fakeGitHub.tsindex 72525306a..6fccdf850 100644--- a/backend/src/github/fakeGitHub.ts+++ b/backend/src/github/fakeGitHub.ts@@ -33,6 +33,9 @@ export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?:const comments = new Map<string, Array<{ id: number; user: { login: string }; author_association?: string; body: string; html_url: string }>>()/** Workflow runs by `owner/name`, lower case: each run's status and its jobs' statuses and runner labels. */const actions = new Map<string, Array<{ id: number; status: string; jobs: Array<{ status: string; labels: string[] }> }>>()+ /** Each installation's accepted permissions, by installation id, as GET /app/installations/{id} answers them. An+ * installation listed here refuses a token that asks for more, as GitHub does; one not listed answers 404 and mints any. */+ const grants = new Map<number, Record<string, 'read' | 'write'>>()const calls: FakeCall[] = []const issued = new Set<string>()const revoked: string[] = []@@ -77,9 +80,19 @@ export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?:const login = decodeURIComponent(match[1]!)return control.botId && login.endsWith('[bot]') ? json(200, { login, id: control.botId }) : json(404, { message: 'Not Found' })}+ if (method === 'GET' && (match = /^\/app\/installations\/(\d+)$/.exec(url.pathname))) {+ if (!jwtValid(auth)) return json(401, { message: 'Bad credentials' })+ const granted = grants.get(Number(match[1]))+ return granted ? json(200, { id: Number(match[1]), permissions: granted }) : json(404, { message: 'Not Found' })+ }if (method === 'POST' && (match = /^\/app\/installations\/(\d+)\/access_tokens$/.exec(url.pathname))) {if (!jwtValid(auth)) return json(401, { message: 'Bad credentials' })if (control.tokenStatus !== 201) return json(control.tokenStatus, { message: control.tokenMessage })+ const granted = grants.get(Number(match[1]))+ const asked = ((body as { permissions?: Record<string, string> }).permissions) ?? {}+ if (granted && Object.entries(asked).some(([name, level]) => !granted[name] || (level === 'write' && granted[name] !== 'write'))) {+ return json(422, { message: 'The permissions requested are not granted to this installation.' })+ }const token = `ghs_fixture_${++minted}`issued.add(token)permissions.set(token, (body as { permissions: unknown }).permissions)@@ -146,7 +159,7 @@ export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?:}return json(404, { message: 'Not Found' })}) as typeof globalThis.fetch- return { fetch, calls, installed, owners, renamed, protection, pulls, checkRuns, checkSuites, reviews, comments, revoked, issued, control, actions, permissions }+ return { fetch, calls, grants, installed, owners, renamed, protection, pulls, checkRuns, checkSuites, reviews, comments, revoked, issued, control, actions, permissions }}/** A configured app talking to [github]. */diff --git a/backend/src/github/tokens.test.ts b/backend/src/github/tokens.test.tsindex 59b60d7ad..c714e4e55 100644--- a/backend/src/github/tokens.test.ts+++ b/backend/src/github/tokens.test.ts@@ -34,6 +34,19 @@ describe('preparation tokens', () => {})})+// Task #2755: an agent's task token carries workflows and issues where its installation granted them; preparation never does.+describe('agent tokens and the installation\'s grant', () => {+ it('carry workflows and issues where granted, and the preparation token stays read-only', async () => {+ const { tokens, github } = setup()+ github.grants.set(77, { contents: 'write', pull_requests: 'write', checks: 'read', actions: 'read', metadata: 'read', workflows: 'write', issues: 'write' })+ await tokens.prepare(repository)+ await tokens.issue(request())+ const minted = github.calls.filter(c => c.path.endsWith('/access_tokens')).map(c => c.body)+ expect(minted).toEqual([{ repositories: ['app'], permissions: { contents: 'read', metadata: 'read' } },+ { repositories: ['app'], permissions: { contents: 'write', pull_requests: 'write', checks: 'read', actions: 'read', metadata: 'read', workflows: 'write', issues: 'write' } }])+ })+})+// A repository renamed on GitHub (2026-10-27: autonomous-harness → openharness): the project keeps the old name, which// GitHub still answers for git, and the app is installed on the repository under its new one.describe('a repository renamed on GitHub', () => {diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 564adae5b..92f55d98b 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -54,6 +54,7 @@ import { askBuddyModel, buddyModelResult, sendBuddyHome, sessionModel } from './import { launchRefusedLine, leadArrived, LEAD_CLAIM_MS, leadJoined, leadOvertaken, leadStartFailed, leadStarting, leadHost, leadWaits, LEAD_CAPABILITY, placeLead } from './leadStart.js'import { appendRouting, coordinatorNameOf, routingSummary, FIRST_INSTRUCTIONS, FIRST_SUMMARY, instructionsHash, instructionsTextSchema, legacyRoleName, liveNotes, MAX_NOTES, noteTextSchema, roleNameSchema, summarySchema, type PmNote } from './instructions.js'import { INSTRUCTIONS_TEMPLATE } from './instructionsTemplate.js'+import { BUILT_IN_HEADING } from './pmSchedule.js'import { placeAfter, queueSiblings } from './taskQueue.js'const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)@@ -1714,6 +1715,11 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,if (!command.askedBy) fail('ASKED_BY_REQUIRED', 'Name the member who asked for this change (askedBy).', 400)}const askedBy = command.askedBy ? askedByOf(state, project, command.askedBy) : (actor as Extract<Actor, { kind: 'person' }>).userId+ // The Swarm adds the built-in PM schedule to every coordinator's read (pmSchedule.ts); one copied into the document would+ // be read twice, and go stale when the built-in one changes. Refused out loud, never stripped.+ if (command.text.split('\n').some(line => line.trim() === BUILT_IN_HEADING)) {+ fail('INSTRUCTIONS_BUILT_IN', 'Remove the "Built-in PM schedule" section: the Swarm adds it to every read, so it is never saved in the document.', 400)+ }const current = project.instructionsRevision ?? 0if (command.baseRevision !== current) {// Refused with the text it missed, to merge and save again (design, Concurrency): never two writers' texts kept silently.diff --git a/backend/src/superTabs/digest.ts b/backend/src/superTabs/digest.tsindex 73e06cf48..ce112cc9f 100644--- a/backend/src/superTabs/digest.ts+++ b/backend/src/superTabs/digest.ts@@ -15,7 +15,7 @@ const IN_PROGRESS: Record<string, string> = { planned: 'planned', working: 'workconst HELD_UP: Record<string, string> = { blocked: 'stuck', lost: 'lost', needs_human: 'waits for a person' }/** The project's local date and time ("2026-10-27", "08:00") at `now`. */-function localNow(timeZone: string, now: number): { date: string; time: string } {+export function localNow(timeZone: string, now: number): { date: string; time: string } {const parts = Object.fromEntries(new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit',minute: '2-digit', hourCycle: 'h23' }).formatToParts(now).map(p => [p.type, p.value]))return { date: `${parts.year}-${parts.month}-${parts.day}`, time: `${parts.hour}:${parts.minute}` }diff --git a/backend/src/superTabs/liveness.test.ts b/backend/src/superTabs/liveness.test.tsindex 342da3cb1..9d30e47f6 100644--- a/backend/src/superTabs/liveness.test.ts+++ b/backend/src/superTabs/liveness.test.ts@@ -3,6 +3,7 @@ import type { AgentStart, Assignment, SuperTabState } from './model.js'import { changesRequested, LEASE_MS, loseTasks, nextLossAt, QUIET_RUNNING_MS, renewOwnTask, revisionReady, sweepForLead, sweepLiveness, waitingForReview } from './liveness.js'import { MACHINE_FRESH_MS, startPreparing } from './machines.js'import { split } from './parts/index.js'+import { stepsFixture } from './steps.test-support.js'const MINUTE = 60_000const assignment = (patch: Partial<Assignment> = {}): Assignment => ({ id: 'a1', agentId: 'w', status: 'working', result: null,@@ -665,3 +666,37 @@ describe('the next time a machine\'s worker can lose its task (DB 2.5)', () => {expect(nextLossAt(idle, 'm')).toBeUndefined()})})++// Diego, 2026-11-04 (task #2693): the project chat's thread replies are the only task state the chat shows (#2704), but a task+// lost outside any command (the sweep, a machine's report, its Lead's poll) never said Stuck there: the thread kept saying On it.+describe('a task lost outside any command says Stuck in its project-chat thread', () => {+ const lost = () => {+ const f = stepsFixture()+ const root = f.group(f.task).cards!.line!.messageId+ const worker = f.state.agents.find(a => a.id === f.dev)!+ const text = `Stuck: ${worker.displayName ?? worker.name} stopped. Next: another engineer takes it over.`+ const replies = (rows: ReturnType<typeof sweepLiveness>) => rows.filter(r => r.conversationId === f.group(f.task).cards!.line!.conversationId)+ f.tick(120 * MINUTE)+ return { f, root, text, replies }+ }++ it('through the sweep: exactly one reply, in the task\'s thread, as its coordinator', () => {+ const { f, root, text, replies } = lost()+ const rows = sweepLiveness(f.state, f.now)+ expect(f.group(f.task).assignment!.status).toBe('lost')+ expect(replies(rows)).toEqual([expect.objectContaining({ text, replyTo: root, thread: root, recipients: [],+ author: expect.objectContaining({ kind: 'agent', id: f.lead }), source: expect.objectContaining({ kind: 'system' }) })])+ })++ it('through the Lead\'s poll', () => {+ const { f, root, text, replies } = lost()+ expect(replies(sweepForLead(f.state, f.now))).toEqual([expect.objectContaining({ text, replyTo: root, thread: root })])+ })++ it('once when an alert loses it inside a command', () => {+ const { f, root, text } = lost()+ const rows = f.run({ type: 'agent.alert', agentId: f.dev, alert: 'limit', active: true }, f.as(f.dev)).messages+ expect(f.group(f.task).assignment!.status).toBe('lost')+ expect(rows.filter(r => r.thread === root && r.text.startsWith('Stuck:'))).toEqual([expect.objectContaining({ text })])+ })+})diff --git a/backend/src/superTabs/liveness.ts b/backend/src/superTabs/liveness.tsindex 8b8ddd0eb..d6bd684aa 100644--- a/backend/src/superTabs/liveness.ts+++ b/backend/src/superTabs/liveness.ts@@ -13,6 +13,7 @@ import { ledProject, projectsOf } from './projects.js'import { coordinatorNameOf } from './instructions.js'import { waitedOn } from './leaderboard/record.js'import { isStep } from './steps.js'+import { endedReply } from './taskLine.js'// Work never sits with a dead owner (design: "A Swarm that never stops", 2026-10-26). A worker's active assignment is held// by a lease that its progress renews. A dead, stalled or limited worker loses it within minutes: the assignment becomes@@ -323,7 +324,9 @@ function loseTask(state: SuperTabState, group: Conversation, worker: Agent, reasreturn [...leadNoticeRows(toLead(state, worker, { id: stableId('work-lost', assignment.id, loss), conversationId: group.id, author: sender, replyTo: null,recipients: [], text: wake, source }).map(row => reachable(state, row))),reachable(state, { id: stableId('work-lost', assignment.id, loss, 'agent'), conversationId: group.id, author: sender, replyTo: null, recipients: [worker.id], source,- text: `Your task "${group.title}" moved: ${reason}. Stop working on it; your status and results for it are no longer accepted.` })]+ text: `Your task "${group.title}" moved: ${reason}. Stop working on it; your status and results for it are no longer accepted.` }),+ // And its project chat's thread says Stuck, as no command saw the loss (task #2693).+ ...endedReply(state, group, stableId('task-line-lost', assignment.id, loss), sender)]}/** Loses at once the tasks of the workers `which` picks that have a reason now: an agent that just reported a usage limit,diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex 9db793b37..fd5984eed 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -603,6 +603,8 @@ export const NOTICE_READERS = {// idleNotices, commands.ts work.check; project instructions, phase 4). `idle-stop` rows are from before.idle: 'recipients', 'review-failed': 'recipients','update-request': 'recipients', 'digest-request': 'recipients', overlap: 'recipients',+ // The coordinator's wake for its built-in schedule (pmSchedule.ts).+ 'schedule-request': 'recipients',// Two agents that may be talking in a loop, told to the coordinator (commands.ts pairLoop, project instructions phase 1).'pair-loop': 'recipients',// The server's routine notices to the coordinator, gathered into one message (noticeDigest.ts).diff --git a/backend/src/superTabs/pmSchedule.test.ts b/backend/src/superTabs/pmSchedule.test.tsnew file mode 100644index 000000000..7a4814be4--- /dev/null+++ b/backend/src/superTabs/pmSchedule.test.ts@@ -0,0 +1,100 @@+import { describe, expect, it } from 'vitest'+import type { Agent, Assignment, Conversation, SuperTabState, WorkStatus } from './model.js'+import { BUILT_IN_HEADING, PM_SCHEDULE_TEXT, SCHEDULE_SLOT_MS, scheduleMessageId, scheduleRequest, scheduleSlot } from './pmSchedule.js'+import { ARCHIVE_QUIET_MS } from './tidy.js'++/** 10:00 on 4 November in Vietnam (03:00 UTC): a slot's first millisecond. */+const T = Date.UTC(2026, 10, 4, 3, 0)+const SLOT = T / SCHEDULE_SLOT_MS++const agent = (id: string): Agent => ({ id, name: id, contributorId: 'owner', membershipGeneration: 'g', machineId: 'mac', harnessId: `h-${id}`,+ machineOwnerId: 'owner', configuration: { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null } } as unknown as Agent)+const work = (status: WorkStatus, over: Partial<Assignment> = {}): Assignment => ({ id: `w-${status}`, agentId: 'eng', status,+ configuration: { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null },+ execution: { machineId: 'mac', harnessId: 'h-eng', machineOwnerId: 'owner' }, result: null, progressAt: T, ...over })+const task = (number: number, assignment: Assignment | null, over: Partial<Conversation> = {}): Conversation => ({ id: `g${number}`,+ projectId: 'p1', number, title: `Task ${number}`, leadId: 'lead', agentIds: ['lead', 'eng'], archived: false, brief: 'Do it.', checks: [],+ assignment, lastMessageSequence: 1, lastActivityAt: new Date(T).toISOString(), ...over })++/** One project whose coordinator is `lead`, with the given work groups. */+function swarm(...groups: Conversation[]): SuperTabState {+ return {+ version: 1, id: 'tab', name: 'Swarm', ownerId: 'owner', environment: 'prod', paused: false, invitations: [],+ people: [{ id: 'owner', email: '[email protected]', role: 'owner', generation: 'g' }] as SuperTabState['people'],+ agents: [agent('lead'), agent('eng')],+ projects: [{ id: 'p1', name: 'lampOS', ownerId: 'owner', leadConversationId: 'lead-p1', visibility: 'public', members: [], updateMinutes: 5 }],+ conversations: [{ ...task(0, null), id: 'lead-p1', number: undefined, title: 'Lead' }, ...groups],+ } as SuperTabState+}+const lead = (state: SuperTabState) => state.agents.find(a => a.id === 'lead')!+const wake = (state: SuperTabState, now = T) => scheduleRequest(state, lead(state), now)++describe('the built-in PM schedule', () => {+ it('is due once per slot, from the slot\'s first millisecond', () => {+ const state = swarm(task(1, null))+ expect(scheduleSlot(T)).toBe(SLOT)+ expect(wake(state)).toMatchObject({ slot: SLOT, draft: { id: scheduleMessageId('tab', 'p1', SLOT) } })+ state.projects![0]!.schedule = { lastSlot: SLOT }+ expect(wake(state, T + SCHEDULE_SLOT_MS - 1)).toBeNull()+ expect(wake(state, T + SCHEDULE_SLOT_MS)).toMatchObject({ slot: SLOT + 1 })+ })++ it('records nothing and sends nothing when there is nothing to sweep, so the slot stays due', () => {+ const state = swarm(task(1, work('working')))+ expect(wake(state)).toBeNull()+ // Something to sweep later in the same slot still wakes the coordinator once.+ state.conversations.push(task(2, null))+ expect(wake(state)).toMatchObject({ slot: SLOT, draft: { id: scheduleMessageId('tab', 'p1', SLOT) } })+ })++ it.each([+ ['an unassigned task', task(1, null)],+ ['a task whose agent is lost', task(1, work('lost', { lost: { reason: 'offline', at: T } }))],+ ['a task waiting on a person', task(1, work('needs_human'))],+ ['a stuck task', task(1, work('blocked'))],+ ['a finished task with no pull request, quiet long enough', task(1, work('done'), { lastActivityAt: new Date(T - ARCHIVE_QUIET_MS).toISOString() })],+ ])('wakes the coordinator for %s', (_name, group) => {+ expect(wake(swarm(group))!.draft).toMatchObject({ source: { kind: 'schedule-request' } })+ })++ it.each([+ ['a finished task with a pull request', task(1, work('done'), { lastActivityAt: new Date(T - ARCHIVE_QUIET_MS).toISOString(),+ pullRequestUrls: ['https://github.com/example/lampos/pull/1'] })],+ ['a finished task quiet for less than the archive wait', task(1, work('done'), { lastActivityAt: new Date(T - ARCHIVE_QUIET_MS + 1).toISOString() })],+ ['a step with no agent', task(2, null, { reviewOf: 'g9', step: 'Review' })],+ ['an archived task', task(1, null, { archived: true })],+ ])('does not wake it for %s', (_name, group) => {+ expect(wake(swarm(group))).toBeNull()+ })++ it('does not wake it for a finished group the Swarm would not archive either: tidying off, or a step whose task is still open', () => {+ const quiet = { lastActivityAt: new Date(T - ARCHIVE_QUIET_MS).toISOString() }+ const off = swarm(task(1, work('done'), quiet))+ off.tidy = false+ expect(wake(off)).toBeNull()+ const step = swarm(task(1, work('working')), task(2, work('done'), { ...quiet, reviewOf: 'g1', step: 'Plan' }))+ expect(wake(step)).toBeNull()+ })++ it('sends nothing and records nothing in a paused Swarm, or for an agent that leads nothing', () => {+ const state = swarm(task(1, null))+ expect(scheduleRequest(state, state.agents.find(a => a.id === 'eng')!, T)).toBeNull()+ state.paused = true+ expect(wake(state)).toBeNull()+ })++ it('names the time in the project\'s zone, to the coordinator alone', () => {+ const draft = wake(swarm(task(1, null)))!.draft!+ expect(draft.text.startsWith('Built-in schedule, 10:00 (Asia/Ho_Chi_Minh). This is a scheduled request from the Swarm, not a new task.')).toBe(true)+ expect(draft.text).toContain('Skip a job your project\'s instructions schedule on their own clock.')+ // On its own, for a coordinator whose CLI predates the built-in section.+ expect(draft.text).toContain('Set no timer of your own')+ expect(draft).toMatchObject({ conversationId: 'lead-p1', recipients: ['lead'], source: { kind: 'schedule-request', projectId: 'p1', slot: SLOT } })+ })++ it('says in its own section that the Swarm runs it and that it is never saved', () => {+ expect(PM_SCHEDULE_TEXT.startsWith(`${BUILT_IN_HEADING}\n`)).toBe(true)+ expect(PM_SCHEDULE_TEXT).toContain('Set no timer of your own')+ expect(PM_SCHEDULE_TEXT).toContain('never save it into the document')+ })+})diff --git a/backend/src/superTabs/pmSchedule.ts b/backend/src/superTabs/pmSchedule.tsnew file mode 100644index 000000000..f518b1dd9--- /dev/null+++ b/backend/src/superTabs/pmSchedule.ts@@ -0,0 +1,81 @@+import { author, stableId, type Agent, type Conversation, type MessageDraft, type SuperTabState } from './model.js'+import { ledProject, projectsOf, type SwarmProject } from './projects.js'+import { workOver } from './decisions.js'+import { digestOf, localNow } from './digest.js'+import { DEFAULT_TIME_ZONE } from './costs/reflection.js'+import { taskLiveness } from './liveness.js'+import { archivable } from './tidy.js'++// Every project's coordinator runs the same built-in schedule, woken by the Swarm on its own poll instead of a timer of its+// own (Ken, 2026-11-04; docs/plans/2026-11-04-pm-built-in-schedule-design.md): a Codex PM may have no timer, and a restart+// lost one. A line in the project's own instructions about the same job wins; the coordinator, which reads both, judges that.++/** The heading of the built-in section, which no saved document may hold (commands.ts instructions.save). */+export const BUILT_IN_HEADING = '## Built-in PM schedule (from the Swarm)'++/** What the coordinator reads after its project's instructions (store.ts instructions, cli swarmInstructionsSkill.ts). */+export const PM_SCHEDULE_TEXT = `${BUILT_IN_HEADING}++The Swarm wakes you for these jobs with a message that names them. Set no timer of your own for them, and delete one you set+before. A line in this project's instructions above about the same job wins: follow it, and skip that job when the Swarm's+message names it. This section is not part of the project's document: never save it into the document.++- Every 30 minutes, the open-task sweep: every open task, the unassigned and "To do" ones included, ends it with an owner+ working on it, a question to a person by name with a default and a time, or a close with its reason. A task waiting on a+ person gets that person asked by name, with a default and a time. Ask no agent whether it is stalled: \`mine\` and the+ task's thread show it. Then archive every finished group the Swarm left open: one with no pull request linked, which the+ auto-archive never takes.+- When the Swarm says a task's agent is lost, the task goes to a new agent with its pushed branch. When it says a task is+ stalled, read the task's thread first, and send it back to its agent only when the thread shows it waits on nothing (a+ review, CI, a person). When it says an agent is idle, stop it unless work is coming for it.`++/** The schedule's clock: slot n starts at n * 30 minutes, in UTC. */+export const SCHEDULE_SLOT_MS = 30 * 60_000+export const scheduleSlot = (now: number): number => Math.floor(now / SCHEDULE_SLOT_MS)+export const scheduleMessageId = (tabId: string, projectId: string, slot: number): string => stableId('schedule', tabId, projectId, String(slot))++const isLead = (state: SuperTabState, group: Conversation) => projectsOf(state).some(p => p.leadConversationId === group.id)+const inProject = (group: Conversation, projectId: string) => (group.projectId ?? 'lead') === projectId++/** Whether the sweep has anything to do among the loaded groups: a task no agent is moving (none assigned, its agent lost, or+ * it waits on a person or is stuck), or a finished group the Swarm may archive (tidy.ts archivable: tidying on, its step's+ * task ended) that the auto-archive never takes, since neither it nor, for a step, its task links a pull request. A task an+ * agent is working on is the stalled and lost notices' (liveness.ts). Steps belong to their task's Engineer. */+export function sweepDue(state: SuperTabState, projectId: string, now: number): boolean {+ return state.conversations.some(group => {+ if (group.kind || group.audience || group.archived || !inProject(group, projectId) || isLead(state, group)) return false+ if (workOver(state, group)) {+ const task = group.reviewOf ? state.conversations.find(c => c.id === group.reviewOf) : undefined+ return archivable(state, group, now) && !group.pullRequestUrls?.length && !task?.pullRequestUrls?.length+ }+ if (group.reviewOf) return false+ if (!group.assignment) return true+ const liveness = taskLiveness(state, group, now)+ return liveness?.state === 'orphaned' || (liveness?.state === 'waiting' && (liveness.why === 'person' || liveness.why === 'blocked'))+ })+}++/** The wake's words: the slot's local time, the job due, and that the project's own schedule wins. */+export function scheduleText(project: SwarmProject, slot: number): string {+ const zone = digestOf(project)?.timeZone ?? DEFAULT_TIME_ZONE+ return [`Built-in schedule, ${localNow(zone, slot * SCHEDULE_SLOT_MS).time} (${zone}). This is a scheduled request from the Swarm, not a new task.`,+ '- Open-task sweep: every open task ends with an owner, a question to a person with a default and a time, or a close with its reason; '+ + 'then archive the finished groups the Swarm left open (see the built-in PM schedule in your instructions).',+ // Said here too: a CLI older than the built-in section shows its PM only this message.+ 'Skip a job your project\'s instructions schedule on their own clock. Set no timer of your own for this one, and delete one you set before.'].join('\n')+}++/** The coordinator's slot and its wake, when a slot is due and the sweep has something to do. Null otherwise, and then nothing+ * is recorded: a slot written with no wake would move the Swarm's head, and every reader's copy, each 30 minutes while+ * nothing happened (#2946 review, 1), so the slot stays due and the next poll checks again, in memory over the loaded state.+ * Null too in a paused Swarm, which stays due until it resumes, or for an agent that leads no project. The caller records+ * the slot in the poll's own write, and sends nothing while its last wake is still unread (store.ts). */+export function scheduleRequest(state: SuperTabState, target: Agent, now: number): { slot: number; draft: MessageDraft } | null {+ if (state.paused) return null+ const project = ledProject(state, target.id)+ const slot = scheduleSlot(now)+ if (!project || slot <= (project.schedule?.lastSlot ?? -1) || !sweepDue(state, project.id, now)) return null+ return { slot, draft: { id: scheduleMessageId(state.id, project.id, slot), conversationId: project.leadConversationId,+ author: author(state, { kind: 'agent', agentId: target.id, machineOwnerId: target.machineOwnerId }), text: scheduleText(project, slot),+ replyTo: null, recipients: [target.id], source: { kind: 'schedule-request', projectId: project.id, slot } } }+}diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.tsindex 91ff838ea..1efcfffc2 100644--- a/backend/src/superTabs/projects.ts+++ b/backend/src/superTabs/projects.ts@@ -43,6 +43,10 @@ export interface SwarmProject {digest?: { time: string; timeZone: string; lastOn?: string; lastAt?: number }/** A person turned the digest off (project.digest with time null), so the default is not filled in again. */digestOff?: true+ /** The last 30-minute slot of the built-in PM schedule in which its coordinator's poll found something to sweep+ * (pmSchedule.ts), woken or held back, and the message that last carried a wake (its own, an update request or a notice+ * digest): no new wake while that one is unread. A slot with nothing to sweep is not written. Readers never get it. */+ schedule?: { lastSlot: number; wakeId?: string }/** The status card at the top of the project chat (Dee, 2026-10-31): the coordinator's last project.report text, which* replaces the one before and posts nothing. Read exactly by those who read the project chat (model.ts visibleState). */status?: ProjectStatus | nulldiff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.tsindex 32bdc521a..755fa1d29 100644--- a/backend/src/superTabs/read/contract.ts+++ b/backend/src/superTabs/read/contract.ts@@ -274,7 +274,10 @@ export interface HostAgentRow {roleName: string/** Its project's instructions as the state names them: the host reads the text when `revision` moves. Revision 0 (no* `hash`): no document yet, so the built-in template. */- instructions: { projectId: string; revision: number; hash: string | null; coordinatorName: string } | null+ instructions: { projectId: string; revision: number; hash: string | null; coordinatorName: string+ /** The coordinator's alone: the built-in PM schedule's hash (pmSchedule.ts), which its read carries beside the text. The host+ * reads again when it moves, as it does for `revision`. */+ builtInHash?: string } | nulllead: boolean/** New: lets the host decide what it may read without a full Swarm read. */leadsConversationId: string | nulldiff --git a/backend/src/superTabs/read/hostRows.ts b/backend/src/superTabs/read/hostRows.tsindex c278c86d0..03ffafc22 100644--- a/backend/src/superTabs/read/hostRows.ts+++ b/backend/src/superTabs/read/hostRows.ts@@ -10,7 +10,11 @@ import { hostLocalGrid, machineContribution, type MachineCleanup } from '../machimport { agentProjectId, agentSetRole, canWatchAgent, isConfidential, groupProject, ledProject, projectsOf, skillModeOf, startProject, skillSetOf, watchClosed } from '../projects.js'import type { HostAgentRow, HostPool, HostRosterRow, HostTabRows } from './contract.js'import { hostEtag } from './hostEtag.js'-import { coordinatorNameOf, FIRST_INSTRUCTIONS, roleNameOf } from '../instructions.js'+import { coordinatorNameOf, FIRST_INSTRUCTIONS, instructionsHash, roleNameOf } from '../instructions.js'+import { PM_SCHEDULE_TEXT } from '../pmSchedule.js'++/** The built-in PM schedule's hash, once: it changes only with a backend release. */+const BUILT_IN_HASH = instructionsHash(PM_SCHEDULE_TEXT)export interface HostLookups {/** The Swarm's people with their account emails (observers). */@@ -86,7 +90,7 @@ function agentRow(tabId: string, state: SuperTabState, machineId: string, user:// running daemons read the text again (2026-11-02: agents kept the old routing after #2495, as revision 0 never moves).instructions: home ? { projectId: home.id, revision: home.instructionsRevision ?? 0,hash: home.instructionsHash ?? (home.instructionsRevision ? null : FIRST_INSTRUCTIONS.instructionsHash),- coordinatorName: coordinatorNameOf(home) } : null,+ coordinatorName: coordinatorNameOf(home), ...ledProject(state, target.id)?.id === home.id ? { builtInHash: BUILT_IN_HASH } : {} } : null,...(custom ? { role: chosen && { ...chosen, projectId: custom.id } } : {}),lead: !!ledProject(state, target.id),// Removed (model.ts leadsRemoved); an older CLI still reads the field, so it stays, always empty.diff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.tsindex f8549a903..28559849b 100644--- a/backend/src/superTabs/read/views.ts+++ b/backend/src/superTabs/read/views.ts@@ -93,8 +93,9 @@ export function readerView(parts: SwarmParts, actor: Actor, now: number, extras:const part = <T>(list: Part<T>[]) => { const keyed = new Map(list.map(p => [p.key, p])); return (key: string) => keyed.get(key)! }const agentPart = part(parts.agents), groupPart = part(parts.groups), machinePart = part(parts.machines), startPart = part(parts.starts)const head = Object.fromEntries(HEAD_FIELDS.filter(field => visible[field] !== undefined).map(field => [field, visible[field]])) as HeadView- // Every project names its coordinator; one from before the field reads as the Product Manager (instructions.ts).- if (head.projects) head.projects = head.projects.map(({ progress: _progress, ...project }) => ({ ...project, coordinatorName: coordinatorNameOf(project) }))+ // Every project names its coordinator; one from before the field reads as the Product Manager (instructions.ts). The built-in+ // schedule's slot is the coordinator poll's bookkeeping (pmSchedule.ts), like progress: no reader shows it.+ if (head.projects) head.projects = head.projects.map(({ progress: _progress, schedule: _schedule, ...project }) => ({ ...project, coordinatorName: coordinatorNameOf(project) }))head.invitations = visible.invitations.filter(i => readable.has(i.conversationId))const projects = new Set((visible.projects ?? []).map(p => p.id)), seen = seenMachineIds(visible), names = swarmUsernames(state)const buddy = isBuddyReader(state, actor)diff --git a/backend/src/superTabs/steps.test-support.ts b/backend/src/superTabs/steps.test-support.tsnew file mode 100644index 000000000..5aa850b15--- /dev/null+++ b/backend/src/superTabs/steps.test-support.ts@@ -0,0 +1,31 @@+/**+ * A task with its PM and Engineer, opened through commands as a Swarm opens one (steps.test.ts): shared by the tests that run+ * commands and sweeps on it (liveness.test.ts), so importing it never runs another file's tests.+ */+import { applyCommand, type Command, type CommandContext } from './commands.js'+import { createSuperTab, type Actor, type AgentConfiguration } from './model.js'++export const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }+const config: AgentConfiguration = { engine: 'codex', model: 'test-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }++export function stepsFixture() {+ let state = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')+ let sequence = 0, now = 1000+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {+ const effects = applyCommand(state, actor, command, { now, operationId: `op-${++sequence}`, ...context })+ state = effects.state+ return effects+ }+ const add = (harnessId: string, group = 'lead', lead = false) => run({ type: 'agent.add', conversationId: group, machineId: 'host', harnessId,+ name: harnessId, configuration: config, lead }, owner, { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }).result.agentId as string+ const as = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'host-owner' })+ const lead = add('pm', 'lead', true)+ const task = run({ type: 'conversation.create', title: 'Fix login', brief: 'Sign in works offline.',+ checks: [{ description: 'Signs in offline', independent: true }] }, as(lead)).result.conversationId as string+ const dev = add('dev', task)+ run({ type: 'work.assign', conversationId: task, agentId: dev }, as(lead))+ const step = (name: string, actor: Actor = as(dev), on = task, checks: Array<{ description: string; independent: boolean }> = []) =>+ run({ type: 'conversation.create', title: name, brief: `${name} it.`, reviewOf: on, step: name, checks } as Command, actor).result.conversationId as string+ const group = (id: string) => state.conversations.find(c => c.id === id)!+ return { run, add, as, lead, task, dev, step, group, tick: (ms: number) => { now += ms }, get now() { return now }, get state() { return state } }+}diff --git a/backend/src/superTabs/steps.test.ts b/backend/src/superTabs/steps.test.tsindex 250d15f1a..2451d2a4c 100644--- a/backend/src/superTabs/steps.test.ts+++ b/backend/src/superTabs/steps.test.ts@@ -4,39 +4,15 @@* readers show it inside its task. No step name means anything to the server.*/import { describe, expect, it } from 'vitest'-import { applyCommand, PAIR_CHAIN_LIMIT, type Command, type CommandContext } from './commands.js'-import { agent, createSuperTab, type Actor, type AgentConfiguration } from './model.js'+import { PAIR_CHAIN_LIMIT, type Command } from './commands.js'+import { agent, type Actor } from './model.js'import { extracted } from './parts/write.js'+import { owner, stepsFixture } from './steps.test-support.js'import { stepEndedRows, stepSleeps } from './steps.js'import { reportedAs } from './projectUpdates.js'import { idleNotices } from './tidy.js'import { QUIET_RUNNING_MS, sweepForLead, sweepLiveness } from './liveness.js'-const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }-const config: AgentConfiguration = { engine: 'codex', model: 'test-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }--export function stepsFixture() {- let state = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')- let sequence = 0, now = 1000- const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {- const effects = applyCommand(state, actor, command, { now, operationId: `op-${++sequence}`, ...context })- state = effects.state- return effects- }- const add = (harnessId: string, group = 'lead', lead = false) => run({ type: 'agent.add', conversationId: group, machineId: 'host', harnessId,- name: harnessId, configuration: config, lead }, owner, { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }).result.agentId as string- const as = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'host-owner' })- const lead = add('pm', 'lead', true)- const task = run({ type: 'conversation.create', title: 'Fix login', brief: 'Sign in works offline.',- checks: [{ description: 'Signs in offline', independent: true }] }, as(lead)).result.conversationId as string- const dev = add('dev', task)- run({ type: 'work.assign', conversationId: task, agentId: dev }, as(lead))- const step = (name: string, actor: Actor = as(dev), on = task, checks: Array<{ description: string; independent: boolean }> = []) =>- run({ type: 'conversation.create', title: name, brief: `${name} it.`, reviewOf: on, step: name, checks } as Command, actor).result.conversationId as string- const group = (id: string) => state.conversations.find(c => c.id === id)!- return { run, add, as, lead, task, dev, step, group, tick: (ms: number) => { now += ms }, get now() { return now }, get state() { return state } }-}-describe('opening a step', () => {it('opens on a task of its project, numbered, its opener in the task', () => {const f = stepsFixture()diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 3eafceacf..813a9aa7c 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -54,6 +54,7 @@ import { moveChatMark } from './read/threadMarkSeeds.js'import { closedAgents, nextRemovalAt, removeClosedAgents, reopened, restoreRefusal, restoreSessions } from './closedAgents.js'import { sessionRows } from './memberRows.js'import { failRefusedStarts, judgedMachines, loseTasks, nextLossAt, sweepForLead, sweepLiveness, SWEEP_EVERY_MS, unpurgedNotice } from './liveness.js'+import { endedReply, taskLineChats } from './taskLine.js'import { archivable, archiveLine, archiveWaitsFor, idleNotices, reviewClosable, reviewCloseLine, reviewPullRequests, type SettledPullRequest } from './tidy.js'import { clock, insertParts, loadActive, loadGroups, loadLightGroups, loadMachineParts, loadObserved, reassemble, split, type GroupData, type HeadData, type MachineData, type Part, type SwarmParts } from './parts/index.js'import { groupsBy, listingDrops, quietSince, readBy, withoutHints } from './parts/indexed.js'@@ -80,6 +81,7 @@ import { STATUS_LABELS,import { QUIET_CLAIM, type HoldReason } from './holdReason.js'import { stuck } from './deliverySettle.js'import { digestIsDue, digestMessage, digestText, doneRow, endedAlert, GATHERED_LIMIT_MS, gatheredNotice, NOTICE_DIGEST_MAX, noticeLine } from './noticeDigest.js'+import { PM_SCHEDULE_TEXT, scheduleRequest } from './pmSchedule.js'import { agentDisplayName } from './agentNames.js'import { endedHolds, HOLDING, startedHolds, type WorkHold } from '../github/holds.js'import { accrueLent, addLent, lentAgents, lentProjects } from './leaderboard/lent.js'@@ -2440,8 +2442,11 @@ export class SuperTabStore {if (revision && stored?.revision !== revision) fail('INSTRUCTIONS_UNAVAILABLE', 'This project\'s instructions cannot be read now. Try again in a moment.', 503)const notes = buddy ? undefined : liveNotes(await readNotes(tx, tabId, projectId), this.now()).map(n => ({ id: n.id, text: n.text, askedBy: n.askedBy, at: new Date(n.at), expiresAt: n.expiresAt === null ? null : new Date(n.expiresAt) }))+ // The built-in PM schedule, beside the document and never in it: to the project's coordinator alone (pmSchedule.ts).+ const coordinator = actor.kind === 'agent' && ledProject(state, actor.agentId)?.id === project.idreturn { projectId, revision, hash: stored ? stored.hash : FIRST_INSTRUCTIONS.instructionsHash, text: stored?.text ?? INSTRUCTIONS_TEMPLATE, template: !stored,- coordinatorName: coordinatorNameOf(project), notesRevision: project.notesRevision ?? 0, ...(notes ? { notes } : {}) }+ coordinatorName: coordinatorNameOf(project), notesRevision: project.notesRevision ?? 0, ...(notes ? { notes } : {}),+ ...(coordinator ? { builtIn: PM_SCHEDULE_TEXT } : {}) }})}@@ -3305,6 +3310,11 @@ export class SuperTabStore {...back.length ? await loadGroups(tx, tabId, 'key', { key: { $in: back.flatMap(r => [...r.groupIds, ...r.leadOf]) } }) : []]loaded = loadedFrom(row, { ...observed, groups: [...new Map([...observed.groups, ...more].map(g => [g.key, g])).values()] })}+ // A task this report may lose says Stuck in its project chat's thread (taskLine.ts endedReply, task #2693): a chat the+ // reads above left out is read too. None today: loadObserved reads every project chat.+ const lines = taskLineChats(loaded.state)+ if (lines.length) loaded = loadedFrom(row, { ...observed, groups: [...new Map([...loaded.parts.groups,+ ...await loadGroups(tx, tabId, 'key', { key: { $in: lines } })].map(g => [g.key, g])).values()] })const state = cloneData(loaded.state)await this.hostFor(tx, user, machineId, owned, state)const pool = await strangerRefusal(state, user.sub, () => {@@ -3615,6 +3625,8 @@ export class SuperTabStore {asked = await waitingInProject(tx, tabId, led.id)for (const id of [...finished.map(g => g.key), ...asked.map(d => d.conversationId)]) groupIds.add(id)}+ // A task its sweep may lose says Stuck in its project chat's thread (taskLine.ts endedReply, task #2693).+ for (const id of taskLineChats(loaded.state)) groupIds.add(id)// One load for both: a second would drop the first's groups.if (groupIds.size) loaded = await this.ensure(tx, loaded, { groupIds: [...groupIds] })const state = cloneData(loaded.state)@@ -3649,18 +3661,24 @@ export class SuperTabStore {woken = true}}+ // Whether this poll's update request is new, so lines may go into it: one already stored keeps its row as it is, with+ // none of them (writeMessages keepStored). Read once, for the digest and the schedule both.+ let updateFresh: boolean | undefined+ const updateOpen = async () => woken && (updateFresh ??= !await tx.superTabMessage.findUnique({ where: { id: update!.id }, select: { id: true } }))+ let digestDraft: MessageDraft | undefinedif (notices.length) {// After this page's cancels, before its rows are marked: all that remain, less what this digest names.const more = gathered.length === NOTICE_DIGEST_MAX ? await agentGatheredCount(tx, tabId, agentId) - notices.length : 0const text = digestText(notices[0]!.delivery.createdAt, notices.map(n => n.line), more, notices.some(n => n.otherAccount))// One message when an update request goes in this poll: the PM gets one turn, not two. Never into one already stored: its row// would be kept as it is, with no lines, or fail the poll (writeMessages keepStored).- const merged = woken && !await tx.superTabMessage.findUnique({ where: { id: update!.id }, select: { id: true } })+ const merged = await updateOpen()if (merged) {update!.text = `${update!.text}\n\n${text}`update!.source = { ...update!.source, notices: notices.length }} else {- written.push(digestMessage(agentId, gathered[0]!.id, projectOf(state, led!.id).leadConversationId, author(state, { kind: 'agent', agentId, machineOwnerId: target.machineOwnerId }), text, notices.length))+ digestDraft = digestMessage(agentId, gathered[0]!.id, projectOf(state, led!.id).leadConversationId, author(state, { kind: 'agent', agentId, machineOwnerId: target.machineOwnerId }), text, notices.length)+ written.push(digestDraft)}// By status too: two polls racing digest each row once. One by one: no `in` on this hot collection (hotFilters).for (const { delivery } of notices) await tx.superTabDelivery.updateMany({ where: { id: delivery.id, tabId, status: 'gathered' }, data: { status: 'digested' } })@@ -3669,6 +3687,34 @@ export class SuperTabStore {// Every row of the page refused: no digest, and still seen.afterCommit(tx, () => logger.info('[swarm-deliveries] notice digest', { tabId, count: 0, cancelled: refused }))}+ // The built-in schedule (pmSchedule.ts), only when the sweep has something to do: its slot is recorded in this same write,+ // woken or held back, so two racing polls wake the coordinator once. Its lines go into the update request, else the notice+ // digest, so the PM gets one turn; none while its last wake is still unread, so a PM deep in a long turn finds one, not one+ // per slot.+ const scheduled = led ? scheduleRequest(state, target, this.now()) : null+ if (scheduled) {+ const project = projectOf(state, led!.id)+ let wakeId = project.schedule?.wakeId+ let placed: 'update' | 'digest' | 'own' | 'skipped-open'+ // The message that carried the last wake, by its delivery's primary key (writeMessages: one row per message and+ // recipient): still unread is queued, claimed or uncertain.+ const last = wakeId ? await tx.superTabDelivery.findUnique({ where: { id: stableId(wakeId, agentId) }, select: { status: true } }) : null+ const open = !!last && ['queued', 'claimed', 'uncertain'].includes(last.status)+ const into = open ? null : await updateOpen() ? update! : digestDraft ?? null+ if (open) placed = 'skipped-open'+ else if (into) {+ into.text = `${into.text}\n\n${scheduled.draft.text}`+ into.source = { ...into.source, schedule: scheduled.slot }+ placed = into === digestDraft ? 'digest' : 'update'+ wakeId = into.id+ } else {+ written.push(scheduled.draft)+ placed = 'own'+ wakeId = scheduled.draft.id+ }+ project.schedule = { lastSlot: scheduled.slot, ...wakeId ? { wakeId } : {} }+ afterCommit(tx, () => logger.info('[swarm-deliveries] schedule request', { tabId, slot: scheduled.slot, placed }))+ }// The morning digest is due once a day; recording it as sent is part of this same write, so it is sent once.const digest = digestRequest(state, target, this.now(), asked)if (digest) {@@ -4213,7 +4259,11 @@ export class SuperTabStore {let ended: WorkHold[] = []const done = await transaction(this.db, async tx => {ended = []- const loaded = await this.load(tx, user, tabId), state = cloneData(loaded.state)+ let loaded = await this.load(tx, user, tabId)+ // The stop says Not building this in its task's project-chat thread (below): that chat is read when the load left it out.+ const lines = taskLineChats(loaded.state)+ if (lines.length) loaded = await this.ensure(tx, loaded, { groupIds: lines })+ const state = cloneData(loaded.state)const before = { agents: state.agents, conversations: cloneData(state.conversations) }const group = state.conversations.find(c => c.assignment?.id === assignmentId)const assignment = await strangerRefusal(state, user.sub, () => {@@ -4249,6 +4299,9 @@ export class SuperTabStore {author: author(state, { kind: 'agent', agentId: worker.id, machineOwnerId: worker.machineOwnerId }),text: `Stopped\n\n${assignment.result}`, replyTo: null, recipients: lead ? [lead] : [] })}+ // And its project chat's thread says Not building this, as a stop a command records does (task #2693).+ notices.push(...endedReply(state, group, stableId('task-line-stopped', tabId, assignmentId),+ worker && author(state, { kind: 'agent', agentId: worker.id, machineOwnerId: worker.machineOwnerId })))}const sequences = numberMessages(state, notices, this.now())// A confirmed stop finishes its worker, as work.status stopped does; no command reads that decision now, so it touchesdiff --git a/backend/src/superTabs/taskLine.ts b/backend/src/superTabs/taskLine.tsindex 48184b672..27b6919ec 100644--- a/backend/src/superTabs/taskLine.ts+++ b/backend/src/superTabs/taskLine.ts@@ -1,7 +1,7 @@import { agentDisplayName } from './agentNames.js'import { isBuddyChat } from './buddies.js'import { shippedNotice } from './buddyNews.js'-import { isLeads, stableId, type Author, type CommandEffects, type Conversation, type SuperTabState } from './model.js'+import { activeWork, isLeads, stableId, type Assignment, type Author, type CommandEffects, type Conversation, type MessageDraft, type SuperTabState } from './model.js'import { groupProject, projectsOf } from './projects.js'import { isStep } from './steps.js'import { usernameOf } from './usernames.js'@@ -57,6 +57,10 @@ function taskAsk(group: Conversation): TaskAsk {return status === 'done' && !group.pullRequestUrls?.length && !group.cards?.pullRequests?.length ? 'closed' : 'on-it'}+/** What a task's thread says when its builder stops reporting and its task is lost, and when its work is stopped. */+const stuck = (builder: string) => `Stuck: ${builder} stopped. Next: another engineer takes it over.`+const notBuilding = (assignment: Assignment) => `Not building this: ${sentence(assignment.result) || 'it was stopped.'}`+/** The thread's reply for what changed in [group] in this command, in the words Dee approved (2026-11-03), or none. */function progress(state: SuperTabState, effects: CommandEffects, group: Conversation, previous: Conversation | undefined, pm: string): string | null {const cards = group.cards?.pullRequests@@ -85,8 +89,8 @@ function progress(state: SuperTabState, effects: CommandEffects, group: Conversa}case 'working': return was.status === 'review' ? `Changes needed: ${sentence(assignment.result) || 'see the review.'} ${builder} is fixing it.` : nullcase 'blocked': return `Stuck: ${sentence(assignment.result) || `${builder} cannot go on.`} Next: ${pm} is looking at it.`- case 'lost': return `Stuck: ${builder} stopped. Next: another engineer takes it over.`- case 'cancelled': case 'stopped': return `Not building this: ${sentence(assignment.result) || 'it was stopped.'}`+ // A lost task says Stuck where it is lost, the one place that sees every loss (liveness.ts loseTask, endedReply).+ case 'cancelled': case 'stopped': return notBuilding(assignment)case 'done': return (group.pullRequestUrls ?? []).length || (group.cards?.pullRequests ?? []).length ? null : 'Done.'default: return null}@@ -155,3 +159,26 @@ function moved(state: SuperTabState, effects: CommandEffects, group: Conversatioif (news) effects.messages.push(news)}}++/** The thread reply of a task that ended outside any command, which syncTaskLines never sees (Diego, 2026-11-04, task #2693):+ * lost to the liveness sweep, its machine's report or its Lead's poll (liveness.ts loseTask, the agent.alert command's too), or+ * stopped by its host's receipt (store.ts stopped). As the command path's replies are: in its line's thread, by its project's+ * coordinator, else [fallback], waking nobody. None for a task with no line, or whose project chat is gone. */+export function endedReply(state: SuperTabState, group: Conversation, id: string, fallback?: Author): MessageDraft[] {+ const line = group.cards?.line, assignment = group.assignment+ if (!line || !assignment) return []+ const chat = state.conversations.find(c => c.id === line.conversationId)+ const author = chat && lineAuthor(state, chat, fallback)+ if (!chat || !author) return []+ const text = assignment.status === 'lost' ? stuck(agentDisplayName(state.agents, assignment.agentId) ?? 'its engineer') : notBuilding(assignment)+ return [{ id, conversationId: chat.id, author, text, replyTo: line.messageId, thread: line.messageId, recipients: [],+ source: { kind: 'system', ask: taskAsk(group) } }]+}++/** The project chats holding the lines of [state]'s open tasks that its load left out: a store path that may end a task outside+ * any command loads them first, so endedReply has its thread to write in. Empty on every path today, which loads every project chat. */+export function taskLineChats(state: SuperTabState): string[] {+ const loaded = new Set(state.conversations.map(c => c.id))+ return [...new Set(state.conversations.flatMap(c => activeWork(c) && c.cards?.line && !loaded.has(c.cards.line.conversationId)+ ? [c.cards.line.conversationId] : []))]+}diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.tsindex 3192a315f..addc4906f 100644--- a/backend/vitest.super-tabs.config.ts+++ b/backend/vitest.super-tabs.config.ts@@ -7,6 +7,6 @@ export default defineConfig({ test: { include: ['integration/superTabs.test.ts','integration/superTabObserver.test.ts', 'integration/productUsageConflicts.test.ts', 'integration/productUsageReceipts.test.ts', 'integration/schemaRelease.test.ts', 'integration/superTabBuddies.test.ts', 'integration/superTabNotAvailable.test.ts','integration/superTabBuddyProbes.test.ts', 'integration/superTabBuddySessions.test.ts', 'integration/superTabSwarmBuddy.test.ts', 'integration/superTabPersonalLead.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/harnessSharesIndexPlan.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts','integration/superTabEvidence.test.ts', 'integration/superTabAttemptModels.test.ts', 'integration/superTabNamedReads.test.ts', 'integration/swarmSweepPlans.test.ts', 'integration/workerIndexPlans.test.ts', 'integration/superTabReflection.test.ts',- 'integration/superTabMessagePages.test.ts', 'integration/superTabDeliveryCompaction.test.ts', 'integration/superTabNoticeDigest.test.ts', 'integration/superTabDigestHour.test.ts', 'integration/superTabCommandLoads.test.ts', 'integration/superTabThreads.test.ts', 'integration/superTabMachineRemovals.test.ts',+ 'integration/superTabMessagePages.test.ts', 'integration/superTabDeliveryCompaction.test.ts', 'integration/superTabNoticeDigest.test.ts', 'integration/superTabPmSchedule.test.ts', 'integration/superTabDigestHour.test.ts', 'integration/superTabCommandLoads.test.ts', 'integration/superTabThreads.test.ts', 'integration/superTabMachineRemovals.test.ts','integration/superTabInstructions.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts', 'integration/superTabPullRequestEvents.test.ts', 'integration/superTabProposals.test.ts', 'integration/superTabRequestReads.test.ts', 'integration/superTabVoiceMessages.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/noDefaultDigest.test-support.ts', 'integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })diff --git a/cli/src/lib/swarmInstructionsSkill.spec.ts b/cli/src/lib/swarmInstructionsSkill.spec.tsindex 637ff0d14..4d2d4c3e4 100644--- a/cli/src/lib/swarmInstructionsSkill.spec.ts+++ b/cli/src/lib/swarmInstructionsSkill.spec.ts@@ -253,3 +253,33 @@ describe('the project instructions skill', () => {expect(() => recordProjectSkillsNotice(join(fixture(), 'removed-worktree'), saved, { version: 'any', change: 1 })).not.toThrow()})})++// The Swarm's built-in PM schedule, read beside the document by the coordinator alone (2026-11-04 PM schedule design).+describe('the built-in PM schedule', () => {+ const BUILT_IN = '## Built-in PM schedule (from the Swarm)\n\nThe Swarm wakes you for these jobs.'++ it('appends the built-in schedule for the coordinator only', () => {+ const coordinator = instructionsSkillText(doc({ roleName: 'PM', coordinator: true, builtIn: BUILT_IN }))+ expect(coordinator.endsWith(`Instructions revision 1:\n\n${TEXT}\n\n${BUILT_IN}`)).toBe(true)+ expect(instructionsSkillText(doc({ builtIn: BUILT_IN }))).not.toContain('Built-in PM schedule')+ expect(instructionsSkillText(doc({ roleName: 'PM', coordinator: true, builtIn: null }))).toBe(instructionsSkillText(doc({ roleName: 'PM', coordinator: true })))+ })++ it('a changed built-in schedule owes one notice', () => {+ const { workspace, saved } = launched()+ const pm = (builtIn: string) => doc({ roleName: 'PM', coordinator: true, builtIn, savedAt: LAUNCHED_AT })+ const first = refreshProjectSkills(workspace, saved, pm(BUILT_IN))!+ recordProjectSkillsNotice(workspace, saved, first)+ const changed = refreshProjectSkills(workspace, saved, pm(`${BUILT_IN} Every 30 minutes.`))!+ expect(changed.owed).toBe(true)+ recordProjectSkillsNotice(workspace, saved, changed)+ expect(refreshProjectSkills(workspace, saved, pm(`${BUILT_IN} Every 30 minutes.`))).toMatchObject({ owed: false })+ })++ it('a launch that printed it owes nothing extra', () => {+ const { workspace, saved, instructions } = launched()+ const refresh = refreshProjectSkills(workspace, saved, doc({ roleName: 'PM', coordinator: true, builtIn: BUILT_IN }))!+ expect(refresh).toMatchObject({ owed: false, change: 0 })+ expect(readFileSync(instructions, 'utf8')).toContain(BUILT_IN)+ })+})diff --git a/cli/src/lib/swarmInstructionsSkill.ts b/cli/src/lib/swarmInstructionsSkill.tsindex 6bd17d1e9..d0f800578 100644--- a/cli/src/lib/swarmInstructionsSkill.ts+++ b/cli/src/lib/swarmInstructionsSkill.ts@@ -15,6 +15,9 @@ import { SWARM_TOOLS_SKILL } from './swarmTools.js'export interface ProjectDoc {revision: number; text: string; summary: string | null; roleName: string; coordinatorName: string; coordinator: booleansavedAt?: number | null+ /** The Swarm's built-in PM schedule, which only the coordinator's read carries (2026-11-04 PM schedule design): not part of+ * the document, so it follows it. Null or absent for anyone else, and from an older backend. */+ builtIn?: string | null}/** `tools` and `instructions` are the two files' paths; `tools` is '' for a Buddy, which has no tools skill. `version` names* what the files hold and `change` counts their rewrites: the notice's operation id is made of both. */@@ -27,7 +30,8 @@ export function instructionsSkillText(doc: ProjectDoc): string {const role = doc.coordinator? `You are this project's ${doc.roleName}, its coordinator: people talk to you when they address no one, and you receive the server's notices.`: `You are this project's ${doc.roleName}. ${doc.coordinatorName} is the project's coordinator.`- return `---\nname: swarm-instructions\ndescription: ${JSON.stringify(DESCRIPTION)}\n---\n${role}\n\nInstructions revision ${doc.revision}:\n\n${doc.text}`+ const builtIn = doc.coordinator && doc.builtIn ? `\n\n${doc.builtIn}` : ''+ return `---\nname: swarm-instructions\ndescription: ${JSON.stringify(DESCRIPTION)}\n---\n${role}\n\nInstructions revision ${doc.revision}:\n\n${doc.text}${builtIn}`}/** What the two files hold (each by its text's sha256; `tools` is '' for a Buddy), the revision and role they were writtendiff --git a/cli/src/superTabs/command.spec.ts b/cli/src/superTabs/command.spec.tsindex e72b3a026..eb468951c 100644--- a/cli/src/superTabs/command.spec.ts+++ b/cli/src/superTabs/command.spec.ts@@ -647,6 +647,18 @@ it('prints the instructions as text with the header and the coordinator\'s notesexpect(JSON.parse(print.mock.calls.at(-1)![0])).toMatchObject({ error: 'INSTRUCTIONS_UNAVAILABLE' })})+// 2026-11-04 PM schedule design: the coordinator's read carries the Swarm's built-in PM schedule, printed after the document so+// a new PM session reads it at launch, and before the notes.+it('prints the built-in schedule after the document', async () => {+ const print = vi.fn(), close = vi.fn()+ const request = vi.fn(async () => ({ ok: true, value: { projectId: 'p1', revision: 2, text: 'Work by this.', template: false, coordinatorName: 'Ana',+ builtIn: '## Built-in PM schedule (from the Swarm)\n\nB', notes: [{ id: 'n1', text: 'Be quick', askedBy: 'ken', at: 0, expiresAt: null }] } }))+ const deps = { where: () => where, pane: undefined, open: async () => ({ request, close, machineId: 'machine' }), print }+ expect(await superTabCommand([...prefix, 'instructions'], deps)).toBe(0)+ expect(print).toHaveBeenLastCalledWith(['Instructions of project p1, revision 2', '', 'Work by this.', '', '## Built-in PM schedule (from the Swarm)\n\nB', '',+ "Ana's notes:", '- Be quick (note n1, asked by ken, 1970-01-01T00:00:00.000Z)'].join('\n'))+})+it('parses a Buddy\'s propose OPERATION_ID JSON as its proposal command, whatever type the JSON names', () => {const prefix = ['--tab', 'tab', '--agent', 'buddy']const proposal = { conversationId: 'chat', ownerMessageId: 'asked', goal: 'Offline sync', scope: 'Desktop only', priority: 'normal' }diff --git a/cli/src/superTabs/command.ts b/cli/src/superTabs/command.tsindex acf7c3cb4..d14223a13 100644--- a/cli/src/superTabs/command.ts+++ b/cli/src/superTabs/command.ts@@ -407,8 +407,11 @@ export async function superTabCommand(argv: readonly string[], deps: {const notes = Array.isArray(value.notes) ? value.notes.map(object) : []const coordinator = typeof value.coordinatorName === 'string' && value.coordinatorName ? value.coordinatorName : 'The coordinator'const when = (at: unknown) => typeof at === 'number' && Number.isFinite(at) ? new Date(at).toISOString() : String(at)+ // The coordinator's read carries the Swarm's built-in PM schedule (2026-11-04 PM schedule design): printed after the+ // document, so a new PM session reads it at launch as its skill will hold it.+ const builtIn = typeof value.builtIn === 'string' && value.builtIn ? ['', value.builtIn] : []print([`Instructions of project ${value.projectId}, revision ${value.revision}${value.template ? ' (the built-in template)' : ''}`, '', value.text,- ...(notes.length ? ['', `${coordinator}'s notes:`, ...notes.map(n => `- ${n.text} (note ${n.id}, asked by ${n.askedByName ?? n.askedBy}, ${when(n.at)}`+ ...builtIn, ...(notes.length ? ['', `${coordinator}'s notes:`, ...notes.map(n => `- ${n.text} (note ${n.id}, asked by ${n.askedByName ?? n.askedBy}, ${when(n.at)}`+ `${n.expiresAt ? `, until ${when(n.expiresAt)}` : ''})`)] : [])].join('\n'))return 0}diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.tsindex 0b4ebdd60..d131b4c62 100644--- a/cli/src/superTabs/host.spec.ts+++ b/cli/src/superTabs/host.spec.ts@@ -3680,6 +3680,8 @@ describe('project instructions from the roster', () => {* revision `lag` (a read behind the roster); `history` refuses the revisions read (an outage). */const saves = [{ revision: 1, hash: 'hash-1', summary: 'Started from the built-in instructions.', text: START, at: LONG_AGO }]let lag: number | undefined, history = true+ /** The built-in PM schedule the backend serves its coordinator's read (2026-11-04 PM schedule design). */+ let builtIn = '## Built-in PM schedule (from the Swarm)\n\nThe Swarm wakes you for these jobs.'/** What the roster says of the agent's project: undefined leaves the keys out, as an old backend does. */let doc: Record<string, unknown> | null | undefined = { projectId: 'app', revision: 1, hash: 'hash-1', coordinatorName: 'Product Manager' }const rows = () => agents.map(agent => {@@ -3714,7 +3716,7 @@ describe('project instructions from the roster', () => {}const at = saves[(lag ?? saves.length) - 1]!return { status: 200, body: { data: { projectId: 'app', revision: at.revision, hash: at.hash, text: at.text, template: false,- coordinatorName: 'Product Manager', notesRevision: 1,+ coordinatorName: 'Product Manager', notesRevision: 1, ...(read[2] === 'a-pm' ? { builtIn } : {}),...(buddy ? {} : { notes: [{ id: 'note', text: NOTE, askedBy: 'ken', at: '2026-10-30T09:00:00.000Z', expiresAt: null }] }) } } }}if (path.endsWith('/deliveries')) return { status: 200, body: { data: [] } }@@ -3744,11 +3746,34 @@ describe('project instructions from the roster', () => {/** The project on the built-in template (nothing saved: revision 0) whose text is [text], as a backend build serves it. */template: (hash: string, text: string) => { saves.length = 0; saves.push({ revision: 0, hash, summary: '', text, at: LONG_AGO })doc = { projectId: 'app', revision: 0, hash, coordinatorName: 'Product Manager' } },- setDoc: (next: typeof doc) => { doc = next }, setLag: (revision: number | undefined) => { lag = revision }, setHistory: (served: boolean) => { history = served } }+ setDoc: (next: typeof doc) => { doc = next }, setBuiltIn: (text: string) => { builtIn = text }, setLag: (revision: number | undefined) => { lag = revision }, setHistory: (served: boolean) => { history = served } }}const instructionsRead = (agentId: string) => `/api/super-tabs/tab/projects/app/instructions?asAgentId=${agentId}`const historyRead = (agentId: string) => `/api/super-tabs/tab/projects/app/instructions/revisions?asAgentId=${agentId}`+ // 2026-11-04 PM schedule design: the coordinator's read carries the Swarm's built-in PM schedule, which changes with backend+ // builds while the document's revision and hash stay; the roster's builtInHash says when.+ it('rereads when the built-in hash moves', async () => {+ const f = docFixture(['pm'])+ f.setDoc({ projectId: 'app', revision: 1, hash: 'hash-1', coordinatorName: 'Product Manager', builtInHash: 'built-in-1' })+ const host = await f.pass()+ expect(readFileSync(f.file('pm'), 'utf8')).toContain('The Swarm wakes you for these jobs.')+ f.setBuiltIn('## Built-in PM schedule (from the Swarm)\n\nEvery 30 minutes, the open-task sweep.')+ f.setDoc({ projectId: 'app', revision: 1, hash: 'hash-1', coordinatorName: 'Product Manager', builtInHash: 'built-in-2' })+ await f.pass(host, 120_000)+ expect(f.reads.filter(path => path === instructionsRead('a-pm'))).toHaveLength(2)+ expect(readFileSync(f.file('pm'), 'utf8')).toContain('Every 30 minutes, the open-task sweep.')+ })++ it('caches the coordinator\'s read apart from a worker\'s', async () => {+ const f = docFixture(['pm', 'tester'])+ await f.pass()+ expect(f.reads.filter(path => path === instructionsRead('a-pm'))).toHaveLength(1)+ expect(f.reads.filter(path => path === instructionsRead('a-tester'))).toHaveLength(1)+ expect(readFileSync(f.file('pm'), 'utf8')).toContain('## Built-in PM schedule (from the Swarm)')+ expect(readFileSync(f.file('tester'), 'utf8')).not.toContain('Built-in PM schedule')+ })+// 2026-11-02, the rollout of #2495: a project with nothing saved stays at revision 0, so the text read once was kept until// the daemon restarted. The template's hash moves with each backend build that changes it.it('reads a changed template again at revision 0', async () => {@@ -3951,12 +3976,13 @@ describe('project instructions from the roster', () => {it('reads the text once for the project\'s agents here, each with its own role line, the coordinator\'s too', async () => {const f = docFixture(['pm', 'tester'])const host = await f.pass()- expect(f.reads).toEqual([instructionsRead('a-pm'), historyRead('a-pm')])+ // The coordinator's read carries the built-in PM schedule, so it is its own; the project's other agents share one.+ expect([...f.reads].sort()).toEqual([instructionsRead('a-pm'), historyRead('a-pm'), instructionsRead('a-tester'), historyRead('a-tester')].sort())expect(readFileSync(f.file('pm'), 'utf8')).toContain('\nYou are this project\'s PM, its coordinator: ')expect(readFileSync(f.file('tester'), 'utf8')).toContain('\nYou are this project\'s Tester. Product Manager is the project\'s coordinator.\n')f.move(f.save('Reviews go to the Reviewer', 'Revision two.\n'))await f.pass(host, 1_000)- expect(f.reads).toHaveLength(4)+ expect(f.reads).toHaveLength(8)expect(f.sent.map(s => s.asAgentId).sort()).toEqual(['a-pm', 'a-tester'])expect(new Set(f.sent.map(s => s.operationId)).size).toBe(2)})diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.tsindex 241e22f78..fef30c183 100644--- a/cli/src/superTabs/host.ts+++ b/cli/src/superTabs/host.ts@@ -283,22 +283,29 @@ function customRole(target: HostAgent): CustomRole | null {}/** The project instructions the roster names for this agent (project instructions, phase 3), or null: an older backend's row* has no `instructions` key and one in no project has null, and both keep their role files as before. */-interface RowInstructions { projectId: string; revision: number; hash: string | null; coordinatorName: string; roleName: string }+interface RowInstructions { projectId: string; revision: number; hash: string | null; coordinatorName: string; roleName: string+ /** The hash of the Swarm's built-in PM schedule the coordinator's read carries (2026-11-04 PM schedule design): it changes+ * with backend builds while the document's revision and hash stay. Null for any other agent, and from an older backend. */+ builtInHash: string | null }function rowInstructions(target: HostAgent): RowInstructions | null {- const { projectId, revision, hash, coordinatorName } = object(target.instructions)+ const { projectId, revision, hash, coordinatorName, builtInHash } = object(target.instructions)return identifier(projectId) && Number.isSafeInteger(revision) && (revision as number) >= 0 && (hash === null || typeof hash === 'string')&& typeof coordinatorName === 'string' && coordinatorName !== '' && typeof target.roleName === 'string' && target.roleName !== ''- ? { projectId, revision: revision as number, hash, coordinatorName, roleName: target.roleName } : null+ ? { projectId, revision: revision as number, hash, coordinatorName, roleName: target.roleName,+ builtInHash: typeof builtInHash === 'string' ? builtInHash : null } : null}/** The instructions text held for one project of a tab, shared by its agents here. A Buddy holds its own: the backend may- * refuse it a project its member lost while the project's agents still read it. */+ * refuse it a project its member lost while the project's agents still read it. So does the coordinator: only its read+ * carries the built-in PM schedule (2026-11-04 PM schedule design), which a worker's shared text must not get, nor lack. */const instructionsKey = (tabId: string, projectId: string, buddyId?: string) => JSON.stringify(buddyId ? [tabId, projectId, buddyId] : [tabId, projectId])/** What a session's skill comes from: its project's instructions at a revision, in its role (a save is acted on at the next* roster, not the next CLI release); else a built-in mode, or a Custom role's version and name (a rename rewrites the front* matter without a fetch), or nothing (a role gone or unusable). */function skillSetOf(target: HostAgent): string {const doc = rowInstructions(target)- if (doc) return JSON.stringify(['instructions', doc.projectId, doc.revision, doc.hash, doc.roleName, doc.coordinatorName, target.lead === true])+ // The built-in PM schedule's hash only when there is one, so an older backend's rows keep the version they had.+ if (doc) return JSON.stringify(['instructions', doc.projectId, doc.revision, doc.hash, doc.roleName, doc.coordinatorName, target.lead === true,+ ...doc.builtInHash ? [doc.builtInHash] : []])if (!('role' in target)) return target.skillMode === 'default' ? 'default' : 'orchestration'const role = customRole(target)return role ? JSON.stringify([role.projectId, role.id, role.version, role.name]) : 'none'@@ -565,7 +572,7 @@ export class SuperTabHost {* save time once a history read answered (`failedSince`: when it first failed): read again only when the roster's* revision moves, and dropped once no roster row names the project. */private readonly instructionTexts = new Map<string, { revision: number; hash: string | null; text: string- history: { summary: string | null; savedAt: number | null } | null; failedSince?: number }>()+ builtInHash: string | null; builtIn: string | null; history: { summary: string | null; savedAt: number | null } | null; failedSince?: number }>()private skillsRunning: Promise<void> | null = nullprivate missing = new Map<string, number>()/** Per Lead harness here: a reopen in progress, its failures, when the next may run, and the reason last logged. */@@ -1611,12 +1618,12 @@ export class SuperTabHost {* installs nothing and is tried again later, as a Custom role's text. */private async refreshInstructions(target: HostAgent, cwd: string, skill: SwarmSkill, doc: RowInstructions, current: () => boolean): Promise<void> {const buddy = skill.role === 'buddy', harnessId = target.agent.harnessId- const key = instructionsKey(target.tabId, doc.projectId, buddy ? target.agent.id : undefined)+ const key = instructionsKey(target.tabId, doc.projectId, buddy || target.lead === true ? target.agent.id : undefined)const path = `/api/super-tabs/${target.tabId}/projects/${doc.projectId}/instructions`, as = `asAgentId=${target.agent.id}`let held = this.instructionTexts.get(key)// The hash as well as the revision: a project with nothing saved stays at revision 0 while the template it reads changes// with backend builds (2026-11-02: running agents kept the old routing after #2495 until their daemon restarted).- if (held?.revision !== doc.revision || held.hash !== doc.hash) {+ if (held?.revision !== doc.revision || held.hash !== doc.hash || held.builtInHash !== doc.builtInHash) {const answer = object(await backend(this.core, 'GET', `${path}?${as}`))// A newer roster's refresh reads its own revision: this one installs and says nothing.if (!current()) { this.skillChecks.delete(harnessId); return }@@ -1624,7 +1631,8 @@ export class SuperTabHost {throw new Error(`The project's instructions read back are not revision ${doc.revision}, which this machine was told to install. Trying again later.`)}// A Buddy reads no history: it names who asked for what. Revision 0 is the built-in template: nothing was saved.- held = { revision: doc.revision, hash: doc.hash, text: answer.text, history: buddy || !doc.revision ? { summary: null, savedAt: null } : null }+ held = { revision: doc.revision, hash: doc.hash, text: answer.text, builtInHash: doc.builtInHash,+ builtIn: typeof answer.builtIn === 'string' && answer.builtIn ? answer.builtIn : null, history: buddy || !doc.revision ? { summary: null, savedAt: null } : null }this.instructionTexts.set(key, held)}// Task 4's review: a failed history read kept for the revision's life left every notice without its summary and gave each@@ -1646,7 +1654,7 @@ export class SuperTabHost {if (!current()) { this.skillChecks.delete(harnessId); return }if (unread && this.now() - held.failedSince! < HISTORY_WAIT_MS) { this.skillChecks.set(harnessId, this.now() + SKILL_RETRY_MS); return }const { summary, savedAt } = held.history ?? { summary: null, savedAt: null }- const refresh = refreshProjectSkills(cwd, skill, { revision: doc.revision, text: held.text, summary, savedAt,+ const refresh = refreshProjectSkills(cwd, skill, { revision: doc.revision, text: held.text, builtIn: held.builtIn, summary, savedAt,roleName: doc.roleName, coordinatorName: doc.coordinatorName, coordinator: target.lead === true })if (!refresh?.owed) returnif (await this.tellSkill(target, refresh, current)) recordProjectSkillsNotice(cwd, skill, refresh)diff --git a/desktop/lib/shared/theme/app_icons.dart b/desktop/lib/shared/theme/app_icons.dartindex 056db9e15..36f68134e 100644--- a/desktop/lib/shared/theme/app_icons.dart+++ b/desktop/lib/shared/theme/app_icons.dart@@ -37,6 +37,7 @@ abstract final class AppIcons {static const arrowUp = LucideIcons.arrowUp400;static const arrowDown = LucideIcons.arrowDown400;static const arrowUpRight = LucideIcons.arrowUpRight400;+ static const atSign = LucideIcons.atSign400;static const bell = LucideIcons.bell400;static const bellOff = LucideIcons.bellOff400;static const bellRing = LucideIcons.bellRing400;@@ -143,6 +144,7 @@ abstract final class AppIcons {static const messagesSquare = LucideIcons.messagesSquare400;static const messageSquare = LucideIcons.messageSquare400;static const messageSquareText = LucideIcons.messageSquareText400;+ static const mic = LucideIcons.mic400;static const minimize = LucideIcons.minimize400;static const minus = LucideIcons.minus400;static const monitor = LucideIcons.monitor400;diff --git a/desktop/lib/super_tabs/composer_actions.dart b/desktop/lib/super_tabs/composer_actions.dartnew file mode 100644index 000000000..3872ebb63--- /dev/null+++ b/desktop/lib/super_tabs/composer_actions.dart@@ -0,0 +1,34 @@+import 'package:flutter/material.dart';++import '../shared/theme/app_icons.dart';+import '../shared/widgets/app_icon_button.dart';++/// @ Tag on a composer's row, as on the phone: it types `@` at the caret+/// ([superTabTagPrompt]), and the tag list opens as for one typed.+class SuperTabComposerTagButton extends StatelessWidget {+ const SuperTabComposerTagButton({super.key, required this.onPressed});++ final VoidCallback? onPressed;++ @override+ Widget build(BuildContext context) => AppIconButton(+ icon: AppIcons.atSign,+ tooltip: 'Tag someone',+ onPressed: onPressed,+ );+}++/// The mic left of send: starts a voice message (voice_recorder.dart). A+/// composer draws it only with a recorder.+class SuperTabComposerMic extends StatelessWidget {+ const SuperTabComposerMic({super.key, required this.onPressed});++ final VoidCallback? onPressed;++ @override+ Widget build(BuildContext context) => AppIconButton(+ icon: AppIcons.mic,+ tooltip: 'Record a voice message',+ onPressed: onPressed,+ );+}diff --git a/desktop/lib/super_tabs/composer_tags.dart b/desktop/lib/super_tabs/composer_tags.dartindex 0108e628c..1b6f2bdd4 100644--- a/desktop/lib/super_tabs/composer_tags.dart+++ b/desktop/lib/super_tabs/composer_tags.dart@@ -115,6 +115,22 @@ List<SuperTabComposerChoice> superTabTagChoices(].take(superTabCompletionLimit).toList();}+/// [value] with `@` typed at its caret, in place of any selection, as @ Tag+/// types it: after a space where the caret follows a word, so the tag list+/// opens there ([superTabTagAtCaret]).+TextEditingValue superTabTagPrompt(TextEditingValue value) {+ final text = value.text;+ final selection = value.selection.isValid+ ? value.selection+ : TextSelection.collapsed(offset: text.length);+ final before = text.substring(0, selection.start);+ final at = before.isEmpty || RegExp(r'\s$').hasMatch(before) ? '@' : ' @';+ return TextEditingValue(+ text: before + at + text.substring(selection.end),+ selection: TextSelection.collapsed(offset: before.length + at.length),+ );+}+/// [value] with the tag typed at [at] replaced by [token] and a space, the/// caret after it.TextEditingValue superTabInsertTag(diff --git a/desktop/lib/super_tabs/composer_toggle.dart b/desktop/lib/super_tabs/composer_toggle.dartindex e212986e9..c0390a9a7 100644--- a/desktop/lib/super_tabs/composer_toggle.dart+++ b/desktop/lib/super_tabs/composer_toggle.dart@@ -29,30 +29,6 @@ class SuperTabComposerToggle extends StatelessWidget {static const _iconSize = 12.0;static const _gap = 4.0;- /// The width this choice takes with [label] in one line, as drawn in- /// [context] (its text size included): what a send row measures to tell- /// whether a label fits. Matches [DesktopPill]'s compact quiet control:- /// side padding, the icon and its gap, and the reserved rim.- static double widthOf(BuildContext context, String label) {- final text = TextPainter(- text: TextSpan(- text: label,- style: DesktopChrome.text(size: _textSize, height: 1.25),- ),- textDirection: Directionality.of(context),- textScaler: MediaQuery.textScalerOf(context),- maxLines: 1,- )..layout();- final width = text.width;- text.dispose();- return 6 * 2 +- grid.AppDesktop.focusWidth * 2 +- _iconSize +- _gap +- width +- 1;- }-@overrideWidget build(BuildContext context) {grid.AppTheme.watch(context);diff --git a/desktop/lib/super_tabs/reply_box.dart b/desktop/lib/super_tabs/reply_box.dartindex 6c3509acd..dcb9b8d1d 100644--- a/desktop/lib/super_tabs/reply_box.dart+++ b/desktop/lib/super_tabs/reply_box.dart@@ -9,6 +9,7 @@ import '../state/harness_attachments.dart';import '../widgets/desktop_chrome.dart';import '../widgets/new_harness_attachments.dart';import '../widgets/new_harness_paste.dart';+import 'composer_actions.dart';import 'composer_files.dart';import 'composer_newline.dart';import 'controller.dart';@@ -16,8 +17,9 @@ import 'swarm_type.dart';/// A thread's reply box, one everywhere a reply is written (the thread pane,/// the Threads view): files dropped, pasted or attached, Enter sends and-/// ⇧Enter breaks the line, attach and the arrow at its right end. [options]-/// sits left of them, such as the pane's Also send and New session.+/// ⇧Enter breaks the line. Under the text, one row as on the phone (Huy and+/// Scholes, 11-04): + (attach) and @ Tag, then [options] such as the pane's+/// New session, and the mic (with [onMic]) and the arrow at its right end.class SuperTabReplyBox extends StatelessWidget {const SuperTabReplyBox({super.key,@@ -32,11 +34,15 @@ class SuperTabReplyBox extends StatelessWidget {required this.onEdited,required this.onSend,this.options,+ this.onTag,+ this.onMic,this.onKey,this.inputFormatters = const [],this.surfaceKey = const ValueKey('super-thread-composer-surface'),this.fieldKey = const ValueKey('super-thread-composer'),this.sendKey = const ValueKey('super-thread-send'),+ this.tagKey = const ValueKey('super-thread-tag'),+ this.micKey = const ValueKey('super-thread-mic'),this.hint = 'Reply',});@@ -55,23 +61,29 @@ class SuperTabReplyBox extends StatelessWidget {final VoidCallback onSend;final Widget? options;+ /// @ Tag's press, and the mic's: no mic without one; @ Tag greyed.+ final VoidCallback? onTag, onMic;+/// Sees each key first, such as an open @ completion list's arrows and/// Enter; a non-null answer is the key's.final KeyEventResult? Function(KeyEvent event)? onKey;final List<TextInputFormatter> inputFormatters;- final Key surfaceKey, fieldKey, sendKey;+ final Key surfaceKey, fieldKey, sendKey, tagKey, micKey;/// The field's hint: what an empty box says it is for.final String hint;- /// The Tab order inside an [OrderedTraversalPolicy] group around the box:- /// the field (and its files) first, then the options, wherever the owner- /// places them ([optionsOrder], such as the pane's Also send on its own line- /// under the box), then attach and send. Outside such a group it has no- /// effect, and the reading order applies.+ /// The Tab order inside an [OrderedTraversalPolicy] group around the box,+ /// the row's own: the field (and its files) first, then + and @ Tag, the+ /// options ([optionsOrder], such as the pane's New session), the mic and+ /// send, and last what the owner puts under the box ([underOrder], such as+ /// the pane's Also send). Outside such a group it has no effect, and the+ /// reading order applies.static const fieldOrder = NumericFocusOrder(1),+ toolsOrder = NumericFocusOrder(1.5),optionsOrder = 2.0,- sendOrder = NumericFocusOrder(3);+ sendOrder = NumericFocusOrder(3),+ underOrder = NumericFocusOrder(4);@overrideWidget build(BuildContext context) => NewHarnessDropZone(@@ -169,14 +181,30 @@ class SuperTabReplyBox extends StatelessWidget {const SizedBox(height: grid.AppDesktop.controlGap),Row(children: [- Expanded(child: options ?? const SizedBox.shrink()),FocusTraversalOrder(- order: sendOrder,+ order: toolsOrder,child: NewHarnessAttachButton(attachments: files,enabled: writable && !busy,+ icon: AppIcons.plus,),),+ FocusTraversalOrder(+ order: toolsOrder,+ child: SuperTabComposerTagButton(+ key: tagKey,+ onPressed: writable ? onTag : null,+ ),+ ),+ Expanded(child: options ?? const SizedBox.shrink()),+ if (onMic case final onMic?)+ FocusTraversalOrder(+ order: sendOrder,+ child: SuperTabComposerMic(+ key: micKey,+ onPressed: writable ? onMic : null,+ ),+ ),FocusTraversalOrder(order: sendOrder,child: ListenableBuilder(diff --git a/desktop/lib/super_tabs/thread_panel.dart b/desktop/lib/super_tabs/thread_panel.dartindex 702b6341d..1a2b01308 100644--- a/desktop/lib/super_tabs/thread_panel.dart+++ b/desktop/lib/super_tabs/thread_panel.dart@@ -20,6 +20,7 @@ import 'model.dart';import 'thread_scroll.dart';import '../widgets/laid_out_list.dart';import 'swarm_type.dart';+import 'voice_recorder.dart';/// One thread beside the chat (Dee, 2026-10-29): its root, a "N replies"/// divider, the replies, and a composer whose reply goes to the root.@@ -33,6 +34,7 @@ class SuperTabThreadPanel extends StatefulWidget {this.sessionActivity,this.machineName,this.onScroll,+ this.voiceRecorder,});final SuperTabController controller;@@ -55,6 +57,9 @@ class SuperTabThreadPanel extends StatefulWidget {/// so a device scrolling this Swarm scrolls the thread, not the chat.final ValueChanged<ScrollController?>? onScroll;+ /// What the reply box's mic records with; without it, no mic shows.+ final SuperTabVoiceRecorder? voiceRecorder;+@overrideState<SuperTabThreadPanel> createState() => _SuperTabThreadPanelState();}@@ -252,7 +257,8 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {/// Where "Also send" also puts the reply, always in full (Scholes, 11-03:/// "Also to chat" did not say where): the project chat as its sidebar row- /// names it, else the main chat.+ /// names it, else the main chat. "Send", as the phone and Slack say it+ /// (Huy and Scholes, 11-04).String get _alsoSendLabel {final group = c.selected, snapshot = c.snapshot;String? channel;@@ -260,17 +266,12 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {channel = snapshot.projectFor(group.id)?.name;}return channel == null- ? 'Also post to the main chat'- : 'Also post to #$channel';+ ? 'Also send to the main chat'+ : 'Also send to #$channel';}String get _alsoSendHint => '$_alsoSendLabel as well as this thread';- /// Whether Also send sits on its own line under the box: its full label- /// has no room beside New session on the send row. Set from the send row's- /// width once it is laid out ([_choices]).- bool _alsoBelow = false;-// An older Buddy chat is kept to read: no thread reply there either (security review 1 of #2437).bool get _writable =>c.canWrite &&@@ -355,6 +356,13 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {setState(() {});}+ /// @ Tag: `@` at the caret, reported as an edit so the tag list opens.+ void _promptTag() {+ _composer.value = superTabTagPrompt(_composer.value);+ _edited(_composer.text);+ _focus.requestFocus();+ }+void _moveTag(int index) {_tagIndex.value = index;WidgetsBinding.instance.addPostFrameCallback((_) {@@ -642,6 +650,13 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {onEdited: _edited,onSend: () => unawaited(_send()),options: _choices(_writable),+ onTag: _promptTag,+ onMic: switch (widget.voiceRecorder) {+ final recorder? => () => unawaited(+ recorder.start(conversationId: _conversationId, root: widget.root),+ ),+ null => null,+ },// `@` in the reply: the open completion list takes its keys first.onKey: (event) {final composing = _composer.value.composing;@@ -661,10 +676,11 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {inputFormatters: [_tagBackspace],);- /// What sits under the box: Also send on its own line where it has no room- /// on the send row, and the muted note while the reply starts a session.- /// They never show together, so they share one place; each keeps its place- /// while hidden, so the box never moves as New session is toggled.+ /// What sits under the box: Also send, a small checkbox on its own line as+ /// in Slack (Huy and Scholes, 11-04), and the muted note while the reply+ /// starts a session. They never show together, so they share one place;+ /// each keeps its place while hidden, so the box never moves as New session+ /// is toggled.Widget? _underBox() {final note = _offersSession? Padding(@@ -682,8 +698,8 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {),): null;- if (!(_alsoSendPossible && _alsoBelow)) return note;- // Its square under the send row's first one: the box's inset.+ if (!_alsoSendPossible) return note;+ // Its square under the row's first button: the box's inset.final line = Visibility(visible: _offersAlsoSend,maintainSize: true,@@ -704,54 +720,21 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {return note == null ? line : Stack(children: [line, note]);}- /// The send row's options, left of attach and send (Scholes, 11-03): New- /// session, then Also send in full where both fit; where they do not, Also- /// send moves to its own line under the box ([_alsoBelow]), never to a- /// shorter label. The choice rests on the row's width alone, so it settles- /// after one frame, in which Also send is drawn in neither place.- Widget _choices(bool writable) => LayoutBuilder(- builder: (context, constraints) {- double width(String label) =>- SuperTabComposerToggle.widthOf(context, label);- final session = _offersSession ? _sessionLabel : null;- // Measured whether or not New session is on, so the place stays put.- final also = _alsoSendPossible ? _alsoSendLabel : null;- final needed =- (session == null ? 0 : width(session)) +- (session != null && also != null ? _choiceGap : 0) +- (also == null ? 0 : width(also));- final below = also != null && needed > constraints.maxWidth;- final inline = _offersAlsoSend && !below && !_alsoBelow;- if (below != _alsoBelow) {- WidgetsBinding.instance.addPostFrameCallback((_) {- if (mounted && below != _alsoBelow) {- setState(() => _alsoBelow = below);- }- });- }- final sessionChoice = FocusTraversalOrder(- order: const NumericFocusOrder(SuperTabReplyBox.optionsOrder),- child: _sessionChoice(writable),- );- return Row(- children: [- // Its own width beside Also send, which then fits; alone it may end- // in "…" in a pane narrower than the app allows.- if (session != null)- inline ? sessionChoice : Flexible(child: sessionChoice),- if (inline) ...[- if (session != null) const SizedBox(width: _choiceGap),- Flexible(child: _alsoSendChoice(writable)),- ],- ],- );- },- );-- /// Also send, on the send row or on its own line under the box; after New- /// session in the Tab order either way.+ /// The row's options, between @ Tag and the mic: New session, ending in "…"+ /// in a pane narrower than the app allows.+ Widget? _choices(bool writable) => _offersSession+ ? Align(+ alignment: Alignment.centerLeft,+ child: FocusTraversalOrder(+ order: const NumericFocusOrder(SuperTabReplyBox.optionsOrder),+ child: _sessionChoice(writable),+ ),+ )+ : null;++ /// Also send, on its own line under the box: after send in the Tab order.Widget _alsoSendChoice(bool writable) => FocusTraversalOrder(- order: const NumericFocusOrder(SuperTabReplyBox.optionsOrder + .1),+ order: SuperTabReplyBox.underOrder,child: SuperTabComposerToggle(key: const ValueKey('super-thread-also-send'),on: _alsoSend,@@ -761,7 +744,6 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {),);- static const _choiceGap = 4.0;static const _sessionLabel = 'New session';/// New session, left of Also send: on and locked once the thread's sessiondiff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex f0fa21af0..0b919a3d6 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -1,7 +1,7 @@import 'dart:async';-import 'dart:math' as math;import 'package:clock/clock.dart';+import 'package:flutter/foundation.dart' show kIsWeb;import 'package:flutter/material.dart';import 'package:flutter/rendering.dart'@@ -82,7 +82,9 @@ import 'project_status.dart';import 'ship_row.dart';import 'switch_pm.dart';import 'pane_layout.dart';+import 'composer_actions.dart';import 'view_room.dart';+import 'voice_recorder.dart';import 'swarm_type.dart';import 'visible_tick.dart';import 'buddy_rows.dart';@@ -114,6 +116,7 @@ class SuperTabView extends StatefulWidget {this.onNewSwarm,this.onChooseAgentTerminal,this.linkSwarms,+ this.voiceRecorder,});final SuperTabController controller;final VoidCallback onInvite;@@ -139,6 +142,9 @@ class SuperTabView extends StatefulWidget {/// without an [app], a link into another Swarm is not followed.final SwarmLinkSwarms? linkSwarms;+ /// What the composer's mic records with; without it, no mic shows.+ final SuperTabVoiceRecorder? voiceRecorder;+@overrideState<SuperTabView> createState() => _SuperTabViewState();}@@ -654,6 +660,16 @@ class _SuperTabViewState extends State<SuperTabView>/// Shows the jump pill while the reader is away from a line not yet seen,/// and Jump to latest while the list is away from its newest message.void _checkUnreadLine() {+ // A jump outside a frame (Jump to latest, a key, a test) moves the+ // position before the list lays out again: the line is measured where it+ // was. Measured again once laid out; a list whose extent then changes said+ // so by itself, one whose extent stays (the composer's two rows, #2662)+ // did not, and the bar never showed.+ if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.idle) {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted) _checkUnreadLine();+ });+ }final scroll = _scroll[c.selectedId];// A jump still landing passes lines it does not stop at: the pill stays// as it was until the line is measured where the jump landed.@@ -2661,50 +2677,25 @@ class _SuperTabViewState extends State<SuperTabView>return ((room - 275) / line).floor().clamp(2, 5);}- /// The composer's field and its controls: a row on a wide window. A phone- /// gives the field the width and the controls a row below (Huy, 2026-11-02:- /// the field had about 40% of the row): [options] and [attach] at the left,- /// wrapping if they must, and [send] at the right.+ /// The composer's field and its controls, as on the phone (Huy and Scholes,+ /// 11-04): the field on top with the width, and one row under it with+ /// [attach] (+), [tag] (@ Tag) and [options] (New session) at the left, and+ /// [trailing] (the mic) and [send] at the right. Send keeps the box's+ /// bottom-right corner however long the message (Scholes, 11-03).Widget _composerLayout({required double room,required Widget field,- required List<Widget> options,required Widget attach,+ required Widget tag,+ required List<Widget> options,+ required List<Widget> trailing,required Widget send,}) {// Too little height for a second row (a phone on its side with its keyboard- // up): the actions take the row's end again. A narrow phone with so little- // height gets the squeezed row, which beats a composer that overflows.- if (_phone && room >= _phoneComposerTwoRowsFrom) {- return Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- Padding(- padding: const EdgeInsets.only(- right: grid.AppDesktop.controlGap,- bottom: grid.AppDesktop.controlGap,- ),- child: field,- ),- Row(- key: const ValueKey('super-message-composer-actions'),- crossAxisAlignment: CrossAxisAlignment.end,- children: [- Expanded(- child: Wrap(- crossAxisAlignment: WrapCrossAlignment.center,- children: [...options, attach],- ),- ),- send,- ],- ),- ],- );- }- // A phone with too little height keeps its squeezed row as it was.- if (_phone) {+ // up): the actions take the row's end. A narrow phone with so little+ // height gets the squeezed row, which beats a composer that overflows; it+ // has no room for @ Tag there, and an @ typed still opens the list.+ if (_phone && room < _phoneComposerTwoRowsFrom) {return ConstrainedBox(constraints: BoxConstraints(minHeight: grid.AppControl.heightFieldScaled,@@ -2713,51 +2704,51 @@ class _SuperTabViewState extends State<SuperTabView>crossAxisAlignment: CrossAxisAlignment.center,children: [Expanded(child: field),- ...options,attach,+ ...options,+ ...trailing,send,],),);}- // The controls stay at the bottom-right as the message grows, level with- // its last line (Scholes, 11-03: centred, they drifted up the box). The- // field is padded to the row's height, so one line sits where it did,- // centred on the controls, and a longer message's last line keeps that- // place.- final row = grid.AppControl.heightFieldScaled;- // The line of the style the field draws with: a padding measured on- // another one left the chips a pixel off the line once the composer took- // Slack's 15 px on 22 px lines (#2732).- final style = SwarmType.composer(context);- final line =- MediaQuery.textScalerOf(context).scale(style.fontSize!) * style.height!;- final inset = math.max(0.0, (row - line) / 2);- return ConstrainedBox(- constraints: BoxConstraints(minHeight: row),- child: Row(- crossAxisAlignment: CrossAxisAlignment.end,- children: [- Expanded(- child: Padding(- padding: EdgeInsets.symmetric(vertical: inset),- child: field,- ),+ return Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Padding(+ padding: const EdgeInsets.only(+ right: grid.AppDesktop.controlGap,+ bottom: grid.AppDesktop.controlGap,),- // As tall as the row at least, the controls centred in it as before;- // taller with larger text.- ConstrainedBox(- constraints: BoxConstraints(minHeight: row),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [...options, attach, send],+ child: field,+ ),+ Row(+ key: const ValueKey('super-message-composer-actions'),+ children: [+ attach,+ tag,+ Expanded(+ child: Wrap(+ crossAxisAlignment: WrapCrossAlignment.center,+ children: options,+ ),),- ),- ],- ),+ ...trailing,+ send,+ ],+ ),+ ],);}+ /// @ Tag: `@` at the caret, reported as an edit so the tag list opens.+ void _promptTag() {+ _composer.value = superTabTagPrompt(_composer.value);+ _composerEdited(_composer.text);+ _focus.requestFocus();+ }+/// Whether ⋮ carries the views a wider header draws as icons.bool get _menuNamesViews =>_phone && !_devicesVisible && !_listViewHoldsThePane;@@ -3727,6 +3718,7 @@ class _SuperTabViewState extends State<SuperTabView>superTabSessionActivity(c, widget.app, session),machineName: widget.machineName,onScroll: (list) => _threadScroll = list,+ voiceRecorder: widget.voiceRecorder,),);}@@ -4734,6 +4726,21 @@ class _SuperTabViewState extends State<SuperTabView>onChanged: _composerEdited,),),+ attach: fingerTarget(+ enabled: _phone,+ NewHarnessAttachButton(+ attachments: _files,+ enabled: writable && !busy,+ icon: AppIcons.plus,+ ),+ ),+ tag: fingerTarget(+ enabled: _phone,+ SuperTabComposerTagButton(+ key: const ValueKey('super-composer-tag'),+ onPressed: writable ? _promptTag : null,+ ),+ ),options: [if (c.offersChatSessions)Padding(@@ -4752,13 +4759,22 @@ class _SuperTabViewState extends State<SuperTabView>child: _chatSessionProject(writable),),],- attach: fingerTarget(- enabled: _phone,- NewHarnessAttachButton(- attachments: _files,- enabled: writable && !busy,- ),- ),+ trailing: [+ if (widget.voiceRecorder case final recorder?)+ fingerTarget(+ enabled: _phone,+ SuperTabComposerMic(+ key: const ValueKey('super-composer-mic'),+ onPressed: writable+ ? () => unawaited(+ recorder.start(+ conversationId: chatId,+ ),+ )+ : null,+ ),+ ),+ ],send: ListenableBuilder(listenable: Listenable.merge([_composer,diff --git a/desktop/lib/super_tabs/voice_recorder.dart b/desktop/lib/super_tabs/voice_recorder.dartnew file mode 100644index 000000000..3fbe16d29--- /dev/null+++ b/desktop/lib/super_tabs/voice_recorder.dart@@ -0,0 +1,9 @@+/// Records a voice message from the composer's mic: sent as audio, people hear+/// it and agents read its words (Dee, 11-04; #2887), never typed into the box.+/// The composer shows its mic only with one, so no button that does nothing+/// shows: none is given until recording comes, with the `record` package and+/// the macOS microphone entitlement (River, 11-04: its own task after #2662).+abstract interface class SuperTabVoiceRecorder {+ /// Starts a take for [conversationId], in the thread [root] when one is open.+ Future<void> start({required String conversationId, String? root});+}diff --git a/desktop/lib/widgets/new_harness_attachments.dart b/desktop/lib/widgets/new_harness_attachments.dartindex 8eedaa240..3fd566dd2 100644--- a/desktop/lib/widgets/new_harness_attachments.dart+++ b/desktop/lib/widgets/new_harness_attachments.dart@@ -67,21 +67,24 @@ void reportAttachProblem(BuildContext context, String? problem) {?.showSnackBar(SnackBar(content: Text(problem)));}-/// 📎 beside New Harness: opens the system's file chooser.+/// 📎 beside New Harness: opens the system's file chooser. A Swarm composer+/// draws it as the phone's + ([icon]).class NewHarnessAttachButton extends StatelessWidget {const NewHarnessAttachButton({super.key,required this.attachments,required this.enabled,+ this.icon = AppIcons.paperclip,});final HarnessAttachments attachments;final bool enabled;+ final IconData icon;@overrideWidget build(BuildContext context) => AppIconButton(key: const ValueKey('new-harness-attach'),- icon: AppIcons.paperclip,+ icon: icon,tooltip: 'Attach files',size: 16,onPressed: !enableddiff --git a/desktop/test/screenshots/composer-row/after/composer-chat-dark.png b/desktop/test/screenshots/composer-row/after/composer-chat-dark.pngnew file mode 100644index 000000000..4284bc38fBinary files /dev/null and b/desktop/test/screenshots/composer-row/after/composer-chat-dark.png differdiff --git a/desktop/test/screenshots/composer-row/after/composer-chat-light.png b/desktop/test/screenshots/composer-row/after/composer-chat-light.pngnew file mode 100644index 000000000..e6e34b88bBinary files /dev/null and b/desktop/test/screenshots/composer-row/after/composer-chat-light.png differdiff --git a/desktop/test/screenshots/composer-row/after/composer-chat-mic-dark.png b/desktop/test/screenshots/composer-row/after/composer-chat-mic-dark.pngnew file mode 100644index 000000000..7cda3356aBinary files /dev/null and b/desktop/test/screenshots/composer-row/after/composer-chat-mic-dark.png differdiff --git a/desktop/test/screenshots/composer-row/after/composer-chat-mic-light.png b/desktop/test/screenshots/composer-row/after/composer-chat-mic-light.pngnew file mode 100644index 000000000..d56909e83Binary files /dev/null and b/desktop/test/screenshots/composer-row/after/composer-chat-mic-light.png differdiff --git a/desktop/test/screenshots/composer-row/after/composer-thread-dark.png b/desktop/test/screenshots/composer-row/after/composer-thread-dark.pngnew file mode 100644index 000000000..12bcb5033Binary files /dev/null and b/desktop/test/screenshots/composer-row/after/composer-thread-dark.png differdiff --git a/desktop/test/screenshots/composer-row/after/composer-thread-light.png b/desktop/test/screenshots/composer-row/after/composer-thread-light.pngnew file mode 100644index 000000000..0dc32f66eBinary files /dev/null and b/desktop/test/screenshots/composer-row/after/composer-thread-light.png differdiff --git a/desktop/test/screenshots/composer-row/after/composer-web-phone-dark.png b/desktop/test/screenshots/composer-row/after/composer-web-phone-dark.pngnew file mode 100644index 000000000..ac389689eBinary files /dev/null and b/desktop/test/screenshots/composer-row/after/composer-web-phone-dark.png differdiff --git a/desktop/test/screenshots/composer-row/after/composer-web-phone-light.png b/desktop/test/screenshots/composer-row/after/composer-web-phone-light.pngnew file mode 100644index 000000000..f6571a779Binary files /dev/null and b/desktop/test/screenshots/composer-row/after/composer-web-phone-light.png differdiff --git a/desktop/test/screenshots/composer-row/before/composer-chat-dark.png b/desktop/test/screenshots/composer-row/before/composer-chat-dark.pngnew file mode 100644index 000000000..cf0fc5682Binary files /dev/null and b/desktop/test/screenshots/composer-row/before/composer-chat-dark.png differdiff --git a/desktop/test/screenshots/composer-row/before/composer-chat-light.png b/desktop/test/screenshots/composer-row/before/composer-chat-light.pngnew file mode 100644index 000000000..1f78bf885Binary files /dev/null and b/desktop/test/screenshots/composer-row/before/composer-chat-light.png differdiff --git a/desktop/test/screenshots/composer-row/before/composer-thread-dark.png b/desktop/test/screenshots/composer-row/before/composer-thread-dark.pngnew file mode 100644index 000000000..8934b5d3bBinary files /dev/null and b/desktop/test/screenshots/composer-row/before/composer-thread-dark.png differdiff --git a/desktop/test/screenshots/composer-row/before/composer-thread-light.png b/desktop/test/screenshots/composer-row/before/composer-thread-light.pngnew file mode 100644index 000000000..6343a56d1Binary files /dev/null and b/desktop/test/screenshots/composer-row/before/composer-thread-light.png differdiff --git a/desktop/test/super_tab_buddy_sessions_test.dart b/desktop/test/super_tab_buddy_sessions_test.dartindex 4b033af58..98d08e4d2 100644--- a/desktop/test/super_tab_buddy_sessions_test.dart+++ b/desktop/test/super_tab_buddy_sessions_test.dart@@ -190,9 +190,8 @@ void main() {Map<String, dynamic> lastCommand(ConversationServer server) =>Map<String, dynamic>.from(server.posts.last['command'] as Map);- testSessions('New session sits beside Also send, hides it, and is sent', (- tester,- ) async {+ testSessions('New session sits on the row above Also send, hides it, and '+ 'is sent', (tester) async {final server = buddyChat();final c = await show(tester, server);await openThread(tester, c, 'message-1');@@ -200,14 +199,10 @@ void main() {expect(newSession, findsOneWidget);expect(alsoSend, findsOneWidget);expect(box(tester, newSession).on, isFalse);- // Left of Also send on one row, or above it where Also send takes its- // own line under the box (Scholes, 11-03).+ // On the box's row; Also send on its own line under the box (Huy and+ // Scholes, 11-04).final a = tester.getRect(newSession), b = tester.getRect(alsoSend);- expect(- (a.top == b.top && a.left < b.left) ||- (b.top > a.bottom && (a.left - b.left).abs() < .5),- isTrue,- );+ expect(b.top, greaterThan(a.bottom));expect(find.byTooltip('Starts a separate Buddy session for this thread'),findsOneWidget,@@ -246,9 +241,9 @@ void main() {expect(box(tester, newSession).label, 'New session');// Always the full wording (Scholes, 11-03): with no room beside New// session, it takes its own line under the box.- expect(box(tester, alsoSend).label, 'Also post to the main chat');+ expect(box(tester, alsoSend).label, 'Also send to the main chat');expect(- find.byTooltip('Also post to the main chat as well as this thread'),+ find.byTooltip('Also send to the main chat as well as this thread'),findsOneWidget,);// New session sits on the send row, left of its buttons; Also send ondiff --git a/desktop/test/super_tab_chat_scroll_test.dart b/desktop/test/super_tab_chat_scroll_test.dartindex b197efe81..054417df5 100644--- a/desktop/test/super_tab_chat_scroll_test.dart+++ b/desktop/test/super_tab_chat_scroll_test.dart@@ -19,6 +19,11 @@ void main() {}) async {final c = server.controller(reading: reading);await c.refresh();+ // A window as tall as a laptop's: below about 620 px, with the composer's+ // two rows (#2662), the group at the top of the view starts above the rows+ // laid out, and the dividing row does not move (_moveSplitToView).+ await tester.binding.setSurfaceSize(const Size(800, 720));+ addTearDown(() => tester.binding.setSurfaceSize(null));await tester.pumpWidget(MaterialApp(theme: grid.buildAppTheme(brightness: Brightness.dark),diff --git a/desktop/test/super_tab_composer_chips_bottom_test.dart b/desktop/test/super_tab_composer_chips_bottom_test.dartindex b80ce1e68..d922023fa 100644--- a/desktop/test/super_tab_composer_chips_bottom_test.dart+++ b/desktop/test/super_tab_composer_chips_bottom_test.dart@@ -14,11 +14,11 @@ import 'support/super_tab_fixture.dart';/// Set to a folder to write the PR's screenshots there.final shots = Platform.environment['SUPER_TAB_COMPOSER_CHIPS_SHOTS'];-/// Scholes, 11-03: the chips beside the message (New session, attach, send)-/// stay at the bottom-right of the box as the message grows, level with its-/// last line, rather than drifting to the middle of a tall box; one line-/// reads as before. The thread reply box keeps its chips on their own row-/// under the text.+/// Scholes, 11-03: the chips (New session, attach, send) stay at the+/// bottom-right of the box as the message grows, rather than drifting to the+/// middle of a tall box. Since the composer took the phone's layout (Huy and+/// Scholes, 11-04), they sit on one row under the text, in the main chat as+/// in a thread, with send at its right end.void main() {setUpAll(() async {if (shots != null) await loadPreviewFonts();@@ -132,54 +132,33 @@ void main() {const ValueKey('super-message-composer-surface'),);- testWidgets('one line: the chips are centered on the line, as before', (- tester,- ) async {- await show(tester);- final box = field(thread: false);- await type(tester, box, 'Check the release notes.');- final line = lastLine(tester, box);- for (final chip in chips) {+ for (final (lines, text) in [+ ('one line', 'Check the release notes.'),+ ('five lines', fiveLines),+ ]) {+ testWidgets('$lines: the chips stay on one row under the last line, '+ 'send at the bottom-right', (tester) async {+ await show(tester);+ final box = field(thread: false);+ await type(tester, box, text);+ final line = lastLine(tester, box);+ final row = tester.getRect(chips.last);+ for (final chip in chips) {+ final rect = tester.getRect(chip);+ expect(rect.top, greaterThanOrEqualTo(line.bottom), reason: '$chip');+ expect((rect.center.dy - row.center.dy).abs(), lessThan(1));+ expect(+ rect.bottom,+ lessThanOrEqualTo(tester.getRect(surface).bottom),+ );+ }+ expect(row.right, greaterThan(tester.getRect(surface).right - 16));expect(- (tester.getCenter(chip).dy - line.center.dy).abs(),- lessThan(1),- reason: '$chip',+ tester.getRect(surface).bottom - row.bottom,+ lessThanOrEqualTo(16),);- }- // One control row inside its padding.- expect(- tester.getRect(surface).height,- closeTo(grid.AppControl.heightFieldScaled + 6, 1),- );- });-- testWidgets('five lines: the chips stay at the bottom-right, level with '- 'the last line', (tester) async {- await show(tester);- final box = field(thread: false);- await type(tester, box, fiveLines);- final line = lastLine(tester, box);- final first = tester.getRect(box).top;- expect(line.top - first, greaterThan(line.height * 3.5));- for (final chip in chips) {- final rect = tester.getRect(chip);- expect(- (rect.center.dy - line.center.dy).abs(),- lessThan(1),- reason: '$chip',- );- expect(rect.bottom, lessThanOrEqualTo(tester.getRect(surface).bottom));- }- // Send at the right end, and the text keeps its width.- expect(- tester.getRect(chips.last).right,- greaterThan(tester.getRect(surface).right - 16),- );- expect(- tester.getRect(box).right,- lessThanOrEqualTo(tester.getRect(chips.first).left),- );- });+ });+ }});testWidgets('the thread reply box: its chips stay on their own row under the 'diff --git a/desktop/test/super_tab_composer_layout_test.dart b/desktop/test/super_tab_composer_layout_test.dartindex 278a2030f..d757a17e2 100644--- a/desktop/test/super_tab_composer_layout_test.dart+++ b/desktop/test/super_tab_composer_layout_test.dart@@ -34,9 +34,10 @@ void main() {for (final brightness in Brightness.values) {for (final scale in [1.0, 2.0]) {- testWidgets('composer text centers in ${brightness.name} at ${scale}x', (- tester,- ) async {+ // Huy and Scholes, 11-04: the text has its own line above the row of+ // actions, as on the phone; the caret and the hint centre on it.+ testWidgets('composer text sits on its line above the actions in '+ '${brightness.name} at ${scale}x', (tester) async {final previousBrightness = grid.AppTheme.brightness.value;grid.AppTheme.brightness.value = brightness;addTearDown(() {@@ -116,12 +117,17 @@ void main() {});}debugPrint('Composer $name: ${measurements[name]}');- expect(editableRect.center.dy, closeTo(rect.center.dy, .75));- expect(caret.center.dy, closeTo(rect.center.dy, .75));+ final actions = tester.getRect(+ find.byKey(const ValueKey('super-message-composer-actions')),+ );+ expect(editableRect.top, greaterThan(rect.top));+ expect(editableRect.bottom, lessThanOrEqualTo(actions.top));+ expect(actions.bottom, lessThanOrEqualTo(rect.bottom));+ expect(caret.center.dy, closeTo(editableRect.center.dy, .75));if (name == 'empty') {expect(tester.getRect(hint).center.dy,- closeTo(rect.center.dy, .75),+ closeTo(editableRect.center.dy, .75),);}}diff --git a/desktop/test/super_tab_composer_row_shots_test.dart b/desktop/test/super_tab_composer_row_shots_test.dartnew file mode 100644index 000000000..6f67efac5--- /dev/null+++ b/desktop/test/super_tab_composer_row_shots_test.dart@@ -0,0 +1,138 @@+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/workspace_chrome.dart';+import 'package:harness/super_tabs/view.dart';+import 'package:harness/super_tabs/voice_recorder.dart';++import 'box_render_preview_test.dart' show loadPreviewFonts;+import 'support/super_tab_fixture.dart';++/// Set to a folder to write the PR's screenshots there.+final shots = Platform.environment['SUPER_TAB_COMPOSER_ROW_SHOTS'];++/// A recorder for the mic's place only: no take is recorded.+class _Preview implements SuperTabVoiceRecorder {+ @override+ Future<void> start({required String conversationId, String? root}) async {}+}++/// The composer as the PR shows it (Huy and Scholes, 11-04): the reader's+/// Buddy chat with New session on offer, a project chat's thread with Also+/// send, the mic's place once recording comes (`chat-mic`), and the web at a+/// phone's width (`web-phone`), each with a draft, in both appearances.+void main() {+ setUpAll(() async {+ if (shots != null) await loadPreviewFonts();+ });++ ConversationServer buddyChat() {+ final server = ConversationServer()..threads = true;+ server.state['threadSessions'] = true;+ server.state['sessionsFromChat'] = true;+ final chat = (server.state['conversations'] as List)[1] as Map;+ chat+ ..['kind'] = 'buddy'+ ..['buddyOwnerId'] = 'owner'+ ..['title'] = 'Wren'+ ..['agentIds'] = ['buddy-main'];+ (server.state['agents'] as List).add({+ 'id': 'buddy-main',+ 'name': 'Wren',+ 'displayName': 'Wren',+ 'machineId': 'mac',+ 'harnessId': 'h-main',+ 'contributorId': 'owner',+ 'buddyOf': {'personId': 'owner', 'generation': 'g1'},+ 'configuration': {'engine': 'claude'},+ });+ server.append(+ 'Measure prod CPU for the last day',+ conversationId: 'offline',+ );+ return server;+ }++ ConversationServer projectThread() {+ final server = ConversationServer()..threads = true;+ server.append('The build fails on the second run. Logs attached below.');+ server.append('Which machine was it on? Please send the trace.');+ server.messages.last+ ..['thread'] = 'message-1'+ ..['replyTo'] = 'message-1';+ return server;+ }++ for (final brightness in Brightness.values) {+ for (final scene in ['chat', 'thread', 'chat-mic', 'web-phone']) {+ testWidgets('screenshot: $scene (${brightness.name})', (tester) async {+ final picture = GlobalKey();+ final thread = scene == 'thread';+ final c = (thread ? projectThread() : buddyChat()).controller();+ addTearDown(c.dispose);+ await c.refresh();+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);+ final phone = scene == 'web-phone';+ await tester.binding.setSurfaceSize(+ phone ? const Size(390, 844) : const Size(1280, 720),+ );+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) =>+ RepaintBoundary(key: picture, child: child),+ home: WorkspaceChromeScope(+ // A phone's browser draws the compact layout below 720 px.+ chrome: WorkspaceChrome(compactBelow: phone ? 720 : 0),+ child: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Mac Studio',+ voiceRecorder: scene == 'chat-mic' ? _Preview() : null,+ ),+ ),+ ),+ ),+ );+ if (!thread) await c.select('offline');+ await tester.pumpAndSettle();+ if (thread) {+ c.openThread('message-1');+ await tester.pumpAndSettle();+ }+ await tester.enterText(+ find.byKey(+ ValueKey(+ thread ? 'super-thread-composer' : 'super-message-composer',+ ),+ ),+ thread ? 'Here is the trace.' : 'Can you check the release notes?',+ );+ await tester.pumpAndSettle();++ await tester.runAsync(() async {+ final boundary =+ picture.currentContext!.findRenderObject()!+ as RenderRepaintBoundary;+ final image = await boundary.toImage(pixelRatio: 1.5);+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);+ await Directory(shots!).create(recursive: true);+ await File('$shots/composer-$scene-${brightness.name}.png')+ .writeAsBytes(bytes!.buffer.asUint8List());+ image.dispose();+ });+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ }, skip: shots == null);+ }+ }+}diff --git a/desktop/test/super_tab_composer_row_test.dart b/desktop/test/super_tab_composer_row_test.dartnew file mode 100644index 000000000..defdc5852--- /dev/null+++ b/desktop/test/super_tab_composer_row_test.dart@@ -0,0 +1,324 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_icons.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/view.dart';+import 'package:harness/super_tabs/voice_recorder.dart';++import 'support/super_tab_fixture.dart';++/// The takes a mic started, as (conversation, thread root).+class _Recorder implements SuperTabVoiceRecorder {+ final takes = <(String, String?)>[];++ @override+ Future<void> start({required String conversationId, String? root}) async =>+ takes.add((conversationId, root));+}++/// Huy and Scholes, 11-04: the Desktop and web composer is the phone's. One+/// rounded box, the text on top and one row under it: + (attach), @ Tag, the+/// New session chip, the mic and send. Also send is a small checkbox under a+/// thread's box. The mic shows only with a recorder (River, 11-04: recording+/// is its own task), so nobody sees a button that does nothing.+void main() {+ const fiveLines =+ 'Five things for today:\nmeasure prod CPU\ncheck the '+ 'release notes\nanswer Diego\nand plan the next batch';++ /// The reader's Buddy chat with its Buddy running, so the row offers New+ /// session; Dee reads the Swarm, so @ has someone to offer.+ ConversationServer server() {+ final server = ConversationServer()..threads = true;+ server.state['threadSessions'] = true;+ server.state['sessionsFromChat'] = true;+ (server.state['people'] as List).add({+ 'id': 'dee',+ 'email': '[email protected]',+ 'role': 'collaborator',+ });+ final chat = (server.state['conversations'] as List)[1] as Map;+ chat+ ..['kind'] = 'buddy'+ ..['buddyOwnerId'] = 'owner'+ ..['title'] = 'Wren'+ ..['agentIds'] = ['buddy-main'];+ (server.state['agents'] as List).add({+ 'id': 'buddy-main',+ 'name': 'Wren',+ 'displayName': 'Wren',+ 'machineId': 'mac',+ 'harnessId': 'h-main',+ 'contributorId': 'owner',+ 'buddyOf': {'personId': 'owner', 'generation': 'g1'},+ 'configuration': {'engine': 'claude'},+ });+ server.append('The build fails on the second run.');+ server.append('Which machine was it on?');+ server.messages.last+ ..['thread'] = 'message-1'+ ..['replyTo'] = 'message-1';+ server.append('Measure prod CPU', conversationId: 'offline');+ server.append('On it', conversationId: 'offline');+ server.messages.last+ ..['thread'] = 'message-3'+ ..['replyTo'] = 'message-3';+ return server;+ }++ Future<SuperTabController> show(+ WidgetTester tester, {+ String chat = 'offline',+ String? thread,+ SuperTabVoiceRecorder? recorder,+ }) async {+ final c = server().controller();+ addTearDown(c.dispose);+ await c.refresh();+ await tester.binding.setSurfaceSize(const Size(1280, 720));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.light),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Mac Studio',+ voiceRecorder: recorder,+ ),+ ),+ ),+ );+ await c.select(chat);+ await tester.pumpAndSettle();+ if (thread != null) {+ c.openThread(thread);+ await tester.pumpAndSettle();+ }+ return c;+ }++ Finder key(String value) => find.byKey(ValueKey(value));++ /// The focused widget's element is [target]'s or one of its descendants'.+ bool focusedIn(WidgetTester tester, Finder target) {+ final focused = FocusManager.instance.primaryFocus?.context;+ if (focused == null) return false;+ final element = tester.element(target);+ if (focused == element) return true;+ var inside = false;+ focused.visitAncestorElements((e) {+ inside = e == element;+ return !inside;+ });+ return inside;+ }++ group('the main chat', () {+ Finder attach() => find.descendant(+ of: key('super-message-composer-surface'),+ matching: key('new-harness-attach'),+ );+ Finder send() => find.byTooltip('Send message');++ testWidgets('holds +, @ Tag and New session under the text, and send at '+ 'the row\'s right end', (tester) async {+ await show(tester);+ for (final text in ['One line', fiveLines]) {+ await tester.enterText(key('super-message-composer'), text);+ await tester.pumpAndSettle();+ final field = tester.getRect(key('super-message-composer'));+ final surface = tester.getRect(key('super-message-composer-surface'));+ final plus = tester.getRect(attach());+ final tag = tester.getRect(key('super-composer-tag'));+ final session = tester.getRect(key('super-chat-new-session'));+ final arrow = tester.getRect(send());+ expect(key('super-message-composer-actions'), findsOneWidget);+ for (final button in [plus, tag, session, arrow]) {+ expect(button.top, greaterThanOrEqualTo(field.bottom), reason: text);+ }+ expect(plus.left, lessThan(tag.left));+ expect(tag.left, lessThan(session.left));+ expect(session.right, lessThan(arrow.left));+ // Send keeps the box's bottom-right corner however long the message+ // (Scholes, 11-03), the box's inset from its edges.+ expect(+ surface.right - arrow.right,+ lessThanOrEqualTo(grid.AppDesktop.groupGap),+ );+ expect(+ surface.bottom - arrow.bottom,+ lessThanOrEqualTo(grid.AppDesktop.groupGap),+ );+ }+ expect(+ find.descendant(of: attach(), matching: find.byIcon(AppIcons.plus)),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: key('super-composer-tag'),+ matching: find.byIcon(AppIcons.atSign),+ ),+ findsOneWidget,+ );+ });++ testWidgets('shows no mic without a recorder, and no Also send', (+ tester,+ ) async {+ await show(tester);+ expect(key('super-composer-mic'), findsNothing);+ expect(key('super-thread-also-send'), findsNothing);+ });++ testWidgets('puts the mic left of send, and a click starts a take for the '+ 'chat', (tester) async {+ final recorder = _Recorder();+ await show(tester, recorder: recorder);+ final mic = tester.getRect(key('super-composer-mic'));+ expect(mic.right, lessThanOrEqualTo(tester.getRect(send()).left));+ expect(+ mic.left,+ greaterThan(tester.getRect(key('super-chat-new-session')).right),+ );+ await tester.tap(key('super-composer-mic'));+ await tester.pump();+ expect(recorder.takes, [('offline', null)]);+ // A take is never dictation: the box stays as it was.+ expect(+ tester+ .widget<TextField>(key('super-message-composer'))+ .controller!+ .text,+ isEmpty,+ );+ });++ testWidgets('@ Tag types @ at the caret and opens the tag list', (+ tester,+ ) async {+ await show(tester);+ await tester.enterText(key('super-message-composer'), 'hi');+ await tester.pump();+ await tester.tap(key('super-composer-tag'));+ await tester.pumpAndSettle();+ final field = tester.widget<TextField>(key('super-message-composer'));+ expect(field.controller!.text, 'hi @');+ expect(field.controller!.selection.baseOffset, 4);+ expect(key('super-composer-completions'), findsOneWidget);+ expect(focusedIn(tester, key('super-message-composer')), isTrue);+ // Enter picks from the list, as for an @ typed.+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pumpAndSettle();+ expect(field.controller!.text, startsWith('hi @'));+ expect(field.controller!.text.length, greaterThan(4));+ });++ testWidgets('Tab goes from the text to +, @ Tag, New session, the mic and '+ 'send, in the row\'s order', (tester) async {+ await show(tester, recorder: _Recorder());+ await tester.enterText(key('super-message-composer'), 'Ready');+ await tester.pump();+ expect(focusedIn(tester, key('super-message-composer')), isTrue);+ for (final next in [+ attach(),+ key('super-composer-tag'),+ key('super-chat-new-session'),+ key('super-composer-mic'),+ send(),+ ]) {+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);+ await tester.pump();+ expect(focusedIn(tester, next), isTrue, reason: '$next');+ }+ // The draft's save runs out.+ await tester.pump(const Duration(seconds: 1));+ });+ });++ group('a thread', () {+ Finder attach() => find.descendant(+ of: key('super-thread-composer-surface'),+ matching: key('new-harness-attach'),+ );++ testWidgets('holds +, @ Tag and New session under the text, send at the '+ 'right end, and Also send on its own line under the box', (+ tester,+ ) async {+ await show(tester, thread: 'message-3');+ await tester.enterText(key('super-thread-composer'), fiveLines);+ await tester.pumpAndSettle();+ final field = tester.getRect(key('super-thread-composer'));+ final surface = tester.getRect(key('super-thread-composer-surface'));+ final plus = tester.getRect(attach());+ final tag = tester.getRect(key('super-thread-tag'));+ final session = tester.getRect(key('super-thread-new-session'));+ final send = tester.getRect(key('super-thread-send'));+ for (final button in [plus, tag, session, send]) {+ expect(button.top, greaterThanOrEqualTo(field.bottom));+ expect(button.bottom, lessThanOrEqualTo(surface.bottom));+ }+ expect(plus.left, lessThan(tag.left));+ expect(tag.left, lessThan(session.left));+ expect(session.right, lessThan(send.left));+ expect(+ find.descendant(of: attach(), matching: find.byIcon(AppIcons.plus)),+ findsOneWidget,+ );+ // Also send is under the box, whatever room the row has.+ final also = tester.getRect(key('super-thread-also-send'));+ expect(also.top, greaterThanOrEqualTo(surface.bottom));+ expect(+ find.descendant(+ of: key('super-thread-also-line'),+ matching: key('super-thread-also-send'),+ ),+ findsOneWidget,+ );+ expect(find.text('Also send to the main chat'), findsOneWidget);+ expect(key('super-thread-mic'), findsNothing);+ });++ testWidgets('names the project chat in Also send', (tester) async {+ await show(tester, chat: 'lead', thread: 'message-1');+ expect(find.text('Also send to #Pilot'), findsOneWidget);+ expect(+ tester.getRect(key('super-thread-also-send')).top,+ greaterThanOrEqualTo(+ tester.getRect(key('super-thread-composer-surface')).bottom,+ ),+ );+ });++ testWidgets('puts the mic left of send, and a click starts a take for the '+ 'thread', (tester) async {+ final recorder = _Recorder();+ await show(tester, thread: 'message-3', recorder: recorder);+ expect(+ tester.getRect(key('super-thread-mic')).right,+ lessThanOrEqualTo(tester.getRect(key('super-thread-send')).left),+ );+ await tester.tap(key('super-thread-mic'));+ await tester.pump();+ expect(recorder.takes, [('offline', 'message-3')]);+ });++ testWidgets('@ Tag types @ at the caret and opens the tag list', (+ tester,+ ) async {+ await show(tester, chat: 'lead', thread: 'message-1');+ await tester.tap(key('super-thread-tag'));+ await tester.pumpAndSettle();+ final field = tester.widget<TextField>(key('super-thread-composer'));+ expect(field.controller!.text, '@');+ expect(key('super-thread-completions'), findsOneWidget);+ });+ });+}diff --git a/desktop/test/super_tab_delivery_test.dart b/desktop/test/super_tab_delivery_test.dartindex 59e18f239..f878cd23b 100644--- a/desktop/test/super_tab_delivery_test.dart+++ b/desktop/test/super_tab_delivery_test.dart@@ -211,10 +211,16 @@ void main() {}await shot('delivery');expect(server.posts, isEmpty);+ // In the small, large-text window the card is taller than the list+ // above the composer's two rows: the reader scrolls to its actions.+ await tester.ensureVisible(find.text('Open terminal'));+ await tester.pumpAndSettle();await tester.tap(find.text('Open terminal'));await tester.pumpAndSettle();expect(opened, 'lead-agent');expect(server.posts, isEmpty);+ await tester.ensureVisible(find.text('It arrived'));+ await tester.pumpAndSettle();await tester.tap(find.text('It arrived'));await tester.pumpAndSettle();expect((server.posts.single['command'] as Map), {diff --git a/desktop/test/super_tab_new_messages_test.dart b/desktop/test/super_tab_new_messages_test.dartindex eecbe94f1..6ffd56666 100644--- a/desktop/test/super_tab_new_messages_test.dart+++ b/desktop/test/super_tab_new_messages_test.dart@@ -506,6 +506,8 @@ void main() {await tester.pumpAndSettle();expect(onScreen(tester, find.byKey(_line)), isTrue);expect(find.byKey(_jump), findsNothing);+ // Read to the end: the mark's save runs out.+ await tester.pump(const Duration(seconds: 1));});testWidgets('with the message list focused, Esc dismisses the bar and 'diff --git a/desktop/test/super_tab_phone_composer_test.dart b/desktop/test/super_tab_phone_composer_test.dartindex c6cbdf776..e14800d3a 100644--- a/desktop/test/super_tab_phone_composer_test.dart+++ b/desktop/test/super_tab_phone_composer_test.dart@@ -117,16 +117,20 @@ void main() {await unmountPhoneSuperTab(tester, c);});- testWidgets('a wider window keeps one row', (tester) async {+ // Huy and Scholes, 11-04: a wide window lays the composer out as the phone+ // does, the field on top and its actions on a row under it.+ testWidgets('a wider window has the phone\'s row under the field', (+ tester,+ ) async {final (_, c) = await mountPhoneSuperTab(tester,const Size(1280, 800),desktop: true,);- expect(_actions, findsNothing);+ expect(_actions, findsOneWidget);final field = tester.getRect(_field), send = tester.getRect(_send);- expect(send.left, greaterThanOrEqualTo(field.right));- expect(send.center.dy, closeTo(field.center.dy, 12));+ expect(send.top, greaterThanOrEqualTo(field.bottom));+ expect(send.right, greaterThan(field.center.dx));await unmountPhoneSuperTab(tester, c);});diff --git a/desktop/test/super_tab_reply_box_test.dart b/desktop/test/super_tab_reply_box_test.dartindex 294653fb3..befd77009 100644--- a/desktop/test/super_tab_reply_box_test.dart+++ b/desktop/test/super_tab_reply_box_test.dart@@ -160,7 +160,7 @@ void main() {}/// Every option sits on the send button's row, vertically centred with it,- /// left of attach and send, inside the box.+ /// left of send, inside the box.void expectOneRow(WidgetTester tester, List<Finder> chips) {final sendRect = tester.getRect(send);final box = tester.getRect(surface);@@ -168,7 +168,9 @@ void main() {for (final chip in chips) {final rect = tester.getRect(chip);expect((rect.center.dy - sendRect.center.dy).abs(), lessThan(1));- expect(rect.right, lessThan(sendRect.left));+ // Never past send: in a pane narrower than the app allows, New session+ // ends in "…" against it.+ expect(rect.right, lessThanOrEqualTo(sendRect.left));expect(rect.left, greaterThanOrEqualTo(box.left));if (right != null) expect(rect.left, greaterThan(right));right = rect.right;@@ -189,27 +191,18 @@ void main() {);}- /// Also send's [label] on its line under the box: whole wherever it- /// measures to fit that line in the face drawn (the Mac's face fits it at- /// every width the app allows, the screenshots show); in a face too wide- /// for even that (the test font on Linux CI), it ends in "…" there and- /// nothing overflows.+ /// Also send's [label] on its line under the box: whole where the face+ /// drawn has room for it (the Mac's face at every width the app allows, the+ /// screenshots show); in a face too wide for that (the test font on Linux+ /// CI), it ends in "…" there and nothing overflows.void expectWholeUnderBox(WidgetTester tester, String label) {- final room = tester.getRect(surface).width - 16;- if (SuperTabComposerToggle.widthOf(tester.element(alsoSend), label) <=- room) {- expectWhole(tester, alsoSend, label);- } else {- final text = find.descendant(of: alsoSend, matching: find.text(label));- expect(- tester.renderObject<RenderParagraph>(text).didExceedMaxLines,- isTrue,- );- expect(- tester.getRect(alsoSend).right,- lessThanOrEqualTo(tester.getRect(surface).right),- );- }+ final text = find.descendant(of: alsoSend, matching: find.text(label));+ final paragraph = tester.renderObject<RenderParagraph>(text);+ if (!paragraph.didExceedMaxLines) expectWhole(tester, alsoSend, label);+ expect(+ tester.getRect(alsoSend).right,+ lessThanOrEqualTo(tester.getRect(surface).right),+ );}/// Also send on its own line under the box, its square under the send@@ -233,98 +226,43 @@ void main() {expect(rect.right, lessThanOrEqualTo(box.right));}+ // Huy and Scholes, 11-04: Also send is a small checkbox on its own line+ // under the box, as in Slack, never on the send row; its wording in full+ // (Scholes, 11-03: "Also to chat" did not say where the reply goes).group('Also send names where it posts', () {- testBox('a project thread names the project chat in full', (tester) async {- await panel(tester, projectChat(), 'lead', width: 800);- expect(box(tester, alsoSend).label, 'Also post to #Pilot');- expect(- find.byTooltip('Also post to #Pilot as well as this thread'),- findsOneWidget,- );- expectOneRow(tester, [alsoSend]);- });-- testBox('a Buddy thread with room says the main chat in full, beside '- 'New session', (tester) async {- await panel(tester, buddyChat(), 'offline', width: 800);- expect(box(tester, alsoSend).label, 'Also post to the main chat');- expect(- find.byTooltip('Also post to the main chat as well as this thread'),- findsOneWidget,- );- expectOneRow(tester, [newSession, alsoSend]);- });-- /// The width the send row's options have in a thread pane [pane] wide:- /// the pane less the box's insets and attach and send, as laid out.- double Function(double pane) roomIn(WidgetTester tester) {- final sendRow = tester.getRect(- find.byKey(const ValueKey('new-harness-attach')),- );- final box = tester.getRect(surface);- final pane = tester.getRect(find.byType(SuperTabThreadPanel));- // The rim is drawn, not laid out: the options start 16 in.- final insets = pane.width - (sendRow.left - box.left - 16);- return (width) => width - insets;- }-- double widthOf(WidgetTester tester, String label) =>- SuperTabComposerToggle.widthOf(tester.element(alsoSend), label);-- // Scholes, 11-03: "Also to chat" did not say where the reply goes. The- // full wording always shows; where it has no room beside New session,- // Also send takes its own line under the box.for (final (kind, full, short) in [- ('project', 'Also post to #Pilot', 'Also to #Pilot'),- ('Buddy', 'Also post to the main chat', 'Also to chat'),+ ('project', 'Also send to #Pilot', 'Also to #Pilot'),+ ('Buddy', 'Also send to the main chat', 'Also to chat'),]) {- testBox('a $kind thread keeps "$full" on the send row while it fits, '- 'and moves it, in full, to its own line under the box where it does '- 'not', (tester) async {+ testBox('a $kind thread says "$full" on its own line under the box, at '+ 'every width', (tester) async {final buddy = kind == 'Buddy';ConversationServer server() => buddy ? buddyChat() : projectChat();final conversation = buddy ? 'offline' : 'lead';- await panel(tester, server(), conversation, width: 800);- final room = roomIn(tester);- final beside = buddy ? widthOf(tester, 'New session') + 4 : 0.0;- final fullFits = widthOf(tester, full) + beside;- double paneFor(double needed) => 800 - room(800) + needed;- await tester.pumpWidget(const SizedBox());- await shown.flush();-- for (final (pane, below) in [- (paneFor(fullFits) + 1, false),- (paneFor(fullFits) - 1, true),- for (final width in [- SuperTabPaneLayout.threadWidth,- SuperTabPaneLayout.rightWidth,- ])- (width, paneFor(fullFits) > width),+ for (final pane in [+ 800.0,+ SuperTabPaneLayout.threadWidth,+ SuperTabPaneLayout.rightWidth,]) {await panel(tester, server(), conversation, width: pane);expect(box(tester, alsoSend).label, full, reason: 'at $pane');expect(find.text(short), findsNothing);- if (below) {- expectWholeUnderBox(tester, full);- } else {- expectWhole(tester, alsoSend, full);- }expect(find.byTooltip('$full as well as this thread'),findsOneWidget,);+ expectUnderBox(tester);+ if (pane == 800) {+ expectWhole(tester, alsoSend, full);+ } else {+ expectWholeUnderBox(tester, full);+ }if (buddy) {expect(box(tester, newSession).label, 'New session');expectOneRow(tester, [newSession]);expectMark(tester, newSession, on: false);}expectMark(tester, alsoSend, on: false);- if (below) {- expectUnderBox(tester);- } else {- expect(alsoLine, findsNothing, reason: 'at $pane');- expectOneRow(tester, [if (buddy) newSession, alsoSend]);- }expect(tester.takeException(), isNull);await tester.pumpWidget(const SizedBox());await shown.flush();@@ -446,8 +384,9 @@ void main() {(SuperTabPaneLayout.rightWidth, 2.0),]) {testBox('${width.round()}px at ${scale}x: no overflow, New session on '- 'the send row, both squares showing, Also send in full on the row '- 'or under the box', (tester) async {+ 'the send row, both squares showing, Also send under the box', (+ tester,+ ) async {await panel(tester,buddyChat(),@@ -459,25 +398,17 @@ void main() {expectOneRow(tester, [newSession]);expectMark(tester, newSession, on: false);expectMark(tester, alsoSend, on: false);- expect(box(tester, alsoSend).label, 'Also post to the main chat');- if (alsoLine.evaluate().isEmpty) {- expectOneRow(tester, [newSession, alsoSend]);- } else {- expectUnderBox(tester);- }- if (alsoLine.evaluate().isEmpty) {- expectWhole(tester, alsoSend, 'Also post to the main chat');- } else {- expectWholeUnderBox(tester, 'Also post to the main chat');- }+ expect(box(tester, alsoSend).label, 'Also send to the main chat');+ expectUnderBox(tester);+ expectWholeUnderBox(tester, 'Also send to the main chat');});}- testBox('a project thread in a wide pane keeps its row with only Also '- 'send', (tester) async {+ testBox('a project thread in a wide pane has no New session, and Also '+ 'send under the box', (tester) async {await panel(tester, projectChat(), 'lead', width: 800);expect(newSession, findsNothing);- expectOneRow(tester, [alsoSend]);+ expectUnderBox(tester);});testBox('in the narrow layout, turning New session on and off never moves '@@ -507,16 +438,17 @@ void main() {});});- // The keyboard order stays as it was wherever Also send sits.+ // The row's order, then Also send under the box (Huy and Scholes, 11-04).for (final width in [800.0, SuperTabPaneLayout.rightWidth]) {- testBox('Tab goes from the reply to New session, Also send, attach and '+ testBox('Tab goes from the reply to +, @ Tag, New session, send and Also ''send at ${width.round()}px', (tester) async {await panel(tester, buddyChat(), 'offline', width: width);final order = [- newSession,- alsoSend,find.byKey(const ValueKey('new-harness-attach')),+ find.byKey(const ValueKey('super-thread-tag')),+ newSession,send,+ alsoSend,];// Send takes focus only with something to send.await tester.enterText(@@ -543,26 +475,22 @@ void main() {});}- // The default width was chosen for "New session" and "Also to chat" on one- // row (10-31); the full wording needs about 410px there, so at 340px it- // takes its own line, whole.testBox('at the thread\'s default width, in the Mac\'s face, a Buddy '- 'thread shows "New session" on the send row and "Also post to the main '+ 'thread shows "New session" on the send row and "Also send to the main ''chat" whole under the box, and a project thread names #openharness in '- 'full on the row', (tester) async {+ 'full under the box', (tester) async {await panel(tester, buddyChat(), 'offline');expectWhole(tester, newSession, 'New session');expectUnderBox(tester);- expectWhole(tester, alsoSend, 'Also post to the main chat');+ expectWhole(tester, alsoSend, 'Also send to the main chat');await tester.pumpWidget(const SizedBox());await shown.flush();final project = projectChat();project.state['name'] = 'openharness';await panel(tester, project, 'lead');- expect(box(tester, alsoSend).label, 'Also post to #openharness');- expect(alsoLine, findsNothing);- expectOneRow(tester, [alsoSend]);- expectWhole(tester, alsoSend, 'Also post to #openharness');+ expect(box(tester, alsoSend).label, 'Also send to #openharness');+ expectUnderBox(tester);+ expectWhole(tester, alsoSend, 'Also send to #openharness');}, skip: !systemFace);}diff --git a/desktop/test/super_tab_thread_scroll_test.dart b/desktop/test/super_tab_thread_scroll_test.dartindex 7a13194f3..37541e598 100644--- a/desktop/test/super_tab_thread_scroll_test.dart+++ b/desktop/test/super_tab_thread_scroll_test.dart@@ -201,7 +201,10 @@ void main() {c.openThread('message-1');await tester.pumpAndSettle();- await tester.drag(inPanel(find.byType(LaidOutListView)), const Offset(0, 400));+ await tester.drag(+ inPanel(find.byType(LaidOutListView)),+ const Offset(0, 400),+ );await tester.pumpAndSettle();final read = threadScroll(tester).pixels;expect(threadScroll(tester).extentAfter, greaterThan(40));@@ -287,7 +290,9 @@ void main() {addTearDown(c.dispose);c.openThread('message-1');await c.loadThread();- await tester.binding.setSurfaceSize(const Size(500, 575));+ // Just tall enough for all of it, Also send's line under the box included+ // (#2662).+ await tester.binding.setSurfaceSize(const Size(500, 592));addTearDown(() => tester.binding.setSurfaceSize(null));await tester.pumpWidget(MaterialApp(diff --git a/desktop/test/super_tab_threads_test.dart b/desktop/test/super_tab_threads_test.dartindex b50815cb6..507b82985 100644--- a/desktop/test/super_tab_threads_test.dart+++ b/desktop/test/super_tab_threads_test.dart@@ -529,7 +529,7 @@ void main() {});testWidgets('a reply from the thread composer goes to the root, and '- '"Also post to #Pilot" sends it to both', (tester) async {+ '"Also send to #Pilot" sends it to both', (tester) async {final server = threaded();final c = await show(tester, server);// The test platform's touch handles sit under a typed reply's end:@@ -540,7 +540,7 @@ void main() {// The label shortens where the test font leaves no room; its hint keeps// the full wording (super_tab_reply_box_test.dart covers the label).expect(- inPanel(find.byTooltip('Also post to #Pilot as well as this thread')),+ inPanel(find.byTooltip('Also send to #Pilot as well as this thread')),findsOneWidget,);await tester.enterText(diff --git a/docs/plans/2026-11-04-desktop-composer-like-phone-plan.md b/docs/plans/2026-11-04-desktop-composer-like-phone-plan.mdnew file mode 100644index 000000000..f2bc43753--- /dev/null+++ b/docs/plans/2026-11-04-desktop-composer-like-phone-plan.md@@ -0,0 +1,63 @@+# Desktop and Web Swarm Composer Like the Phone's Implementation Plan++> **For agentic workers:** The assigned Engineer implements this plan task by task in this session, test first, by the project's instructions. No subagents: the two composers share their new buttons.++**Goal:** The Desktop and web Swarm composer, in the main chat and in a thread, is the phone's: one rounded box with the text on top and one row under it holding + (attach), @ Tag, the New session chip, a mic slot and send; Also send is a small checkbox under the box, in threads only.++**Architecture:** The main chat's `_composerLayout` (`view.dart`) gives every width the two-row layout a phone already has (field on top, actions below), keeping only the squeezed one-row layout for a phone with too little height. `SuperTabReplyBox` (`reply_box.dart`) takes the same row. The row's new buttons live in `composer_actions.dart`: an @ Tag button that types `@` at the caret, so the existing tag list opens, and a mic that starts a take on a `SuperTabVoiceRecorder` (`voice_recorder.dart`). No recorder is given yet, so no mic shows (River, 11-04: recording, the `record` package and the macOS microphone entitlement are a follow-up task). The thread's Also send leaves the send row for its own line under the box, always, so its width is no longer measured.++**Tech Stack:** Flutter (Desktop, web build of the same code), flutter_test widget tests with the `ConversationServer` fixture (memory store, fake sign-in).++**Spec:** Swarm task #2662, conversation 6a9ff95c03fa38a4851f6cc7 (Huy and Scholes, 11-04; River's split, 11-04).++## Global Constraints++- Harness Design Language: tokens only (`grid.AppDesktop`, `DesktopChrome`, `AppIcons`), no hard-coded colours or sizes, nothing explanatory added.+- Icons only through `AppIcons`, weight 400 (`audit-icons.py`, `icon_catalog_render_test`, `lucide_weight_test`).+- Enter sends, Shift+Enter adds a line; every button is reachable with Tab, in the row's order.+- No formatting toolbar: Desktop has none today, and none is added.+- Kept from Scholes, 11-03: send stays at the bottom-right of the box however many lines are typed (#2763); New session and Also send are square checkboxes with their full wording (thread composer).+- The mic never shows without a recorder: no button that does nothing.+- `NewHarnessAttachButton` keeps its paperclip in the New harness form; only the Swarm composers pass +.+- Before and after screenshots, light and dark, offscreen on a Team account.+- PR body first line: "Requested by [email protected] through Harness."++## Review Focus++- A five-line message: the row stays under the last line, send at the bottom-right, nothing overlapping the text.+- The Swarm Buddy chat with New session on: the project picker fits in the row beside New session at the narrowest Desktop width.+- @ Tag after a word ("hi|") types " @", at the start "@"; the tag list opens and Enter picks from it, not send.+- A thread with its own session (no Also send) and one that starts a session: the line under the box keeps its place, so the box does not move as New session is toggled.+- Phone-width web keeps fitting 320x568 with the keyboard up (the squeezed row below 320 px of room).++---++### Task 1: The main chat composer's row++**Files:**+- Create: `desktop/lib/super_tabs/composer_actions.dart`, `desktop/lib/super_tabs/voice_recorder.dart`+- Modify: `desktop/lib/super_tabs/view.dart` (`_composerLayout`, the composer row, `SuperTabView.voiceRecorder`), `desktop/lib/super_tabs/composer_tags.dart` (`superTabTagPrompt`), `desktop/lib/widgets/new_harness_attachments.dart` (`icon`), `desktop/lib/shared/theme/app_icons.dart` (`atSign`, `mic`)+- Test: `desktop/test/super_tab_composer_row_test.dart`; update `super_tab_composer_chips_bottom_test.dart`++**Interfaces:**+- Produces: `abstract interface class SuperTabVoiceRecorder { Future<void> start({required String conversationId, String? root}); }`; `TextEditingValue superTabTagPrompt(TextEditingValue value)`; `SuperTabComposerTagButton({Key? key, required VoidCallback? onPressed})`; `SuperTabComposerMic({Key? key, required VoidCallback? onPressed})`; `SuperTabView(voiceRecorder: SuperTabVoiceRecorder?)`.++- [ ] **Step 1: Write the failing tests** at 1280x720 in the reader's Buddy chat: the field is above `super-message-composer-actions`; the row reads +, @, New session left to right, then send at its right end, all under the field; no `super-composer-mic` without a recorder; with a fake recorder the mic sits left of send and a tap starts one take for the chat; @ Tag after "hi" makes "hi @" and opens `super-composer-completions`; Tab from the field reaches +, @, New session, mic, send in that order; Enter sends and Shift+Enter breaks the line from the new layout.+- [ ] **Step 2: Run them and watch them fail** — `flutter test test/super_tab_composer_row_test.dart` (the row and its buttons are missing).+- [ ] **Step 3: Commit the failing tests**+- [ ] **Step 4: Implement** the row, the buttons and the seam; update `super_tab_composer_chips_bottom_test.dart` to the new layout (send at the bottom-right, under the last line).+- [ ] **Step 5: Run** `super_tab_composer_row_test`, `super_tab_composer_chips_bottom_test`, `super_tab_composer_layout_test`, `super_tab_phone_composer_test`, `super_tab_phone_targets_test`, `super_tab_composer_newline_test`, `super_tab_completions_test` and the tests that find `new-harness-attach`.+- [ ] **Step 6: Commit**++### Task 2: The thread composer's row and Also send under the box++**Files:**+- Modify: `desktop/lib/super_tabs/reply_box.dart`, `desktop/lib/super_tabs/thread_panel.dart`, `desktop/lib/super_tabs/view.dart` (pass the recorder)+- Test: `desktop/test/super_tab_composer_row_test.dart` (thread group); update `super_tab_reply_box_test.dart`++- [ ] **Step 1: Write the failing tests**: the thread's row reads +, @, New session, then send at its right end; Also send (`super-thread-also-send`) is always on its own line under the box (`super-thread-also-line`), reading "Also send to #openharness" in the project chat and "Also send to the main chat" elsewhere; the main chat has no Also send; with a fake recorder the thread's mic starts a take for that thread's root.+- [ ] **Step 2: Run them and watch them fail**+- [ ] **Step 3: Commit the failing tests**+- [ ] **Step 4: Implement**; remove `_alsoBelow` and its measuring; update `super_tab_reply_box_test.dart`.+- [ ] **Step 5: Run** the thread tests (`super_tab_reply_box_test`, `super_tab_thread_composer_test`, `super_tab_thread_tags_test`, `super_tab_threads_test`, `super_tab_buddy_sessions_test`) and the guards: `python3 scripts/check-ui-style.py --only desktop/lib/super_tabs`, `python3 desktop/scripts/audit-icons.py`, `icon_catalog_render_test`, `lucide_weight_test`, `laid_out_list_test`.+- [ ] **Step 6: Commit**, then the before (main) and after screenshots, light and dark, from `super_tab_composer_row_shots_test.dart`.diff --git a/docs/plans/2026-11-04-pm-built-in-schedule-design.md b/docs/plans/2026-11-04-pm-built-in-schedule-design.mdnew file mode 100644index 000000000..3fcbdf90e--- /dev/null+++ b/docs/plans/2026-11-04-pm-built-in-schedule-design.md@@ -0,0 +1,235 @@+# Every project's PM runs a built-in schedule, woken by the Swarm++Status: design, 2026-11-04. Requested by Ken.++## Why++Only two of the six projects give their PM a schedule: openharness (River's "PM schedule" section) and lampos (Leo's+rules). In physical-router, garage-pod, computer and spaceship the PM acts only when a notice or a person reaches it, so a+task nobody owns, or one waiting on a person nobody asked, sits until someone looks. Where a schedule exists, the PM keeps+it on its own timer: a timer its engine may not have (a Codex PM), and one lost on every session restart until the PM+remembers to recreate it.++Ken, 2026-11-04:++- The PM jobs every project needs are loaded by default for every project's PM, appended to the project's instructions,+ not copied into each document.+- A line in the project's own instructions wins over the default.+- The Swarm wakes the PM for them; the PM sets no timer of its own for them.+- Jobs due at the same time go in one message.+- The PM must know these jobs exist, so it does not do the same work twice.+- openharness drops the three lines of its own schedule that the default now covers.++## Goals++- Every project's PM, existing and new, gets the same jobs with no change to its document.+- The PM is woken for them on time without a timer of its own, across restarts and engines.+- The PM knows which jobs are the Swarm's, and never runs one twice.+- A project's own line about the same job wins.++## Non-goals++- A per-project schedule editor, or parsing a project's instructions to find its times. Nothing parses the document+ (instructionsTemplate.ts); the PM reads it and judges what overlaps.+- Moving project-specific jobs (openharness's batch pull request, triage, releases, reports to Dee; Leo's status line)+ into the default.+- An on/off switch per project.++## Anti-goals++- A PM woken every 30 minutes with nothing to do. Every wake is a turn of a long-context session.+- Two messages in one poll where one would do.+- The default copied into a project's document by a PM that saves what it read.+- A job the Swarm already does on its own (below) repeated by the PM.++## What the Swarm already does, so the default leaves it out++| Job in River's schedule | Already done by the Swarm |+|---|---|+| A task whose agent is lost goes to a new agent | `work-lost` notice to the PM (liveness.ts), in the notice digest |+| A task with no progress for 30 minutes | `work-stalled` notice to the PM (liveness.ts sweepForLead) |+| Agents with no work are stopped | `idle` notice after 15 minutes, once per idle spell (tidy.ts idleNotices) |+| Finished groups whose pull requests are merged or closed are archived | Auto-archive (archive.ts), unless the owner turned tidying off |+| Morning digest, status card | `digest-request` at 08:00, `update-request` when work changes |++The default keeps the rules for answering these notices, since how to answer them is part of the job, but schedules no+job for them.++## The default++### The jobs++One job, every 30 minutes: **the open-task sweep.** Every open task of the project, unassigned and "To do" ones included,+ends the sweep with one of:++- an owner working on it;+- a question to a person, by name, with a default and a time;+- a close, with its reason.++A task waiting on a person gets that person asked by name, with a default and a time. A task nobody will work on is+closed. The PM asks no agent whether it is stalled: `mine` and the task's thread show it.++Then every finished group the Swarm left open is archived: one with no pull request linked, which the auto-archive+(tidy.ts reviewClosable, archive.ts) never takes (Ken, 2026-11-04).++The default also states the rules for the notices the Swarm sends, so every PM answers them the same way:++- `work-lost`: the task goes to a new agent with its pushed branch.+- `work-stalled`: the PM reads the task's thread first, and sends it back to its agent only when the thread shows it+ waits on nothing (a review, CI, a batch, a person).+- `idle`: the PM stops the agent unless work is coming for it.++No hourly cleanup job (Ken, 2026-11-04). On prod in the 24 hours to 2026-11-04 the Swarm archived 113 finished+groups itself and sent 121 idle notices; 15 finished groups were left unarchived, from 2026-10-27 to 11-04+(about 2 a day), each with no pull request linked to its group: the auto-archive waits for a linked pull request merged+or closed. They were archived by hand once; the sweep now archives new ones. The 30-minute sweep catches a task whose pull request merged but+which was never set done.++### Where the PM reads it++The instructions read (store.ts, the project instructions read) returns a new field, `builtIn`, beside `text`: the+default's text, from one constant in the backend (`pmSchedule.ts`). It is read-only, belongs to no revision, and only the+coordinator's read carries it (a Buddy's read and a worker's read omit it).++The CLI's instructions skill (cli/src/lib/swarmInstructionsSkill.ts instructionsSkillText) appends it after the document,+for the coordinator only, under its own heading:++```+## Built-in PM schedule (from the Swarm)++The Swarm wakes you for these jobs with a message that names them. Set no timer of your own for them, and delete one you+set before. A line in this project's instructions above about the same job wins: follow it, and skip that job when the+Swarm's message names it.+...the jobs and notice rules...+```++Because `builtIn` is part of what the skill holds, a change to the default rewrites the skill and tells the PM once, as a+new revision does today (refreshProjectSkills). The document's `text`, `hash` and `revision` are unchanged, so a PM that+saves what it read never copies the default into the document.++How a change reaches a running PM, and the launch:++- **The roster says when it changed.** The host rereads instructions only when the roster's `revision` or `hash` moves+ (cli/src/superTabs/host.ts refreshInstructions; backend/src/superTabs/read/hostRows.ts). The coordinator's row gains+ `builtInHash` (a hash of `builtIn`), and the host rereads when it moves too.+- **The host caches per role.** `instructionsKey` is shared by every agent of a tab and project, so a worker's read+ (no `builtIn`) could be reused for the coordinator. The key gains the coordinator's agent id, as it does a Buddy's.+- **The launch read prints it.** A new PM session is told to run `harness super-tab instructions`. For the coordinator+ that command prints `builtIn` after the document, under the same heading and a line saying it is not part of the+ document and is never saved. The launch record then counts the section as read for that `builtInHash`, so a launch+ owes no extra notice, and a later change of the default owes one.+- **The save refuses a copied section.** `instructions.save` refuses a text holding the heading line+ `## Built-in PM schedule (from the Swarm)`, saying to remove that section: the separate field keeps a read from+ copying it, and this keeps a PM that copied it from the skill file from storing it. Nothing is stripped silently.++### How the Swarm wakes the PM++The PM's own poll is the clock, as for the morning digest and the notice digest (store.ts fullDeliveries): no server+timer.++- **Slots.** A slot is a 30-minute window in UTC: slot `n` starts at `n * 30 min`. On the coordinator's poll, the+ schedule is due when the current slot is past the project's `schedule.lastSlot`. A PM offline for several slots gets+ one wake for the current slot, never one per missed slot.+- **The message.** One message to the coordinator, in the project's Lead conversation, `source.kind` `schedule-request`+ with `slot`. It names the time and each job due, and says it comes from the Swarm's built-in schedule:++ ```+ Built-in schedule, 10:00 (Asia/Ho_Chi_Minh). This is a scheduled request from the Swarm, not a new task.+ - Open-task sweep: every open task ends with an owner, a question to a person with a default and a time, or a close+ with its reason.+ Skip a job your project's instructions schedule on their own clock.+ ```++ Its id is `stableId('schedule', tabId, projectId, String(slot))`, so a retried poll writes it once. The time shown is+ in the project's digest time zone (digest.ts), Vietnam time when it has none.+- **One message per poll.** When the same poll writes an update request, the schedule's lines are appended to it, as the+ notice digest is today. When it writes a notice digest and no update request, the schedule's lines go into the+ digest's message. Only when nothing else is written does the schedule get a message of its own. The morning digest+ stays its own message: it asks the PM to post to people, a different act.+- **Nothing to do, no wake.** The sweep is for tasks no agent is moving; a task with an agent working on it is covered by+ the stalled and lost notices. So there is no message, and nothing is recorded, unless the project has an open task+ (a top-level task, not a step: a step belongs to its task's Engineer) that is unassigned or "To do", has lost its agent,+ or is waiting on a person, blocked or needing a human (liveness.ts task state), and no finished group quiet for+ ARCHIVE_QUIET_MS with no pull request linked. *Builder's call (Claude):* this keeps a+ busy project from 48 wakes a day while every task moves; a task parked on a person still wakes the sweep each slot,+ which is what makes the PM ask or close it. A slot with nothing to do writes nothing: `schedule` lives in the Swarm's+ head, and a write there moves every reader's copy each 30 minutes while nothing happened (#2946 review). The slot stays+ due, and each later poll checks again in memory over the loaded state; something to sweep later in the slot wakes the+ PM once. Readers' head leaves `schedule` out, as it leaves `progress`.+- **Only loaded groups.** The check sees the groups the poll loaded: a finished group with no pull request already asleep+ (sweeps.ts sleepQuietGroups, after a day of quiet) does not wake the PM. The PM's own sweep still finds it.+- **One unread wake at a time.** No new wake is written while the last `schedule-request` to the coordinator is still+ open (queued, claimed or uncertain), as the update request does (projectUpdates.ts). The slot is still recorded as+ handled, so a PM deep in a long turn finds one wake, not one per slot, when it comes back. A paused Swarm records nothing and sends nothing; its schedule is due again when+ it resumes, as the morning digest is.+- **Recorded in the same write.** `schedule.lastSlot` is set in the poll's single save, so two racing polls write the+ wake once: the second finds the slot handled, or the message id already stored.++### The project's own lines win++The Swarm does not know a project's times. The PM does: its document is above the default in the same skill, and the+wake message says to skip a job the project schedules itself. A project that wants a different sweep (lampos, say) writes+its own line; the PM then answers the Swarm's wake by skipping that job.++## Rollout++1. Backend and CLI ship together in one batch: the `builtIn` field, the wake, the skill section.+2. After the backend release, check on prod that River receives one `schedule-request` per slot, merged into an update+ request or a digest when one goes in the same poll.+3. Only then, with Ken's go, Claude saves openharness's instructions through the instructions API (the document lives on+ prod, not in the repo); this step is part of the plan. Save them without the three duplicate lines, so River is never without a sweep:+ - "Every 30 minutes, at :07 and :37" keeps only the batch pull request (Workflow 5); the progress sync goes.+ - "Every 30 minutes, at :22 and :52" keeps the worktree cleanup and the team pull request sweep; the open-task sweep+ goes.+ - "Every hour" (archive and stop) goes.+ The instructions-change notice makes River reread, and the skill's built-in section tells it to delete its own+ timers for those jobs.+4. Lampos keeps Leo's rules as they are; they win where they overlap.++## Design (docs/feature-design-rules.md)++- **Growth:** one number per project (`schedule.lastSlot`) in the Swarm's state. The messages are ordinary Lead-chat+ messages, at most 48 a day per active project and none for an idle one, kept and compacted as other notices are+ (deliveryCompaction.ts).+- **Concurrency:** the poll's existing Swarm transaction (fullDeliveries); the message's stable id makes a retry or a race+ write it once.+- **Read cost:** nothing new on a worker's poll. The coordinator's poll reads no more than today: the open-task and+ running-agent check uses the loaded state.+- **Scale:** 10x projects is 10x of a message every 30 minutes, written on polls that already run. The first metric to+ warn is the PM's turns per hour, logged with each wake (`[swarm-deliveries] schedule request`).+- **Compatibility:** an old CLI ignores `builtIn`; its PM still gets the wake, which carries the jobs and the "set no+ timer" line on its own. An old backend sends no `builtIn` and no wake; a new CLI writes no section then.+- **Migration and rollback:** none to migrate; a project with no `schedule` is due at its first poll. A rollback stops+ the wakes and the section; `schedule` is left unread. The openharness instructions change (rollout step 3) is a normal+ revision and can be reverted the same way.+- **Audience:** the server writes the wake to the coordinator alone: `schedule-request` gets a `recipients` entry in+ model.ts `NOTICE_READERS`, as `digest-request` has, or it would read as `people`. It serves `builtIn` only on the+ coordinator's read.+- **Identity:** the wake's author is the coordinator's own agent, as for the digest request; no machine owner's login.+- **Failure:** a poll that fails writes nothing and the slot stays due for the next poll. A PM that never polls (host+ down) gets no wake; the existing machine-offline notices tell people, and the first poll back wakes it once.+- **Platforms:** server and CLI only. People never see the wake: like the digest request it is the coordinator's alone,+ and Desktop, web and phone already hide rows whose readers are `recipients`.++## Tests++- The schedule is due once per slot; a second poll in the same slot writes nothing; a poll after three missed slots+ writes one wake.+- No wake and nothing written (the head's version unchanged) when nothing is due; none and nothing recorded for a paused+ Swarm. Readers' head carries no `schedule`.+- One message per poll: merged into an update request, or into a notice digest, when one goes in the same poll.+- Only the coordinator's instructions read carries `builtIn`; the skill appends it for the coordinator only, and a+ changed `builtIn` rewrites the skill and owes one notice.+- Saving instructions after a read leaves `builtIn` out of the stored text; a save holding the built-in heading is+ refused with its message.+- No wake for a project whose open tasks all have an agent working; a wake when one is unassigned or waiting on a person.+- No second wake while the first is open; the slot still moves.+- A changed `builtIn` moves the coordinator's roster `builtInHash`, and the host rereads; the coordinator's and a+ worker's reads are cached apart.+- The launch read prints the section for the coordinator, and the launch owes no extra notice.++## Left to the builder++- The exact wording of `builtIn` and of the wake, within what is above.+- Where the "nothing to do" check lives and its exact test of a running agent.+- File names beyond `pmSchedule.ts`.diff --git a/docs/plans/2026-11-04-pm-built-in-schedule-plan.md b/docs/plans/2026-11-04-pm-built-in-schedule-plan.mdnew file mode 100644index 000000000..1200aeb78--- /dev/null+++ b/docs/plans/2026-11-04-pm-built-in-schedule-plan.md@@ -0,0 +1,226 @@+# Built-in PM schedule Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Every project's coordinator is woken by the Swarm every 30 minutes for the open-task sweep when there is+something to sweep, and reads the built-in schedule after its project's instructions.++**Architecture:** A new backend module `pmSchedule.ts` holds the built-in text, the slot clock and the wake. The+coordinator's poll (`store.ts fullDeliveries`) writes the wake beside the update request and the notice digest, in one+message per poll. The instructions read and the host roster carry the built-in text and its hash to the coordinator+only, and the CLI appends it to the instructions skill and to the `instructions` command's output.++**Tech Stack:** TypeScript, Fastify, Prisma on MongoDB (backend), vitest; Node CLI daemon (cli/), vitest.++**Spec:** docs/plans/2026-11-04-pm-built-in-schedule-design.md++## Global Constraints++- Slot: 30 minutes in UTC; slot `n` starts at `n * 30 min` (`SCHEDULE_SLOT_MS = 30 * 60_000`).+- Wake message id: `stableId('schedule', tabId, projectId, String(slot))`; `source: { kind: 'schedule-request', projectId, slot }`.+- `schedule-request` readers: `'recipients'` in model.ts `NOTICE_READERS`.+- Built-in heading, exactly: `## Built-in PM schedule (from the Swarm)`.+- One message per poll: merged into the update request when one is written, else into the notice digest when one is+ written, else its own message. The morning digest stays separate.+- No wake while the last `schedule-request` to that coordinator is `queued`, `claimed` or `uncertain`; the slot is still+ recorded.+- No wake and nothing written when nothing is due (Task 1 `sweepDue`; #2946 review: the head stays unchanged); no wake and nothing recorded in a paused Swarm.+- No on/off switch. Log line: `[swarm-deliveries] schedule request`.+- No new collection, index or query: the check reads the loaded state; the open-wake check is one `findFirst` on+ `SuperTabDelivery` by `tabId, agentId, messageId, status`, the same shape as the update request's pending check.+- Commits stay local on branch `pm-built-in-schedule`; push and pull request only on Ken's go.++## Review Focus++1. A poll landing exactly on a slot's first millisecond: due once, never twice across two polls in that slot (Task 1 test).+2. A paused Swarm that resumes after three slots: one wake for the current slot, not three (Task 2 test).+3. The coordinator replaced mid-day: the new coordinator's first poll wakes it even though the former one holds an+ open wake (Task 2 test).+4. An update request already stored from an earlier poll: the wake is not merged into it (it would be kept without the+ lines, writeMessages keepStored), it goes into the digest or its own message (Task 2 test).+5. A worker's instructions read cached and then reused for the coordinator on the same host, or the other way round+ (Task 4 test).++---++### Task 1: The schedule module++**Files:**+- Create: `backend/src/superTabs/pmSchedule.ts`+- Modify: `backend/src/superTabs/projects.ts` (SwarmProject gains `schedule?: { lastSlot: number }`, with a comment naming pmSchedule.ts)+- Modify: `backend/src/superTabs/model.ts` (`NOTICE_READERS` gains `'schedule-request': 'recipients'` beside `'digest-request'`)+- Test: `backend/src/superTabs/pmSchedule.test.ts`++**Interfaces:**+- Produces:+ - `export const BUILT_IN_HEADING = '## Built-in PM schedule (from the Swarm)'`+ - `export const PM_SCHEDULE_TEXT: string`: the heading, then the paragraph from the spec ("The Swarm wakes you for these+ jobs with a message that names them. Set no timer of your own for them, and delete one you set before. A line in this+ project's instructions above about the same job wins: follow it, and skip that job when the Swarm's message names it.+ This section is not part of the project's document: never save it into the document."), then the open-task sweep+ (owner / question to a person by name with a default and a time / close with its reason; ask the waited-on person;+ ask no agent whether it is stalled; then archive every finished group the Swarm left open with no pull request+ linked), then the three notice rules (`work-lost`, `work-stalled`, `idle`) as in the spec.+ - `export const SCHEDULE_SLOT_MS = 30 * 60_000`+ - `export const scheduleSlot = (now: number): number` → `Math.floor(now / SCHEDULE_SLOT_MS)`+ - `export const scheduleMessageId = (tabId: string, projectId: string, slot: number): string`+ - `export function sweepDue(state: SuperTabState, projectId: string, now: number): boolean`: true when a loaded,+ unarchived, top-level task of the project (no `reviewOf`, no `kind`, not its Lead conversation, not `workOver`) has+ no assignment, or `taskLiveness` says `orphaned`, or `waiting` with `why` `person` or `blocked`; or when a loaded+ group of the project is `workOver`, unarchived, has no pull request (its own `pullRequestUrls`, or its task's for a+ step) and has been quiet for `ARCHIVE_QUIET_MS` (tidy.ts).+ - `export function scheduleText(project: SwarmProject, slot: number): string`: `Built-in schedule, HH:MM (ZONE). This is+ a scheduled request from the Swarm, not a new task.`, the open-task sweep line, and `Skip a job your project's+ instructions schedule on their own clock.` HH:MM is the slot's start in `digestOf(project)?.timeZone ??+ DEFAULT_TIME_ZONE` (digest.ts; export its `localNow` for this).+ - `export function scheduleRequest(state: SuperTabState, target: Agent, now: number): { slot: number; draft: MessageDraft | null } | null`:+ null when the Swarm is paused, `target` leads no project, or `scheduleSlot(now) <= project.schedule?.lastSlot`; else+ the slot, with a draft to the coordinator alone in the Lead conversation (author: the coordinator's own agent, as+ `digestRequest`) when `sweepDue`, or `draft: null` when nothing is due. It does not record the slot; the caller does.++- [ ] **Step 1: Write the failing tests** in `pmSchedule.test.ts`, on a fixture built like digest.test.ts's:+ - `due once per slot`: at `T = 20 * SCHEDULE_SLOT_MS` (a slot's first millisecond) with one unassigned task,+ `scheduleRequest(...)!.slot === 20` and `.draft!.id === scheduleMessageId('tab', 'p1', 20)`; with+ `project.schedule = { lastSlot: 20 }`, `scheduleRequest(state, lead, T + SCHEDULE_SLOT_MS - 1)` is null.+ - `nothing to sweep`: every task working with fresh progress → `{ slot: 20, draft: null }`.+ - `sweep wanted for`: one test per case → draft not null: an unassigned task; a `lost` assignment; `needs_human`;+ `blocked`; a done task with no pull request quiet `ARCHIVE_QUIET_MS`. Not for: a done task with a pull request; a+ done task quiet less than `ARCHIVE_QUIET_MS`; a step (`reviewOf`) with no assignment.+ - `paused`: `state.paused = true` → null.+ - `text`: `draft.text` starts `Built-in schedule, 10:00 (Asia/Ho_Chi_Minh).` for a slot starting 03:00 UTC, and+ `draft.source` equals `{ kind: 'schedule-request', projectId: 'p1', slot }`, `draft.recipients` equals `['lead']`.+ - `built-in text`: `PM_SCHEDULE_TEXT.startsWith(BUILT_IN_HEADING)` and it contains `Set no timer of your own` and+ `never save it into the document`.+- [ ] **Step 2: Run them to verify they fail**+ Run: `cd backend && npm test -- src/superTabs/pmSchedule.test.ts`+ Expected: FAIL, cannot resolve `./pmSchedule.js`.+- [ ] **Step 3: Implement** the Produces block above, and the `projects.ts` and `model.ts` lines.+- [ ] **Step 4: Run them to verify they pass**+ Run: `cd backend && npm test -- src/superTabs/pmSchedule.test.ts src/superTabs/digest.test.ts && npx tsc --noEmit -p .`+ Expected: PASS, tsc clean.+- [ ] **Step 5: Commit** `git add backend/src/superTabs/pmSchedule.ts backend/src/superTabs/pmSchedule.test.ts backend/src/superTabs/projects.ts backend/src/superTabs/model.ts backend/src/superTabs/digest.ts && git commit -m "Swarm: the built-in PM schedule's text, slot clock and wake"`++### Task 2: The coordinator's poll writes the wake++**Files:**+- Modify: `backend/src/superTabs/store.ts` (`fullDeliveries`, after the notice digest block, before the morning digest)+- Modify: `backend/integration/noDefaultDigest.test-support.ts` (the schedule is off unless a test calls `wantSchedule()`)+- Create: `backend/integration/superTabPmSchedule.test.ts`+- Modify: `backend/vitest.super-tabs.config.ts` and `backend/vitest.super-tabs.ci.config.ts` (add the new file wherever+ `integration/superTabNoticeDigest.test.ts` is listed)++**Interfaces:**+- Consumes: Task 1's `scheduleRequest`, `scheduleText`, `scheduleMessageId`.+- Produces: `export const wantSchedule = (): void` in noDefaultDigest.test-support.ts, mocking `pmSchedule.js`'s+ `scheduleRequest` to return null unless called, reset `beforeEach`, as `wantDefaultDigest` does for the digest.++In `fullDeliveries`: call `scheduleRequest(state, target, this.now())` when `led`. When it returns a slot, set+`project.schedule = { lastSlot: slot }` on the cloned state (saved by the poll's single `this.save`). When it has a draft,+read the last wake's open delivery: `tx.superTabDelivery.findFirst({ where: { tabId, agentId, messageId:+scheduleMessageId(tabId, project.id, previousLastSlot), status: { in: ['queued', 'claimed', 'uncertain'] } } })`, skipped+when there was no previous slot. With none open: append `\n\n` + the draft's text to the update request when this poll+pushed one and it is not already stored (the existing `merged` check), else to the notice digest message this poll+pushed, else push the draft. Merged rows keep their `source` and gain `schedule: slot`. Log `[swarm-deliveries]+schedule request` with `{ tabId, slot, placed: 'update' | 'digest' | 'own' | 'skipped-open' }` after commit (none when nothing is due).++- [ ] **Step 1: Write the failing integration tests** in `superTabPmSchedule.test.ts`, with the swarm setup copied from+ superTabNoticeDigest.test.ts and `wantSchedule()` in each test:+ - `wakes once per slot`: an unassigned task; the coordinator's poll returns one delivery whose message has+ `source.kind === 'schedule-request'`; a second poll in the same slot returns none new.+ - `no wake when nothing is due`: the only task is working with fresh progress → no `schedule-request` message, and+ the project's `schedule.lastSlot` is the current slot.+ - `one unread wake at a time`: leave the first wake unclaimed, move the clock one slot, poll → no second+ `schedule-request`; `lastSlot` moved.+ - `merged into the update request`: a change that makes this poll write an update request → one message, its text+ containing `Built-in schedule,`, no separate `schedule-request` message.+ - `merged into the notice digest`: a gathered notice due in the same poll, no update request → the digest's message+ text contains `Built-in schedule,`.+ - `paused then resumed`: pause, advance three slots, poll → no wake; resume, poll → exactly one wake.+ - `new coordinator`: the wake to coordinator A is open; switch the project's lead to agent B; B's poll → one wake to B.+ - `stored update request`: an update request already written by an earlier poll and re-pushed by this poll → the wake+ is not in it.+- [ ] **Step 2: Run to verify they fail**+ Run: `cd backend && npx vitest run --config vitest.super-tabs.config.ts integration/superTabPmSchedule.test.ts`+ Expected: FAIL, no `schedule-request` message (and `wantSchedule` not exported).+- [ ] **Step 3: Implement** the store change and `wantSchedule()`.+- [ ] **Step 4: Run to verify they pass, with the suites that count coordinator messages**+ Run: `cd backend && npx vitest run --config vitest.super-tabs.config.ts integration/superTabPmSchedule.test.ts integration/superTabNoticeDigest.test.ts integration/superTabDigestHour.test.ts integration/superTabLiveness.test.ts integration/superTabs.test.ts`+ Expected: PASS.+- [ ] **Step 5: Commit** `git commit -am "Swarm: the coordinator's poll wakes it for the built-in schedule, in one message per poll"` (add the new test file first).++### Task 3: The coordinator's instructions read, roster and save guard++**Files:**+- Modify: `backend/src/superTabs/store.ts` `instructions()` (≈ line 2302): add `builtIn: PM_SCHEDULE_TEXT` to the answer+ when the actor is an agent and `ledProject(state, actor.agentId)?.id === projectId`; absent otherwise.+- Modify: `backend/src/superTabs/read/hostRows.ts` (the `instructions` row ≈ line 87): add+ `builtInHash: ledProject(state, target.id)?.id === home.id ? instructionsHash(PM_SCHEDULE_TEXT) : null`.+- Modify: `backend/src/superTabs/commands.ts` `case 'instructions.save'` (≈ line 1706): before the revision check,+ `fail('INSTRUCTIONS_BUILT_IN', 'Remove the "Built-in PM schedule" section: the Swarm adds it to every read, so it is never saved in the document.', 400)`+ when a line of `command.text` equals `BUILT_IN_HEADING` (trimmed).+- Test: `backend/integration/superTabInstructions.test.ts`++- [ ] **Step 1: Write the failing tests** in superTabInstructions.test.ts:+ - `the coordinator's read carries the built-in schedule`: read as the coordinator → `builtIn === PM_SCHEDULE_TEXT`;+ as a worker, and as a person → `builtIn` undefined; `text` and `hash` equal those of a read before this change.+ - `the roster names the built-in hash for the coordinator only`: the coordinator's host row has+ `instructions.builtInHash === instructionsHash(PM_SCHEDULE_TEXT)`; a worker's row has `null` (read the rows as the+ file already does, or through `poolRows` from hostRows.test-support.ts).+ - `a save holding the built-in section is refused`: `instructions.save` with `text` = the document ++ `\n\n${PM_SCHEDULE_TEXT}` fails with code `INSTRUCTIONS_BUILT_IN`, and the revision does not move; a save after an+ ordinary read (its `text`) succeeds.+- [ ] **Step 2: Run to verify they fail**+ Run: `cd backend && npx vitest run --config vitest.super-tabs.config.ts integration/superTabInstructions.test.ts`+ Expected: FAIL on `builtIn` undefined.+- [ ] **Step 3: Implement** the three changes.+- [ ] **Step 4: Run to verify they pass**+ Run: `cd backend && npx vitest run --config vitest.super-tabs.config.ts integration/superTabInstructions.test.ts integration/superTabHostGroups.test.ts && npm test -- src/superTabs && npx tsc --noEmit -p .`+ Expected: PASS, tsc clean.+- [ ] **Step 5: Commit** `git commit -am "Swarm: the coordinator reads the built-in PM schedule beside its instructions, and no save stores it"`++### Task 4: The CLI appends the built-in schedule for the coordinator++**Files:**+- Modify: `cli/src/superTabs/host.ts`: `RowInstructions` gains `builtInHash?: string | null`; `instructionsKey` gains the+ agent id when `target.lead === true` (as for a Buddy); `refreshInstructions` rereads when `held.builtInHash !==+ (doc.builtInHash ?? null)` too, keeps `builtIn` (`typeof answer.builtIn === 'string' ? answer.builtIn : null`) in+ `held`, and passes it to `refreshProjectSkills`.+- Modify: `cli/src/lib/swarmInstructionsSkill.ts`: `ProjectDoc` gains `builtIn?: string | null`; `instructionsSkillText`+ appends `\n\n${doc.builtIn}` after the document when `doc.coordinator && doc.builtIn`.+- Modify: `cli/src/superTabs/command.ts` (`action === 'instructions'`, ≈ line 401): print `value.builtIn` after+ `value.text` and before the notes when it is a non-empty string.+- Test: `cli/src/lib/swarmInstructionsSkill.spec.ts`, `cli/src/superTabs/host.spec.ts`, `cli/src/superTabs/routeCommand.spec.ts`++- [ ] **Step 1: Write the failing tests**+ - swarmInstructionsSkill.spec.ts `appends the built-in schedule for the coordinator only`: with `builtIn: '## Built-in+ PM schedule (from the Swarm)\n\nX'`, the coordinator's text ends with it after the document; a worker's text does+ not contain it.+ - swarmInstructionsSkill.spec.ts `a changed built-in schedule owes one notice`: install, record the notice, refresh+ with a different `builtIn` → `owed === true`; refresh again unchanged → `owed === false` after the notice is recorded.+ - swarmInstructionsSkill.spec.ts `a launch that printed it owes nothing extra`: first install after a launch record,+ revision saved before the launch, with `builtIn` → `owed === false`.+ - host.spec.ts `rereads when the built-in hash moves`: roster with `builtInHash: 'a'`, then `'b'` at the same revision+ and hash → two instructions reads.+ - host.spec.ts `caches the coordinator's read apart from a worker's`: a worker and the coordinator of one project on+ one host → two reads, and only the coordinator's skill file contains the heading.+ - routeCommand.spec.ts `prints the built-in schedule after the document`: answer with `builtIn: 'B'` → output has+ `Work by this.` then `B` then the notes.+- [ ] **Step 2: Run to verify they fail**+ Run: `cd cli && npx vitest run src/lib/swarmInstructionsSkill.spec.ts src/superTabs/host.spec.ts src/superTabs/routeCommand.spec.ts`+ Expected: FAIL on the new tests only.+- [ ] **Step 3: Implement** the three changes.+- [ ] **Step 4: Run to verify they pass**+ Run: `cd cli && npx vitest run src/lib/swarmInstructionsSkill.spec.ts src/superTabs/host.spec.ts src/superTabs/routeCommand.spec.ts src/superTabs/serviceReads.spec.ts && npm run typecheck`+ Expected: PASS, typecheck clean. Then `npm run test:harnessd` (a CLI coverage gate PR CI does not run).+- [ ] **Step 5: Commit** `git commit -am "CLI: the coordinator's instructions skill and command append the built-in PM schedule"`++### Task 5: After the release (no code)++- [ ] Ken's go for the backend and CLI release, in the 09:00–16:00 window, in River's batch.+- [ ] On prod read-only: River's Lead conversation has `schedule-request` messages, at most one per slot, merged where+ an update request or digest went in the same poll; idle projects log no `[swarm-deliveries] schedule request` line.+- [ ] With Ken's go, save the six projects' instructions and read each back. In physical-router, lampos, garage-pod,+ computer and spaceship the whole `## PM schedule` section added on 2026-11-04 goes: the built-in section carries all+ of it. In openharness the progress sync goes from the :07/:37 line (the batch pull request stays), the open-task sweep+ and its archive sentence go from the :22/:52 line (the worktree cleanup and the team pull request sweep stay), and the+ "Every hour" line goes.diff --git a/docs/plans/2026-11-04-task-line-ended-outside-commands-plan.md b/docs/plans/2026-11-04-task-line-ended-outside-commands-plan.mdnew file mode 100644index 000000000..a3856e2e3--- /dev/null+++ b/docs/plans/2026-11-04-task-line-ended-outside-commands-plan.md@@ -0,0 +1,55 @@+# A task ended outside any command says so in its thread Implementation Plan++> **For agentic workers:** Follow the project Engineer workflow: plan first in a draft PR; implement task by task with a committed failing test before its passing code; one independent review step on the pull request.++**Goal:** A task lost to the liveness sweep, a machine's report or its Lead's poll, or stopped by its host's stop receipt, posts its one `Stuck` or `Not building this` reply in its project-chat thread, as a task that moves in a command does. Today these thread replies are the only task state the chat shows (#2704), so the thread kept saying `On it: Kai is building it` for hours, then jumped to the next builder. Fix to what ships (Diego, 2026-11-04, task #2693).++**Architecture:** `syncTaskLines` (taskLine.ts) compares the state before and after each command, so a status set outside any command is never seen: by `loseTask` (liveness.ts), called from the machine report and the 30 s sweep (store.ts `fullReading`) and the Lead's poll (store.ts `fullDeliveries`, `sweepForLead`), and by `store.stopped()`. A new `endedReply(state, group, id, fallback)` in taskLine.ts writes the reply where the status is set: same thread, author (the project's coordinator) and `system` source as the command path's replies, words shared with `progress()`. `loseTask` returns it with its two work-lost rows; `stopped()` writes it with its Stopped notice. The `lost` case leaves `progress()`, so `agent.alert`, the one command that loses a task, posts once. Each store path loads the task's project chat when its load left it out (`taskLineChats`), so the reply has somewhere to go.++**Tech Stack:** TypeScript, Vitest (backend unit tests); the Super Tab integration suite (Mongo memory replica set) for `stopped()`.++**Spec:** Swarm task #2693 (Diego; Buddy's proposal with the evidence on main 6368bf6b0).++## Global Constraints++- One reply per loss or stop, never two: a stable id from the assignment and the loss (a resumed task can be lost again), or the assignment for a stop.+- Replies wake nobody (`recipients: []`), as every task-line reply.+- A task with no line (a step, a private chat, the project chat) gets none. A task whose project chat no longer exists gets none.+- Swarm code stays out of cli/src/core. PR body begins `Requested by [email protected] through Harness.`++## Design++- Growth: one message per lost or stopped attempt, in the chat that already holds the task's line; deleted with that chat's messages.+- Concurrency: inside the transactions that already set the status (the report, the Lead's poll, the stop receipt).+- Read cost: no new read when the project chat is loaded, which it is on every path today (loadObserved and a full load read every project chat). Otherwise one read by key for the missing chats.+- Scale: one row per loss; 10x tasks lost is 10x rows, the same as the work-lost rows beside them.+- Compatibility: an ordinary thread reply with the existing `system` source; old and new apps read it already.+- Migration + rollback: none. Rolling back stops new replies; written ones stay.+- Audience: the project chat's own readers, as for every task-line reply (a private project's chat is read only by its readers).+- Identity: written as the project's coordinator, else the task's worker for a loss or the stopped worker, never the machine owner.+- Failure: a missing chat writes nothing, and the task's own conversation still holds its work-lost rows or Stopped notice.+- Platforms: backend only.++## Review Focus++- `agent.alert` posts exactly one Stuck reply (the `lost` case is gone from `progress()`, and `loseTask` posts it).+- The reply's id is stable, so a retried report or poll transaction writes it once.+- Every path that sets `lost` or `stopped` outside a command has its project chat loaded before it writes.++---++### Task 1: A loss says Stuck in its thread++**Files:** `backend/src/superTabs/taskLine.ts`, `backend/src/superTabs/liveness.ts`, `backend/src/superTabs/store.ts` (`fullReading`, `fullDeliveries`), `backend/src/superTabs/liveness.test.ts`++**Interfaces:** `endedReply(state: SuperTabState, group: Conversation, id: string, fallback?: Author): MessageDraft[]`; `taskLineChats(state: SuperTabState): string[]`.++- [x] Failing tests (stepsFixture): a task lost by `sweepLiveness` after 120 quiet minutes has exactly one row in the project chat, in `cards.line.messageId`'s thread, `Stuck: <worker> stopped. Next: another engineer takes it over.`; the same through `sweepForLead`; `agent.alert` still posts exactly one. Commit; watch them fail.+- [x] Implement `endedReply`; return it from `loseTask`; drop `lost` from `progress()`; load missing line chats in `fullReading` and `fullDeliveries`. Commit; watch them pass.++### Task 2: A host's stop says Not building this in its thread++**Files:** `backend/src/superTabs/store.ts` (`stopped`), `backend/integration/superTabTaskLines.test.ts`++- [x] Failing test: a stop receipt for an assigned task posts one `Not building this: The execution host confirmed that this harness stopped.` reply in the task's thread, and a repeated receipt adds none. Commit; watch it fail.+- [x] Write `endedReply` in `stopped()` with its Stopped notice; load a missing line chat. Commit; watch it pass. Then the full backend unit suite.diff --git a/docs/swarm-github-app.md b/docs/swarm-github-app.mdindex 02deda042..0a7c4aee2 100644--- a/docs/swarm-github-app.md+++ b/docs/swarm-github-app.md@@ -25,7 +25,7 @@ On GitHub, open the organization, then **Settings → Developer settings → Git| Homepage URL | `https://harness.autonomous.ai` || Callback URL, Setup URL | Leave empty. || Webhook → Active | Clear it. Harness subscribes to no events. |-| Repository permissions | **Contents:** Read and write. **Pull requests:** Read and write. **Checks:** Read-only. **Actions:** Read-only. **Metadata:** Read-only (GitHub sets this one). Leave every other permission at *No access*. |+| Repository permissions | **Contents:** Read and write. **Pull requests:** Read and write. **Checks:** Read-only. **Actions:** Read-only. **Metadata:** Read-only (GitHub sets this one). **Workflows:** Read and write, and **Issues:** Read and write, if agents should push changes to `.github/workflows` and write issues (see [Workflows and issues](#workflows-and-issues)). Leave every other permission at *No access*. || Organization and account permissions | No access. || Where can this GitHub App be installed? | **Only on this account** |@@ -43,7 +43,9 @@ register with [GitHub's manifest flow](https://docs.github.com/apps/sharing-gith"pull_requests": "write","checks": "read","actions": "read",- "metadata": "read"+ "metadata": "read",+ "workflows": "write",+ "issues": "write"},"default_events": []}@@ -67,6 +69,32 @@ organization's **Settings → GitHub Apps → Configure**.If a project uses a repository the app is not installed on, its agents cannot push.They receive the install link to pass on to an organization owner.+### Workflows and issues++An agent's token also asks for **Workflows** and **Issues** where the repository's+installation has granted them, at no more than the granted level. Without+Workflows, GitHub refuses a push that changes `.github/workflows`, and on a large+repository it can refuse a push it could not finish checking for workflow changes in+time. Harness reads what each installation has granted and asks only for that, so an+installation that has not granted them keeps getting today's tokens. A grant is+remembered ten minutes, and read again at once when GitHub refuses a token for its+permissions.++To grant them on an app already installed:++1. On the app's settings page (**Settings → Developer settings → GitHub Apps →+ the app → Permissions & events**), set **Workflows** and **Issues** to **Read and+ write** and click **Save changes**.+2. An owner of each organization the app is installed on opens **Settings → GitHub+ Apps → Configure** for the app, reviews the request and clicks **Accept new+ permissions**. Until then, that installation's tokens leave the new permissions out.++Every agent that gets its token from the app, for a repository whose installation+granted these, gets them, Harness Team account agents included. A workflow change+runs in CI with the repository's secrets, so a branch an agent pushes can run code+with them; the default branch's pull request rule (below) still keeps such a change+from reaching the default branch unreviewed.+### 3. Require pull requests on the default branchA token that can write contents can push straight to any branch that nothing