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-02 1400: #2499 #2514 #2533 #2524 (#2536)
0xken15e984cfea26ab
diff --git a/backend/integration/superTabFollowedThreads.test.ts b/backend/integration/superTabFollowedThreads.test.tsindex 0db70a05f..74589221b 100644--- a/backend/integration/superTabFollowedThreads.test.ts+++ b/backend/integration/superTabFollowedThreads.test.ts@@ -19,7 +19,7 @@ import { SwarmReads } from '../src/superTabs/read/service.js'import { HostReads } from '../src/superTabs/read/host.js'import { buddyChatId } from '../src/superTabs/buddies.js'import { resetInboxReads } from '../src/superTabs/read/inbox.js'-import { MAX_READ_THREADS, resetThreadsReads, THREADS_READS, THREADS_WINDOW_MS } from '../src/superTabs/read/followedThreads.js'+import { MAX_READ_THREADS, resetThreadsReads, TAGGED_THREADS, THREADS_READS, THREADS_WINDOW_MS } from '../src/superTabs/read/followedThreads.js'import type { Author, Conversation, SuperTabState } from '../src/superTabs/model.js'import { THREAD_MARK_CAP, writeThreadFollow, writeThreadMark } from '../src/superTabs/readMarks.js'import { writeLegacySwarm } from '../scripts/swarm-parts/legacy.js'@@ -486,3 +486,138 @@ describe('a person\'s followed threads (GET /threads)', () => {expect(reply.body.data.read.every((t: any) => t.replies <= 100)).toBe(true)}, 120_000)})++describe('a thread the person is tagged in, in a chat they never opened (GET /threads)', () => {+ /** The tag row the store writes for a tagged message (mentions.ts writeMentions); `insert` stores messages only. */+ const tag = (tabId: string, conversationId: string, messageId: string, as: AuthUser = peer, options: { at?: number; resolved?: boolean; projectId?: string } = {}) =>+ db.superTabMention.create({ data: { id: `${tabId}-${messageId}-${as.sub}`, tabId, personId: as.sub, projectId: options.projectId ?? 'lead', conversationId, messageId,+ authorAgentId: owner.sub, createdAt: new Date(options.at ?? Date.now()), resolvedAt: options.resolved ? new Date() : null } })+ /** Owner's root with owner's reply tagging peer: peer never marked the chat read. */+ async function tagged(tabId: string, conversationId: string, label: string, worker: string) {+ const [root] = await insert(tabId, conversationId, [{ text: `${label} root`, author: personAuthor(owner) }])+ const [reply] = await insert(tabId, conversationId, [{ text: `${label} reply`, author: agentAuthor(worker), thread: root!, mentions: [peer.sub] }])+ await tag(tabId, conversationId, reply!)+ return { root: root!, reply: reply! }+ }++ it('lists it as a read thread, though the inbox counts the chat as read and lists none of its threads', async () => {+ const s = await scene()+ const t = await tagged(s.tabId, s.web, 'Tagged', s.worker)+ expect((await inbox(s.tabId, peer)).body.data.threads).toEqual([])+ const { status, body } = await threads(s.tabId, peer)+ expect(status).toBe(200)+ expect(body.data.unread).toEqual([])+ expect(roots(body.data.read)).toEqual(['Tagged root'])+ expect(body.data.read[0]).toMatchObject({ conversationId: s.web, rootId: t.root, replies: 1, follow: null })+ expect(body.data.more).toBe(false)+ // The tag is the person's own: nobody else is shown the thread for it.+ expect((await threads(s.tabId, outsider)).body.data).toEqual({ unread: [], read: [], more: false })+ })++ it('lists a thread whose root is the tagged message, and one whose tag is answered, once each', async () => {+ const s = await scene()+ const [rootTagged, answered] = await insert(s.tabId, s.web, [{ text: 'Tagged at the root', author: personAuthor(owner), mentions: [peer.sub] },+ { text: 'Answered root', author: personAuthor(owner) }])+ const [, answeredReply] = await insert(s.tabId, s.web, [{ text: 'Reply', author: agentAuthor(s.worker), thread: rootTagged! }, { text: 'Tagged reply', author: agentAuthor(s.worker), thread: answered!, mentions: [peer.sub] }])+ await tag(s.tabId, s.web, rootTagged!)+ await tag(s.tabId, s.web, answeredReply!, peer, { resolved: true })+ await tag(s.tabId, s.web, answeredReply!, owner)+ const { body } = await threads(s.tabId, peer)+ expect(roots(body.data.read).sort()).toEqual(['Answered root', 'Tagged at the root'])+ })++ it('never lists a thread whose tag names a chat they cannot read, another chat\'s message, a hidden root, an archived chat or an expired tag, naming nothing', async () => {+ const s = await scene()+ // A private project's thread: peer's tag row exists, as no route would write one.+ const secret = await tagged(s.tabId, s.secretGroup, 'Secret', s.worker)+ // A tag row for peer that names the open chat but another chat's message.+ const [forgedRoot] = await insert(s.tabId, s.secretGroup, [{ text: 'Forged root', author: personAuthor(owner) }])+ const [forgedReply] = await insert(s.tabId, s.secretGroup, [{ text: 'Forged reply', author: agentAuthor(s.worker), thread: forgedRoot!, mentions: [peer.sub] }])+ await tag(s.tabId, s.web, forgedReply!)+ // A thread whose root only agents read.+ const [hiddenRoot] = await insert(s.tabId, s.web, [{ text: 'Hidden root', author: agentAuthor('hidden-agent'), source: { kind: 'note', recipientsOnly: true }, recipientIds: [s.worker] }])+ const [hiddenReply] = await insert(s.tabId, s.web, [{ text: 'Reply under a hidden root', author: agentAuthor(s.worker), thread: hiddenRoot!, mentions: [peer.sub] }])+ await tag(s.tabId, s.web, hiddenReply!)+ // An expired tag (30 days), and an archived chat's.+ const old = await tagged(s.tabId, s.openChat, 'Expired', s.worker)+ await db.superTabMention.updateMany({ where: { tabId: s.tabId, messageId: old.reply }, data: { createdAt: new Date(Date.now() - 31 * 24 * 60 * 60_000) } })+ const archived = await tagged(s.tabId, s.web, 'Archived', s.worker)+ expect(roots((await threads(s.tabId, peer)).body.data.read)).toEqual(['Archived root'])+ await editChat(s.tabId, s.web, data => { data.archived = true })+ expect((await threads(s.tabId, peer)).body.data).toEqual({ unread: [], read: [], more: false })+ expect(JSON.stringify((await threads(s.tabId, peer)).body)).not.toMatch(/Secret|Forged|Hidden|hidden-agent|Expired|Archived/)+ expect([secret.root, archived.root, old.root]).toHaveLength(3)+ })++ it('leaves out a thread they unfollowed, and a Buddy chat of another person', async () => {+ const s = await scene()+ const t = await tagged(s.tabId, s.web, 'Unfollowed', s.worker)+ await follow(s.tabId, s.web, t.root, false, peer)+ const other = await tagged(s.tabId, s.web, 'Kept', s.worker)+ // Peer\'s Buddy chat is theirs alone: a tag of the owner there names nothing for the owner.+ const [buddyRoot] = await insert(s.tabId, s.buddyId, [{ text: 'Buddy root', author: personAuthor(peer) }])+ const [buddyReply] = await insert(s.tabId, s.buddyId, [{ text: 'Buddy reply', author: personAuthor(peer), thread: buddyRoot!, mentions: [owner.sub] }])+ await tag(s.tabId, s.buddyId, buddyReply!, owner)+ expect(roots((await threads(s.tabId, peer)).body.data.read)).toEqual(['Kept root'])+ const ownerRead = (await threads(s.tabId, owner)).body.data+ expect(JSON.stringify(ownerRead)).not.toMatch(/Buddy/)+ expect(other.root).toBeTruthy()+ })++ it('stops listing it once they lose the chat, and again lists it when they read it', async () => {+ const s = await scene()+ await tagged(s.tabId, s.web, 'Revoked', s.worker)+ expect(roots((await threads(s.tabId, peer)).body.data.read)).toEqual(['Revoked root'])+ await editChat(s.tabId, s.web, data => { data.audience = { people: [{ id: owner.sub, generation: 0 }] } })+ expect((await threads(s.tabId, peer)).body.data).toEqual({ unread: [], read: [], more: false })+ await editChat(s.tabId, s.web, data => { delete data.audience })+ expect(roots((await threads(s.tabId, peer)).body.data.read)).toEqual(['Revoked root'])+ await store.execute(owner, s.tabId, { operationId: randomUUID(), command: { type: 'member.remove', userId: peer.sub } })+ const left = await threads(s.tabId, peer)+ expect(left.status).toBe(404)+ expect(JSON.stringify(left.body)).not.toMatch(/Revoked|Web/)+ })++ it(`checks at most ${TAGGED_THREADS} tagged threads, newest tag first, and says there are more`, async () => {+ const s = await scene()+ const many = await insert(s.tabId, s.web, Array.from({ length: TAGGED_THREADS + 5 }, (_, i) => ({ text: `Root ${i}`, author: personAuthor(owner) })))+ const replies = await insert(s.tabId, s.web, many.map(thread => ({ text: 'Reply', author: agentAuthor(s.worker), thread, mentions: [peer.sub] })))+ for (const [i, reply] of replies.entries()) await tag(s.tabId, s.web, reply, peer, { at: Date.now() - (replies.length - i) * 1000 })+ const { body } = await threads(s.tabId, peer)+ expect(body.data.read).toHaveLength(TAGGED_THREADS)+ expect(body.data.more).toBe(true)+ // The newest tags: the last roots.+ expect(roots(body.data.read)).toContain(`Root ${TAGGED_THREADS + 4}`)+ expect(roots(body.data.read)).not.toContain('Root 0')+ })++ /** An older tag in `older`, and TAGGED_THREADS + 1 newer ones in `chat` (the caller then hides them from the list). */+ async function olderBehindNewer(tabId: string, older: string, chat: string, worker: string) {+ const old = await tagged(tabId, older, 'Older', worker)+ await db.superTabMention.updateMany({ where: { tabId, messageId: old.reply }, data: { createdAt: new Date(Date.now() - 3_600_000) } })+ const roots = await insert(tabId, chat, Array.from({ length: TAGGED_THREADS + 1 }, (_, i) => ({ text: `Newer ${i}`, author: personAuthor(owner) })))+ const replies = await insert(tabId, chat, roots.map(thread => ({ text: 'Reply', author: agentAuthor(worker), thread, mentions: [peer.sub] })))+ for (const reply of replies) await tag(tabId, chat, reply)+ return roots+ }++ it('does not let newer tags in an archived chat use up the cap and hide an older tag in an open chat', async () => {+ const s = await scene()+ await olderBehindNewer(s.tabId, s.web, s.openChat, s.worker)+ await editChat(s.tabId, s.openChat, data => { data.archived = true })+ const { body } = await threads(s.tabId, peer)+ expect(roots(body.data.read)).toEqual(['Older root'])+ expect(body.data.more).toBe(false)+ expect(JSON.stringify(body.data)).not.toMatch(/Newer/)+ })++ it('does not let newer tags in threads they unfollowed use up the cap and hide an older tag', async () => {+ const s = await scene()+ const newer = await olderBehindNewer(s.tabId, s.web, s.web, s.worker)+ for (const root of newer) expect((await follow(s.tabId, s.web, root, false, peer)).status).toBe(200)+ const { body } = await threads(s.tabId, peer)+ expect(roots(body.data.read)).toEqual(['Older root'])+ expect(body.data.more).toBe(false)+ expect(JSON.stringify(body.data)).not.toMatch(/Newer/)+ })+})diff --git a/backend/integration/superTabLeaderboard.test.ts b/backend/integration/superTabLeaderboard.test.tsindex e5a775470..a216c9a82 100644--- a/backend/integration/superTabLeaderboard.test.ts+++ b/backend/integration/superTabLeaderboard.test.ts@@ -56,7 +56,7 @@ afterAll(async () => {/** A Swarm in parts: peer's request shipped this week, peer's request shipped last week and gone dormant, a private chat* that carries a ship record, a private project with its own shipped request, and the owner's work waiting on them. */-async function scene() {+async function scene(before?: (state: SuperTabState) => void) {const s = swarm(NOW)s.join(peerActor)s.join(outsiderActor)@@ -82,6 +82,7 @@ async function scene() {})const tabId = `tab-${randomUUID()}`const state = { ...structuredClone(s.state), id: tabId } as SuperTabState+ before?.(state)await writeLegacySwarm(db, { state, revision: 50 })const report = await migrateSwarm(db, tabId, { now: () => NOW - 60_000 })if (!report.ok) throw new Error(report.error)@@ -154,6 +155,139 @@ describe('the leaderboard read', () => {expect(score(last.body, peer.sub).details.shipped).toEqual([{ title: 'Old', prUrl: PR, mergedAt: WEEK - 2 * 86_400_000 }])})+ describe('a rolling period', () => {+ it('sums a shipped request by its exact time and says which period', async () => {+ const s = await scene()+ const seven = await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=lead&period=7d`, peer)+ expect(seven.status).toBe(200)+ expect(seven.body.data.period).toEqual({ name: '7d', start: NOW + 1 - WEEK_MS, end: NOW })+ // The dormant group shipped 2 days before this week began: inside the 7 days up to now, whichever week that was.+ expect(score(seven.body, peer.sub)).toMatchObject({ shipped: { count: 2 }, prevWeekPoints: 0 })+ const thirty = await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=lead&period=30d`, peer)+ expect(score(thirty.body, peer.sub)).toMatchObject({ shipped: { count: 2 }, prevWeekPoints: null })+ expect(thirty.body.data.goal.lastWeek).toBeNull()+ expect(JSON.stringify(thirty.body.data)).not.toMatch(/Peer and PM|Hidden/)+ const day = await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=lead&period=24h`, peer)+ expect(score(day.body, peer.sub).shipped.count).toBe(1)+ })++ it('reads Lent and verdicts stored in parts: an older week once, days and hours beside it, and no other read carries the days', async () => {+ const s = await scene(state => {+ const day = Math.floor(NOW / 86_400_000) * 86_400_000+ state.machines = [{ machineId: 'peer-mac', name: 'Peer Mac', contributorId: peer.sub, membershipGeneration: state.people.find(p => p.id === peer.sub)!.generation, generation: 'g1',+ cwd: '/repo', engines: ['claude'], maxAgents: 2, paused: false, lent: [{ week: WEEK - WEEK_MS, busyMs: 20 * HOUR }], lentDays: [{ day, projectId: 'lead', busyMs: 10 * HOUR }] }]+ state.conversations.find(c => c.title === 'Fresh')!.ledger!.reviewHours = [{ hour: NOW - HOUR, engine: 'claude', model: 'opus', effort: 'high', count: 2 }]+ state.conversations.find(c => c.title === 'Fresh')!.ledger!.reviews = [{ week: WEEK - WEEK_MS, engine: 'claude', model: 'opus', effort: 'high', count: 3 }]+ })+ const url = `/api/super-tabs/${s.tabId}/leaderboard?projectId=lead&period=30d`+ const first = await get(url, peer)+ expect(score(first.body, peer.sub).lent).toEqual({ machines: 1, agentMs: 30 * HOUR })+ expect(first.body.data.byModel.find((m: { model: string }) => m.model === 'opus')).toMatchObject({ reviews: 5 })+ expect((await get(url, peer)).body.data).toEqual(first.body.data)+ // A week's read is as it was.+ const week = await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=lead&week=${WEEK - WEEK_MS}`, peer)+ expect(score(week.body, peer.sub).lent.agentMs).toBe(20 * HOUR)+ const parts = await get(`/api/super-tabs/${s.tabId}/parts`, peer)+ expect(JSON.stringify(parts.body.data)).not.toMatch(/lentDays|reviewHours/)+ })++ it('All projects sums what the reader may read: a private project counts for its reader, and nothing of it reaches anyone else', async () => {+ const s = await scene()+ const url = `/api/super-tabs/${s.tabId}/leaderboard?projectId=lead&period=30d`+ // Peer's own request in the private project they cannot read.+ const asOwner = await get(`${url}&scope=all`, owner), asOutsider = await get(`${url}&scope=all`, outsider)+ expect(asOwner.body.data.allProjects).toBe(true)+ expect(score(asOwner.body, peer.sub).shipped.count).toBe(3)+ expect(score(asOutsider.body, peer.sub).shipped.count).toBe(2)+ expect(JSON.stringify(asOutsider.body.data)).not.toMatch(/Hidden|Secret/)+ expect(JSON.stringify(asOutsider.body.data)).not.toContain(s.secret)+ expect(asOwner.body.data.goal.thisWeek.shipped).toBe(3)+ // A private chat's ship record counts for no one, whatever the scope.+ expect(JSON.stringify(asOwner.body.data)).not.toMatch(/Peer and PM/)+ const one = await get(url, owner)+ expect(score(one.body, peer.sub).shipped.count).toBe(2)+ expect(one.body.data).not.toHaveProperty('allProjects')+ })++ it('All projects adds Lent earned on a private project only for who reads it', async () => {+ const s = await scene(state => {+ const secret = state.projects!.find(p => p.name === 'Secret')!+ state.machines = [{ machineId: 'peer-mac', name: 'Peer Mac', contributorId: peer.sub, membershipGeneration: state.people.find(p => p.id === peer.sub)!.generation, generation: 'g1',+ cwd: '/repo', engines: ['claude'], maxAgents: 2, paused: false, lentDays: [{ day: Math.floor(NOW / 86_400_000) * 86_400_000, projectId: secret.id, busyMs: 30 * HOUR }] }]+ })+ const url = `/api/super-tabs/${s.tabId}/leaderboard?projectId=lead&period=30d&scope=all`+ expect(score((await get(url, owner)).body, peer.sub).lent).toEqual({ machines: 1, agentMs: 30 * HOUR })+ const outsiders = await get(url, outsider)+ expect(score(outsiders.body, peer.sub).lent).toEqual({ machines: 0, agentMs: 0 })+ expect(score(outsiders.body, peer.sub).details.lent).toEqual([])+ })++ it('All projects sums a Swarm from before projects, whose list is not stored', async () => {+ const s = await scene(state => {+ const secret = state.projects!.find(p => p.name === 'Secret')!+ state.conversations = state.conversations.filter(c => c.projectId !== secret.id)+ state.agents = state.agents.filter(a => state.conversations.some(c => c.agentIds.includes(a.id)))+ delete state.projects+ })+ const { status, body } = await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=lead&period=7d&scope=all`, peer)+ expect(status).toBe(200)+ expect(score(body, peer.sub).shipped.count).toBeGreaterThan(0)+ })++ it('All projects names a private project\'s PM only to who reads that project', async () => {+ const s = await scene(state => {+ const project = state.projects!.find(p => p.name === 'Secret')!+ const lead = state.conversations.find(c => c.id === project.leadConversationId)!+ const pm = { ...state.agents[0]!, id: 'secret-pm', harnessId: 'secret-pm-harness', name: 'Secret PM', displayName: 'Secret PM' }+ state.agents.push(pm)+ lead.leadId = pm.id+ lead.agentIds = [pm.id]+ })+ const url = `/api/super-tabs/${s.tabId}/leaderboard?projectId=lead&period=7d&scope=all`+ expect(JSON.stringify((await get(url, owner)).body.data.agents)).toContain('Secret PM')+ expect(JSON.stringify((await get(url, outsider)).body.data)).not.toContain('Secret PM')+ })++ it('reads All projects\' dormant groups too, and refuses it for a week', async () => {+ const s = await scene(state => {+ const secret = state.conversations.find(c => c.title === 'Hidden')!+ Object.assign(secret, { dormant: true, lastActivityAt: new Date(NOW - 2 * HOUR).toISOString() })+ })+ const url = `/api/super-tabs/${s.tabId}/leaderboard?projectId=lead&period=7d&scope=all`+ expect(score((await get(url, owner)).body, peer.sub).details.shipped.map((d: { title: string }) => d.title)).toContain('Hidden')+ expect((await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=lead&scope=all`)).status).toBe(400)+ })++ it('answers the same whatever the reader asks twice', async () => {+ const s = await scene()+ const url = `/api/super-tabs/${s.tabId}/leaderboard?projectId=lead&period=30d`+ expect((await get(url)).body.data).toEqual((await get(url)).body.data)+ })++ it('keeps a private project\'s board to its readers, refused as any other id is', async () => {+ const s = await scene()+ const secret = await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=${s.secret}&period=7d`, outsider)+ const unknown = await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=no-such-project&period=7d`, outsider)+ expect(secret.status).toBe(404)+ expect(unknown.status).toBe(404)+ expect(secret.body.error).toEqual(unknown.body.error)+ })++ it('refuses an unknown period, and a week and period together', async () => {+ const s = await scene()+ expect((await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=lead&period=90d`)).status).toBe(400)+ expect((await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=lead&period=7d&week=${WEEK}`)).status).toBe(400)+ })++ it('still answers an older app that asks for a week, with no period in it', async () => {+ const s = await scene()+ const { status, body } = await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=lead`)+ expect(status).toBe(200)+ expect(body.data).toMatchObject({ week: WEEK })+ expect(body.data).not.toHaveProperty('period')+ })+ })+it('leaves the ledger out of the groups every reader loads', async () => {const s = await scene()const { body } = await get(`/api/super-tabs/${s.tabId}/parts`, peer)diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex 819d35146..ec2f0514e 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -7,6 +7,7 @@ import { attachmentsFromEnv, FORM_TOO_LARGE_MESSAGE, MAX_FORM_ATTACHMENT_BYTES,import { validateBody, validateParams, validateQuery } from '../middlewares/validation.js'import { sendError, sendSuccess } from '../utils/response.js'import { operationSchema } from '../superTabs/commands.js'+import { PERIODS } from '../superTabs/leaderboard/rolling.js'import { fail, SuperTabError } from '../superTabs/model.js'import { SuperTabStore } from '../superTabs/store.js'import { redisPollMemory } from '../superTabs/pollMemory.js'@@ -63,7 +64,9 @@ const listQuery = z.object({ after: id.optional(), mentions: z.literal('1').opticonst cursor = z.string().min(1).max(512).regex(/^[A-Za-z0-9_-]+$/)const changesQuery = agentQuery.extend({ cursor })const costsQuery = z.object({ days: z.coerce.number().int().min(1).max(MAX_DAYS).default(DEFAULT_DAYS), asAgentId: id.optional() }).strict()-const leaderboardQuery = z.object({ projectId: id, week: z.coerce.number().int().nonnegative().safe().optional() }).strict()+const leaderboardQuery = z.object({ projectId: id, week: z.coerce.number().int().nonnegative().safe().optional(), period: z.enum(PERIODS).optional(), scope: z.literal('all').optional() }).strict()+ .refine(query => query.week === undefined || query.period === undefined, 'Ask for a week or a period, not both.')+ .refine(query => query.scope === undefined || query.period !== undefined, 'All projects is read by period.')const dormantQuery = agentQuery.extend({ dormant: z.literal('1'), projectId: id.optional(), before: cursor.optional() })const groupParams = tabParams.extend({ conversationId: id })const hostChangesQuery = z.object({ cursor: cursor.optional(), full: z.literal('1').optional() }).strict()@@ -497,7 +500,7 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su(req, reply) => respond(reply, () => reads.markActivityRead(req.user!, req.params.tabId, req.body.through)))app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof leaderboardQuery> }>('/api/super-tabs/:tabId/leaderboard',{ preHandler: [validateParams(tabParams), validateQuery(leaderboardQuery)] },- (req, reply) => respond(reply, () => reads.leaderboard(req.user!, req.params.tabId, req.query.projectId, req.query.week)))+ (req, reply) => respond(reply, () => reads.leaderboard(req.user!, req.params.tabId, req.query.projectId, req.query.week, req.query.period, req.query.scope === 'all')))app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof dormantQuery> }>('/api/super-tabs/:tabId/groups',{ preHandler: [validateParams(tabParams), validateQuery(dormantQuery)] },(req, reply) => respond(reply, () => reads.dormant(req.user!, req.params.tabId, { projectId: req.query.projectId, before: req.query.before }, req.query.asAgentId)))diff --git a/backend/src/superTabs/buddyMachines.test.ts b/backend/src/superTabs/buddyMachines.test.tsindex d8c3f666d..e2587a737 100644--- a/backend/src/superTabs/buddyMachines.test.ts+++ b/backend/src/superTabs/buddyMachines.test.ts@@ -155,6 +155,15 @@ describe('a Buddy on its person\'s own machine outside the Swarm', () => {}})+ it('keeps a machine\'s daily Lent rows out of every Swarm read: only the leaderboard read uses them', () => {+ const f = setup()+ f.state.machines!.find(m => m.machineId === 'owner-mac')!.lentDays = [{ day: 0, projectId: 'lead', busyMs: 1 }]+ for (const reader of [owner, peer, pmActor(f)]) {+ expect(visibleState(f.state, reader, 1000).machines!.find(m => m.machineId === 'owner-mac')).not.toHaveProperty('lentDays')+ }+ expect(f.state.machines!.find(m => m.machineId === 'owner-mac')!.lentDays).toEqual([{ day: 0, projectId: 'lead', busyMs: 1 }])+ })+it('never serves the Swarm\'s local models, and its host is not told the Swarm\'s grid or to join a Team account', async () => {const f = setup()f.state.localModels = { grid: 'swarm-grid', enabled: true, ready: true }diff --git a/backend/src/superTabs/leaderboard/contract.ts b/backend/src/superTabs/leaderboard/contract.tsindex ba0df0491..6536eb529 100644--- a/backend/src/superTabs/leaderboard/contract.ts+++ b/backend/src/superTabs/leaderboard/contract.ts@@ -1,8 +1,11 @@/**- * The leaderboard read's response (`GET /api/super-tabs/:tabId/leaderboard?projectId=&week=`), the `data` of the usual- * envelope. Desktop/web (`desktop/lib/super_tabs/leaderboard`) mirror it by hand. Times are epoch milliseconds; people are+ * The leaderboard read's response (`GET /api/super-tabs/:tabId/leaderboard?projectId=&week=` or `&period=`), the `data` of+ * the usual envelope. Asked for a period (rolling.ts), "week" below means that period and "last week" the one of the same+ * length before it. Desktop/web (`desktop/lib/super_tabs/leaderboard`) mirror it by hand. Times are epoch milliseconds; people are* member ids. The only conversation text in it is the titles of conversations the reader may read (details); no message text.*/+import type { PeriodName } from './rolling.js'+export type Medal = 'gold' | 'silver' | 'bronze'export type UnblockKind = 'decision' | 'approval' | 'needs_human' | 'tag_reply'@@ -20,8 +23,8 @@ export interface PersonScore {/** Their profile name, else their email's local part. */displayName: stringpoints: number- /** The same scoring for the week before, for the arrow against last week. */- prevWeekPoints: number+ /** The same scoring for the week before, for the arrow against last week. Null for Last 30d, which has no comparison. */+ prevWeekPoints: number | null/** 1 for the most points; people with the same points share a rank. */rank: number/** For the top three ranks with points; null otherwise. */@@ -94,14 +97,18 @@ export interface RecentModel {export interface Leaderboard {projectId: stringweek: number+ /** The rolling period this sums, when one was asked for; `end` is the read's time. Absent from a week's answer. */+ period?: { name: PeriodName; start: number; end: number }+ /** Sums every project the reader may read, and lists everyone in the Swarm: the roster's All projects. Absent otherwise. */+ allProjects?: true/** The team's goal: everyone's points count toward it. */- goal: { openRequests: number; thisWeek: WeekGoal; lastWeek: WeekGoal }+ goal: { openRequests: number; thisWeek: WeekGoal; lastWeek: WeekGoal | null }/** Every person who reads the project, most points first. */people: PersonScore[]/** Agents waiting on a person now: how many per person, in name order. Never ranked, never in the points. */waiting: { total: number; people: Array<{ personId: string; count: number; conversationIds: string[] }> }/** Absent from a backend before it. */- models: { thisWeek: ModelShare; lastWeek: ModelShare }+ models: { thisWeek: ModelShare; lastWeek: ModelShare | null }/** The project's PM and Buddies, most points first. Absent from a backend before them. */agents: AgentScore[]/** Every model that worked this week, most points first. Absent from a backend before it. */diff --git a/backend/src/superTabs/leaderboard/lent.test.ts b/backend/src/superTabs/leaderboard/lent.test.tsindex de2804700..09906be28 100644--- a/backend/src/superTabs/leaderboard/lent.test.ts+++ b/backend/src/superTabs/leaderboard/lent.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from 'vitest'import { MACHINE_FRESH_MS, type ContributedMachine } from '../machines.js'import { createSuperTab, type Agent, type Conversation, type SuperTabState, type WorkStatus } from '../model.js'-import { accrueLent, addLent, lentAgents } from './lent.js'+import { accrueLent, addLent, lentAgents, lentProjects } from './lent.js'import { WEEK_MS, weekStart } from './week.js'// Monday 2026-10-26 00:00 UTC.@@ -83,6 +83,15 @@ describe('lent agent-hours from machine readings', () => {expect(pool.lent).toEqual([{ week: MONDAY, busyMs: 10_000 }])})+ it('keeps each day\'s time under the project of the task, and a task of no project under the default one', () => {+ const inSecret = { ...task('a'), projectId: 'secret' }+ const pool = machine(['h-a', 'h-b'], MONDAY), state = swarm(pool, [agent('a'), agent('b')], [inSecret, task('b')])+ accrueLent(state, pool, MONDAY + 10_000)+ expect(pool.lentDays).toEqual([{ day: MONDAY, projectId: 'secret', busyMs: 10_000 }, { day: MONDAY, projectId: 'lead', busyMs: 10_000 }])+ expect(pool.lent).toEqual([{ week: MONDAY, busyMs: 20_000 }])+ expect(lentProjects(state, pool, ['h-a', 'h-b'])).toEqual({ secret: 1, lead: 1 })+ })+it('adds nothing on the first reading', () => {const pool = machine([], 0), state = swarm(pool, [agent('a')])delete pool.observation@@ -114,7 +123,8 @@ describe('lent for a report that loads no Swarm (DB 2.5)', () => {[['h-idle'], MONDAY + 10_000]] as const) {const full = scene([...running]), fast = scene([...running])accrueLent(full, full.machines![0]!, now)- addLent(fast.machines![0]!, now, lentAgents(fast, fast.machines![0]!, fast.machines![0]!.observation!.runningHarnessIds))+ addLent(fast.machines![0]!, now, lentAgents(fast, fast.machines![0]!, fast.machines![0]!.observation!.runningHarnessIds),+ lentProjects(fast, fast.machines![0]!, fast.machines![0]!.observation!.runningHarnessIds))expect(fast.machines![0]!.lent, JSON.stringify(running)).toEqual(full.machines![0]!.lent)}expect(lentAgents(scene([]), scene([]).machines![0]!, ['h-busy', 'h-idle'])).toBe(1)diff --git a/backend/src/superTabs/leaderboard/lent.ts b/backend/src/superTabs/leaderboard/lent.tsindex 79dfa911b..fdd557814 100644--- a/backend/src/superTabs/leaderboard/lent.ts+++ b/backend/src/superTabs/leaderboard/lent.ts@@ -5,36 +5,51 @@* Lead's session is confidential coordination, not lent build work (Lead's ruling on the review of #1762).*/import { MACHINE_FRESH_MS, type ContributedMachine } from '../machines.js'-import type { SuperTabState } from '../model.js'+import type { Conversation, SuperTabState } from '../model.js'import { ledProject } from '../projects.js'import { LEDGER_WEEKS } from './record.js'-import { WEEK_MS, weekStart } from './week.js'+import { DAY_MS, WEEK_MS, weekStart } from './week.js'/** `busyMs`: agent time spent on other people's tasks, the only time Lent counts (Dee, 2026-10-28). `agentMs`: online agent* time, recorded before then and no longer counted or written. */export interface LentWeek { week: number; agentMs?: number; busyMs?: number }+/** The same busy time by UTC day and the project of the task it went to, for the rolling periods (rolling.ts): a project a+ * reader may not read adds nothing to what they see (review of #2499). */+export interface LentDay { day: number; projectId: string; busyMs: number }/** Credits the time since the machine's previous reading, at most one fresh reading's worth, to each Swarm agent that* reading showed running and that is working on a task someone else asked for: one nobody named counts as someone else's.* Call it before the new reading replaces the previous one. */export function accrueLent(state: SuperTabState, pool: ContributedMachine, now: number): void {- addLent(pool, now, lentAgents(state, pool, pool.observation?.runningHarnessIds ?? []))+ const running = pool.observation?.runningHarnessIds ?? []+ addLent(pool, now, lentAgents(state, pool, running), lentProjects(state, pool, running))}/** How many of the machine's agents among the [running] sessions Lent counts: each working on a task someone else asked* for, never a Lead's or a private chat's. A reading-only report adds time for the count its last full report recorded. */export function lentAgents(state: SuperTabState, pool: ContributedMachine, running: readonly string[]): number {+ return lentTasks(state, pool, running).length+}++/** The same agents by the project of the task each works on. */+export function lentProjects(state: SuperTabState, pool: ContributedMachine, running: readonly string[]): Record<string, number> {+ const projects: Record<string, number> = {}+ for (const task of lentTasks(state, pool, running)) projects[task.projectId ?? 'lead'] = (projects[task.projectId ?? 'lead'] ?? 0) + 1+ return projects+}++function lentTasks(state: SuperTabState, pool: ContributedMachine, running: readonly string[]): Conversation[] {const sessions = new Set(running)const privateChats = state.conversations.filter(c => c.audience)- const busy = new Set(state.conversations.filter(c => !c.audience && c.assignment?.status === 'working' && c.requesterId !== pool.contributorId)- .map(c => c.assignment!.agentId))+ const busy = new Map(state.conversations.filter(c => !c.audience && c.assignment?.status === 'working' && c.requesterId !== pool.contributorId)+ .map(c => [c.assignment!.agentId, c]))return state.agents.filter(a => a.machineId === pool.machineId && sessions.has(a.harnessId) && busy.has(a.id)- && !ledProject(state, a.id) && !privateChats.some(c => c.agentIds.includes(a.id))).length+ && !ledProject(state, a.id) && !privateChats.some(c => c.agentIds.includes(a.id))).map(a => busy.get(a.id)!)}/** Credits [count] agents with the time since the machine's previous reading, at most one fresh reading's worth, in the* current week. Call it before the new reading replaces the previous one. */-export function addLent(pool: ContributedMachine, now: number, count: number): void {+export function addLent(pool: ContributedMachine, now: number, count: number, projects: Record<string, number> = {}): void {const previous = pool.observationif (!previous) returnconst elapsed = Math.min(Math.max(0, now - previous.receivedAt), MACHINE_FRESH_MS)@@ -44,4 +59,13 @@ export function addLent(pool: ContributedMachine, now: number, count: number): vconst current = kept.find(l => l.week === week) ?? kept[kept.push({ week }) - 1]!current.busyMs = (current.busyMs ?? 0) + elapsed * countpool.lent = kept+ // One row per day and project, for LEDGER_WEEKS: they cover every kept week and Last 30d, and go as they age. Time with no+ // project named (a reading recorded by an older server) stays in the week's row alone.+ const today = Math.floor(now / DAY_MS) * DAY_MS+ const days = (pool.lentDays ?? []).filter(d => now - d.day < LEDGER_WEEKS * WEEK_MS)+ for (const [projectId, agents] of Object.entries(projects)) {+ const day = days.find(d => d.day === today && d.projectId === projectId) ?? days[days.push({ day: today, projectId, busyMs: 0 }) - 1]!+ day.busyMs += elapsed * agents+ }+ pool.lentDays = days}diff --git a/backend/src/superTabs/leaderboard/read.ts b/backend/src/superTabs/leaderboard/read.tsindex 59c53a0ce..ec3a72402 100644--- a/backend/src/superTabs/leaderboard/read.ts+++ b/backend/src/superTabs/leaderboard/read.ts@@ -22,7 +22,7 @@ const BOARD_FIELDS = ['id', 'kind', 'projectId', 'title', 'leadId', 'audience',/** Dormant groups of one project active since [since]: a request shipped in a week the board sums wrote its Done row then.* Only the fields the board reads: every open board reads them once a minute (Diego's issue file, 2026-10-27). */-export async function recentDormantGroups(tx: Prisma.TransactionClient, tabId: string, projectId: string, since: number): Promise<Conversation[]> {+export async function recentDormantGroups(tx: Prisma.TransactionClient, tabId: string, projectId: string | string[], since: number): Promise<Conversation[]> {// Through the project index by name (parts/indexed.ts): planned, this read could take the dormancy one and read every quiet// conversation of the Swarm to return none.const rows = await groupsBy(tx, 'project', [{ $match: quietSince(tabId, projectId, since) },diff --git a/backend/src/superTabs/leaderboard/record.ts b/backend/src/superTabs/leaderboard/record.tsindex ec427dfc2..b0d4e4247 100644--- a/backend/src/superTabs/leaderboard/record.ts+++ b/backend/src/superTabs/leaderboard/record.ts@@ -4,6 +4,7 @@*/import { isLeads, type Actor, type Agent, type AgentConfiguration, type Assignment, type Author, type Check, type Conversation, type SuperTabState, type WorkStatus } from '../model.js'import { groupProject, ledProject } from '../projects.js'+import { HOUR_MS } from './rolling.js'import { WEEK_MS, weekStart } from './week.js'import { agentTarget } from '../rules.js'import type { UnblockKind } from './contract.js'@@ -38,6 +39,8 @@ export interface RanOn { engine: string; model: string | null; effort?: string;* model's points (Lead, 2026-10-29). Counted, not listed, so no cap ever drops an earned point (review of #2097). A* person's verdict is no model's. */export interface ReviewCount extends RanOn { week: number; count: number }+/** The same verdicts by hour, for the rolling periods (rolling.ts): one row per hour and model that had one. */+export interface ReviewHour extends RanOn { hour: number; count: number }/** A group's leaderboard bookkeeping; readers never get it whole (read/views.ts groupView). */export interface GroupLedger {askedAt?: number@@ -68,6 +71,8 @@ export interface GroupLedger {shippedLeadId?: string | null/** Review verdicts by week and model, for the last LEDGER_WEEKS weeks, oldest first. */reviews?: ReviewCount[]+ /** The same by hour, for the last LEDGER_WEEKS weeks. */+ reviewHours?: ReviewHour[]/** The Buddy's proposal the group was opened from: the Buddy earns when it ships (Lead, 2026-10-29). */proposal?: { buddyId: string; messageId: string }}@@ -300,6 +305,12 @@ export function recordVerdict(state: SuperTabState, group: Conversation, check:if (same) same.count++else kept.push({ week, ...on, count: 1 })ledger.reviews = kept+ const hour = Math.floor(now / HOUR_MS) * HOUR_MS+ const hours = (ledger.reviewHours ?? []).filter(r => now - r.hour < LEDGER_WEEKS * WEEK_MS)+ const sameHour = hours.find(r => r.hour === hour && r.engine === on.engine && r.model === on.model && r.effort === on.effort && r.grid === on.grid)+ if (sameHour) sameHour.count+++ else hours.push({ hour, ...on, count: 1 })+ ledger.reviewHours = hours}/** A group opened from a Buddy's proposal remembers it, for the Buddy's points when it ships. */diff --git a/backend/src/superTabs/leaderboard/rolling.test.ts b/backend/src/superTabs/leaderboard/rolling.test.tsnew file mode 100644index 000000000..3e84b2899--- /dev/null+++ b/backend/src/superTabs/leaderboard/rolling.test.ts@@ -0,0 +1,290 @@+import { describe, expect, it } from 'vitest'+import type { ContributedMachine } from '../machines.js'+import { createSuperTab, type Agent, type Check, type Conversation, type SuperTabState } from '../model.js'+import { addLent } from './lent.js'+import { recordVerdict, type GroupLedger } from './record.js'+import { HOUR_MS as HOUR, lentIn, periodSpans, reviewsIn, type PeriodName } from './rolling.js'+import { leaderboard } from './stats.js'+import { DAY_MS as DAY, WEEK_MS as WEEK, weekStart } from './week.js'++// Wednesday 2026-11-25 12:00 UTC.+const NOW = Date.UTC(2026, 10, 25, 12), TODAY = Date.UTC(2026, 10, 25), THIS_WEEK = weekStart(NOW)+const reach = { projects: new Set(['lead']), unsplit: true }+const opus = { engine: 'claude', model: 'opus', effort: 'high' }++function swarm(): SuperTabState {+ const state = createSuperTab('tab', 'Pilot', { id: 'ken', email: '[email protected]' }, 'prod')+ state.people.push({ id: 'dee', email: '[email protected]', role: 'collaborator', generation: 'g' })+ return state+}+let n = 0+const group = (extra: Partial<Conversation> & { ledger?: GroupLedger } = {}): Conversation => ({ id: `r${++n}`, projectId: 'lead', title: `Group ${n}`, leadId: null,+ agentIds: [], archived: false, brief: '', checks: [], assignment: null, lastMessageSequence: 0, ...extra })+const shipped = (at: number, extra: Partial<Conversation> = {}) => group({ requesterId: 'dee', pullRequestUrls: ['https://github.com/o/r/pull/1'], ledger: { askedAt: at - HOUR, shippedAt: at }, ...extra })+const machine = (extra: Partial<ContributedMachine>): ContributedMachine => ({ machineId: 'mac', name: 'Studio', contributorId: 'dee', membershipGeneration: 'g', generation: 'g1',+ cwd: '/repo', engines: ['claude'], maxAgents: 2, paused: false, ...extra })+const read = (period: PeriodName, groups: Conversation[], machines: ContributedMachine[] = [], now = NOW) =>+ leaderboard({ state: swarm(), groups, machines, projectId: 'lead', week: weekStart(now), now, period })+const dee = (view: ReturnType<typeof read>) => view.people.find(p => p.personId === 'dee')!+const spans = (name: PeriodName) => periodSpans(name, NOW)++describe('the rolling periods', () => {+ it('counts a shipped request by its exact time, in the period and the one before it', () => {+ const groups = [shipped(NOW - 23 * HOUR), shipped(NOW - 25 * HOUR), shipped(NOW - 6 * DAY), shipped(NOW - 8 * DAY), shipped(NOW - 29 * DAY), shipped(NOW - 31 * DAY)]+ expect(read('24h', groups).goal).toMatchObject({ thisWeek: { shipped: 1 }, lastWeek: { shipped: 1 } })+ expect(read('7d', groups).goal).toMatchObject({ thisWeek: { shipped: 3 }, lastWeek: { shipped: 1 } })+ expect(read('30d', groups).goal.thisWeek.shipped).toBe(5)+ })++ it('names the period it summed; a week\'s answer names none', () => {+ expect(read('7d', [])).toMatchObject({ week: THIS_WEEK, period: { name: '7d', start: NOW + 1 - WEEK, end: NOW } })+ expect(leaderboard({ state: swarm(), groups: [], machines: [], projectId: 'lead', week: THIS_WEEK, now: NOW })).not.toHaveProperty('period')+ })++ it('has no comparison for Last 30d: nothing says 0 when nothing was read', () => {+ const view = read('30d', [shipped(NOW - DAY)])+ expect(view.goal.lastWeek).toBeNull()+ expect(view.models.lastWeek).toBeNull()+ expect(dee(view).prevWeekPoints).toBeNull()+ })++ it('scores points, details, agents and models over the same period', () => {+ const answers = group({ ledger: { unblocks: [{ personId: 'dee', at: NOW - HOUR, waitedMs: 0, kind: 'decision' }, { personId: 'dee', at: NOW - 3 * DAY, waitedMs: 0, kind: 'decision' }] } })+ const ran = shipped(NOW - HOUR, { ledger: { askedAt: NOW - 2 * HOUR, shippedAt: NOW - HOUR, runs: [{ assignmentId: 'a', at: NOW - 2 * HOUR, ...opus }] } })+ const view = read('24h', [answers, ran, shipped(NOW - 3 * DAY)])+ expect(dee(view)).toMatchObject({ points: 4, prevWeekPoints: 0, shipped: { count: 1 }, unblocked: { count: 1 } })+ expect(dee(view).details.shipped).toHaveLength(1)+ expect(view.byModel).toMatchObject([{ model: 'opus', shipped: { count: 1 }, attempts: 1 }])+ expect(dee(read('7d', [answers, ran, shipped(NOW - 3 * DAY)]))).toMatchObject({ points: 8, shipped: { count: 2 }, unblocked: { count: 2 } })+ })++ it('never counts a private conversation or a machine it was not handed', () => {+ const hidden = shipped(NOW - HOUR, { audience: { people: [{ id: 'dee', generation: 'g' }] }, ledger: { askedAt: 0, shippedAt: NOW - HOUR,+ reviewHours: [{ hour: TODAY, ...opus, count: 9 }] } })+ const view = read('7d', [hidden])+ expect(dee(view).shipped.count).toBe(0)+ expect(view.byModel).toEqual([])+ expect(JSON.stringify(view)).not.toContain(hidden.title)+ })+})++describe('All projects', () => {+ const twoProjects = () => {+ const state = swarm()+ state.projects!.push({ ...state.projects![0]!, id: 'other', leadConversationId: 'other-lead', name: 'Other' }, { ...state.projects![0]!, id: 'secret', leadConversationId: 'secret-lead', name: 'Secret' })+ return state+ }+ const here = shipped(NOW - HOUR), there = shipped(NOW - 2 * HOUR, { projectId: 'other', title: 'Over there' }), tucked = shipped(NOW - 3 * HOUR, { projectId: 'secret', title: 'Tucked away' })+ const all = (projects: string[], groups: Conversation[]) => leaderboard({ state: twoProjects(), groups, machines: [], projectId: 'lead', week: THIS_WEEK, now: NOW, period: '7d', allProjects: projects })++ it('sums every project it is given, one project\'s board only its own', () => {+ const groups = [here, there]+ const view = all(['lead', 'other'], groups)+ expect(view.allProjects).toBe(true)+ expect(view.goal.thisWeek.shipped).toBe(2)+ expect(dee(view)).toMatchObject({ points: 6, shipped: { count: 2 } })+ const one = leaderboard({ state: twoProjects(), groups, machines: [], projectId: 'lead', week: THIS_WEEK, now: NOW, period: '7d' })+ expect(one).not.toHaveProperty('allProjects')+ expect(dee(one)).toMatchObject({ points: 3, shipped: { count: 1 } })+ })++ it('lists a person\'s one Buddy once across the projects summed, and only if they read one of them', () => {+ const state = twoProjects()+ state.projects![0]!.visibility = 'private'+ state.projects![1]!.visibility = 'private'+ state.projects![2]!.visibility = 'private'+ state.projects![1]!.members = [{ id: 'dee', generation: 'g' }]+ state.projects![2]!.members = [{ id: 'dee', generation: 'g' }]+ state.agents.push({ id: 'dee-buddy', machineId: 'mac', harnessId: 'h-b', machineOwnerId: 'dee', contributorId: 'dee', membershipGeneration: 'g', name: 'Dee Buddy',+ configuration: { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null }, buddyOf: { personId: 'dee', generation: 'g' }, buddyScope: 'swarm' } as unknown as Agent)+ const reading = (projects: string[]) => leaderboard({ state, groups: [], machines: [], projectId: 'lead', week: THIS_WEEK, now: NOW, period: '7d', allProjects: projects }).agents+ expect(reading(['lead', 'other', 'secret']).filter(a => a.agentId === 'dee-buddy')).toHaveLength(1)+ expect(reading(['lead']).filter(a => a.agentId === 'dee-buddy')).toEqual([])+ })++ it('counts nothing of a project the reader may not read, though its group is at hand', () => {+ const view = all(['lead', 'other'], [here, there, tucked])+ expect(dee(view).shipped.count).toBe(2)+ expect(JSON.stringify(view)).not.toContain('Tucked away')+ })++ it('keeps the sidebar\'s recent models to the open project', () => {+ const run = (projectId: string, model: string) => group({ projectId, ledger: { runs: [{ assignmentId: `a-${model}`, at: NOW - HOUR, engine: 'claude', model }] } })+ const view = all(['lead', 'other'], [run('lead', 'opus'), run('other', 'sonnet')])+ expect(view.recentModels.map(m => m.model)).toEqual(['opus'])+ expect(view.byModel.map(m => m.model).sort()).toEqual(['opus', 'sonnet'])+ })+})++describe('Lent in a rolling period', () => {+ it('shares a day out over the part of it that has passed, so the periods add up', () => {+ const pool = { lentDays: [{ day: TODAY, projectId: 'lead', busyMs: 6 * HOUR }, { day: TODAY - DAY, projectId: 'lead', busyMs: 12 * HOUR }, { day: TODAY - 2 * DAY, projectId: 'lead', busyMs: 24 * HOUR }] }+ // Now is noon: all of today, the second half of yesterday.+ expect(Math.round(lentIn(pool, spans('24h').current, NOW, reach) / HOUR)).toBe(12)+ expect(Math.round(lentIn(pool, spans('24h').previous!, NOW, reach) / HOUR)).toBe(18)+ expect(lentIn(pool, spans('7d').current, NOW, reach)).toBe(42 * HOUR)+ })++ it('reads days only for a period and weeks only for a week', () => {+ const pool = { lent: [{ week: THIS_WEEK, busyMs: 10 * HOUR }], lentDays: [{ day: TODAY, projectId: 'lead', busyMs: 10 * HOUR }] }+ expect(lentIn(pool, { start: THIS_WEEK, end: THIS_WEEK + WEEK, rolling: false }, NOW, reach)).toBe(10 * HOUR)+ expect(lentIn(pool, spans('7d').current, NOW, reach)).toBe(10 * HOUR)+ })++ it('counts a week recorded before the days once, at its end, and only what its days do not hold', () => {+ // Wednesday 2026-11-04, reading the week before the finer rows began.+ const now = Date.UTC(2026, 10, 4, 12), last = Date.UTC(2026, 9, 26), at = (name: PeriodName) => periodSpans(name, now).current+ const pool = { lent: [{ week: last, busyMs: 10 * HOUR }], lentDays: [{ day: last + 6 * DAY, projectId: 'lead', busyMs: 4 * HOUR }] }+ expect(lentIn(pool, at('30d'), now, reach)).toBe(10 * HOUR)+ // The unsplit 6 hours fall in the middle of that week: in Last 7d, with the day's row, and no lump in Last 24h.+ expect(lentIn(pool, at('7d'), now, reach)).toBe(10 * HOUR)+ expect(lentIn(pool, at('24h'), now, reach)).toBe(0)+ })++ it('reads the same however many times it is asked, and writes nothing', () => {+ const pool = machine({ lent: [{ week: THIS_WEEK - WEEK, busyMs: 22 * HOUR }], lentDays: [] })+ const before = structuredClone(pool)+ const first = read('30d', [], [pool]), second = read('30d', [], [pool])+ expect(dee(first).lent.agentMs).toBe(22 * HOUR)+ expect(dee(second)).toEqual(dee(first))+ expect(pool).toEqual(before)+ })++ it('ignores a week\'s old online hours, as the weekly read does', () => {+ expect(lentIn({ lent: [{ week: THIS_WEEK - WEEK, agentMs: 40 * HOUR }] }, spans('30d').current, NOW, reach)).toBe(0)+ })++ it('scores a machine by the period', () => {+ const pool = machine({ lentDays: [{ day: TODAY, projectId: 'lead', busyMs: 20 * HOUR }, { day: TODAY - 10 * DAY, projectId: 'lead', busyMs: 30 * HOUR }] })+ expect(dee(read('7d', [], [pool]))).toMatchObject({ points: 2, lent: { machines: 1, agentMs: 20 * HOUR }, details: { lent: [{ machineName: 'Studio', busyHours: 20 }] } })+ expect(dee(read('30d', [], [pool]))).toMatchObject({ points: 5, lent: { agentMs: 50 * HOUR } })+ })+})++describe('Lent of a project out of reach (review of #2499)', () => {+ const secret = { day: TODAY, projectId: 'secret', busyMs: 20 * HOUR }, mine = { day: TODAY, projectId: 'lead', busyMs: 10 * HOUR }++ it('adds nothing to All projects or a project\'s board, only what those projects earned', () => {+ const pool = machine({ lentDays: [secret, mine] })+ expect(dee(read('7d', [], [pool]))).toMatchObject({ points: 1, lent: { agentMs: 10 * HOUR } })+ const all = (projects: string[]) => leaderboard({ state: swarm(), groups: [], machines: [pool], projectId: 'lead', week: THIS_WEEK, now: NOW, period: '7d', allProjects: projects })+ expect(dee(all(['lead'])).lent.agentMs).toBe(10 * HOUR)+ const asOwner = swarm()+ asOwner.projects!.push({ ...asOwner.projects![0]!, id: 'secret', leadConversationId: 'secret-lead' })+ expect(dee(leaderboard({ state: asOwner, groups: [], machines: [pool], projectId: 'lead', week: THIS_WEEK, now: NOW, period: '7d', allProjects: ['lead', 'secret'] })).lent.agentMs).toBe(30 * HOUR)+ })++ it('never comes back as unsplit weekly time', () => {+ const pool = { lent: [{ week: weekStart(TODAY), busyMs: 30 * HOUR }], lentDays: [secret, mine] }+ expect(lentIn(pool, spans('7d').current, NOW, reach)).toBe(10 * HOUR)+ })++ it('leaves a weekly row, which names no project, out for someone no board of the reader shows', () => {+ const state = swarm(), last = Date.UTC(2026, 9, 26), now = Date.UTC(2026, 10, 2, 12)+ state.projects![0]!.visibility = 'private'+ state.projects!.push({ ...state.projects![0]!, id: 'secret', leadConversationId: 'secret-lead', members: [{ id: 'dee', generation: 'g' }] })+ const pool = machine({ lent: [{ week: last, busyMs: 20 * HOUR }] })+ const asRead = (projects: string[]) => leaderboard({ state, groups: [], machines: [pool], projectId: 'lead', week: weekStart(now), now, period: '30d', allProjects: projects })+ expect(dee(asRead(['lead']))).toMatchObject({ points: 0, lent: { machines: 0, agentMs: 0 } })+ expect(dee(asRead(['lead', 'secret'])).lent.agentMs).toBe(20 * HOUR)+ })+})++describe('the week finer rows began', () => {+ it('leaves a week\'s unsplit part on the first day, so it never stays in Last 24h until Sunday', () => {+ // Thursday of the week of 2026-11-02, with Monday's and Tuesday's work recorded by week only.+ const now = Date.UTC(2026, 10, 5, 12), week = Date.UTC(2026, 10, 2)+ const pool = { lent: [{ week, busyMs: 8 * HOUR }] }, ledger = { reviews: [{ week, ...opus, count: 3 }] }+ expect(lentIn(pool, periodSpans('24h', now).current, now, reach)).toBe(0)+ expect(lentIn(pool, periodSpans('7d', now).current, now, reach)).toBe(8 * HOUR)+ expect(reviewsIn(ledger, periodSpans('24h', now).current)).toEqual([])+ expect(reviewsIn(ledger, periodSpans('7d', now).current)).toMatchObject([{ count: 3 }])+ })+})++describe('a week that just ended', () => {+ it('is no lump in Last 24h: read on the Monday after, its unsplit part sits mid-week', () => {+ const now = Date.UTC(2026, 10, 2, 6), last = Date.UTC(2026, 9, 26)+ const pool = { lent: [{ week: last, busyMs: 30 * HOUR }] }+ expect(lentIn(pool, periodSpans('24h', now).current, now, reach)).toBe(0)+ expect(lentIn(pool, periodSpans('7d', now).current, now, reach)).toBe(30 * HOUR)+ })+})++describe('review verdicts in a rolling period', () => {+ it('counts each hour\'s verdicts in the one period that holds them', () => {+ const ledger = { reviewHours: [{ hour: NOW - HOUR, ...opus, count: 2 }, { hour: NOW - 30 * HOUR, ...opus, count: 5 }] }+ expect(reviewsIn(ledger, spans('24h').current)).toMatchObject([{ count: 2 }])+ expect(reviewsIn(ledger, spans('24h').previous!)).toMatchObject([{ count: 5 }])+ expect(read('24h', [group({ ledger })]).byModel).toMatchObject([{ model: 'opus', reviews: 2, points: 2 }])+ })++ it('counts a week recorded before the hours once, per model, without what the hours hold', () => {+ const week = THIS_WEEK - WEEK, sonnet = { ...opus, model: 'sonnet' }+ const ledger = { reviews: [{ week, ...opus, count: 3 }, { week, ...sonnet, count: 1 }], reviewHours: [{ hour: week + DAY, ...opus, count: 3 }, { hour: week + DAY, ...sonnet, count: 0 }] }+ const rows = reviewsIn(ledger, spans('30d').current)+ expect(rows.filter(r => r.model === 'opus').reduce((sum, r) => sum + r.count, 0)).toBe(3)+ expect(rows.filter(r => r.model === 'sonnet').reduce((sum, r) => sum + r.count, 0)).toBe(1)+ })++ it('reads a week by its weekly rows alone', () => {+ const ledger = { reviews: [{ week: THIS_WEEK, ...opus, count: 3 }], reviewHours: [{ hour: NOW - HOUR, ...opus, count: 3 }] }+ expect(reviewsIn(ledger, { start: THIS_WEEK, end: THIS_WEEK + WEEK, rolling: false })).toMatchObject([{ count: 3 }])+ })+})++describe('what a verdict writes', () => {+ const check = { id: 'c1', description: 'Passes', status: 'pending' } as unknown as Check+ const reviewer = { id: 'rev', harnessId: 'h-rev', machineId: 'mac', configuration: { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null } } as unknown as Agent+ const reviewed = () => group({ assignment: { id: 'a', agentId: 'worker' } as Conversation['assignment'], ledger: { runs: [{ assignmentId: 'a', at: NOW - DAY, engine: 'claude', model: 'opus' }] } })++ it('counts it in its week and its hour, one row per hour and model', () => {+ const g = reviewed()+ recordVerdict(swarm(), g, check, reviewer, NOW + 1)+ g.ledger!.runs![0]!.firstVerdicts = undefined+ recordVerdict(swarm(), g, check, reviewer, NOW + 2)+ expect(g.ledger!.reviews).toEqual([{ week: THIS_WEEK, ...opus, count: 2 }])+ expect(g.ledger!.reviewHours).toEqual([{ hour: NOW, ...opus, count: 2 }])+ })++ it('lets go of hours older than the weeks kept', () => {+ const g = reviewed()+ g.ledger!.reviewHours = [{ hour: NOW - 36 * DAY, ...opus, count: 7 }, { hour: NOW - 34 * DAY, ...opus, count: 1 }]+ recordVerdict(swarm(), g, check, reviewer, NOW)+ expect(g.ledger!.reviewHours.map(r => r.hour)).toEqual([NOW - 34 * DAY, NOW])+ })++ it('keeps an assignee\'s own verdict out of both', () => {+ const g = reviewed()+ recordVerdict(swarm(), g, check, { ...reviewer, id: 'worker' }, NOW)+ expect(g.ledger).not.toHaveProperty('reviewHours')+ })+})++describe('what readings write', () => {+ const pool = () => machine({ observation: { receivedAt: NOW - 10_000 } as ContributedMachine['observation'] })++ it('adds a reading to its week and its day', () => {+ const m = pool()+ addLent(m, NOW, 2, { lead: 1, other: 1 })+ addLent(m, NOW, 0)+ expect(m.lent).toEqual([{ week: THIS_WEEK, busyMs: 20_000 }])+ expect(m.lentDays).toEqual([{ day: TODAY, projectId: 'lead', busyMs: 10_000 }, { day: TODAY, projectId: 'other', busyMs: 10_000 }])+ })++ it('keeps a machine\'s days bounded, and every day Last 30d can ask for', () => {+ const m = pool()+ m.lentDays = Array.from({ length: 60 }, (_, back) => ({ day: TODAY - back * DAY, projectId: 'lead', busyMs: 1 }))+ addLent(m, NOW, 1, { lead: 1 })+ expect(m.lentDays.length).toBeLessThanOrEqual(35)+ expect(Math.min(...m.lentDays.map(d => d.day))).toBeLessThanOrEqual(NOW - 30 * DAY)+ expect(m.lentDays.find(d => d.day === TODAY)!.busyMs).toBe(10_001)+ })++ it('never counts a day and its week twice', () => {+ const m = pool()+ addLent(m, NOW, 1, { lead: 1 })+ expect(lentIn(m, spans('7d').current, NOW, reach)).toBe(10_000)+ expect(lentIn(m, spans('30d').current, NOW, reach)).toBe(10_000)+ })+})diff --git a/backend/src/superTabs/leaderboard/rolling.ts b/backend/src/superTabs/leaderboard/rolling.tsnew file mode 100644index 000000000..a7de5799a--- /dev/null+++ b/backend/src/superTabs/leaderboard/rolling.ts@@ -0,0 +1,73 @@+/**+ * The board's rolling periods, Last 24h, Last 7d and Last 30d, ending now (Dee, 2026-11-02). Ship times, answers and attempts+ * have exact times. Review verdicts and Lent were kept by week only, so they are now also kept finer: verdicts by hour, Lent+ * by day. The weekly rows stay and are still written, because an older app reads weeks and a rollback needs them. What a+ * weekly row holds beyond its finer rows was recorded before those existed: it counts in full at one moment (fallsAt). It+ * ages out with its row, so nothing has to rewrite stored data.+ */+import type { ContributedMachine } from '../machines.js'+import type { GroupLedger, RanOn } from './record.js'+import { DAY_MS, WEEK_MS } from './week.js'++export const HOUR_MS = 3_600_000+export const PERIODS = ['24h', '7d', '30d'] as const+export type PeriodName = typeof PERIODS[number]+const PERIOD_MS: Record<PeriodName, number> = { '24h': DAY_MS, '7d': WEEK_MS, '30d': 30 * DAY_MS }++/** The first day finer rows were written; a weekly row of that week or later has at most that much left unsplit. */+const FINER_ROWS_SINCE = Date.UTC(2026, 10, 2)++/** [start, end). `rolling` reads the finer rows, otherwise the span is a leaderboard week and reads its weekly rows. */+export interface Span { start: number; end: number; rolling: boolean }+export const weekSpan = (week: number): Span => ({ start: week, end: week + WEEK_MS, rolling: false })++/** The period ending now, and the one of the same length before it. Last 30d has none: comparing it would need 60 days of+ * records and twice the read, and the board keeps LEDGER_WEEKS. */+export function periodSpans(name: PeriodName, now: number): { current: Span; previous: Span | null } {+ const length = PERIOD_MS[name], end = now + 1, start = end - length+ return { current: { start, end, rolling: true }, previous: name === '30d' ? null : { start: start - length, end: start, rolling: true } }+}++export const within = (at: number, span: Span): boolean => at >= span.start && at < span.end++/** Where the unsplit part of a week's row counts: the middle of its week, or the day finer rows began if that came first, so+ * a week that just ended is no lump in Last 24h, nor the week they began in until Sunday. Never before its week. */+const fallsAt = (week: number): number => Math.max(week, Math.min(week + WEEK_MS / 2, FINER_ROWS_SINCE))++/** What a rolling read of Lent may add: the projects it sums; and whether it may add this machine's unsplit weekly time, which+ * names no project, so it could be a private one's. A reader gets it only for someone a board they can open already shows,+ * as the week read does (review of #2499). */+export interface LentReach { projects: ReadonlySet<string>; unsplit: boolean }++/** A machine's busy agent time in [span]. A day's row is shared out evenly over the part of that day that has passed, so a+ * rolling edge inside a day takes its share: the hours inside a day are not kept (a machine would hold 840 rows). What the+ * weekly row holds beyond its days is told from all its days, the ones of projects out of reach included: otherwise their+ * time would come back as unsplit. */+export function lentIn(machine: Pick<ContributedMachine, 'lent' | 'lentDays'>, span: Span, now: number, reach: LentReach): number {+ if (!span.rolling) return machine.lent?.find(l => l.week === span.start)?.busyMs ?? 0+ const days = machine.lentDays ?? []+ let total = 0+ for (const { day, projectId, busyMs } of days) {+ if (!reach.projects.has(projectId)) continue+ const end = Math.min(day + DAY_MS, now + 1)+ total += busyMs * Math.max(0, Math.min(end, span.end) - Math.max(day, span.start)) / Math.max(1, end - day)+ }+ if (reach.unsplit) {+ for (const { week, busyMs = 0 } of machine.lent ?? []) {+ if (!within(fallsAt(week), span)) continue+ total += Math.max(0, busyMs - days.reduce((sum, d) => sum + (d.day >= week && d.day < week + WEEK_MS ? d.busyMs : 0), 0))+ }+ }+ return Math.round(total)+}++const sameModel = (a: RanOn, b: RanOn): boolean => a.engine === b.engine && a.model === b.model && a.effort === b.effort && !!a.grid === !!b.grid++/** A group's review verdicts in [span], one entry for each stored row or unsplit weekly part. */+export function reviewsIn(ledger: Pick<GroupLedger, 'reviews' | 'reviewHours'>, span: Span): Array<RanOn & { count: number }> {+ const weeks = ledger.reviews ?? [], hours = ledger.reviewHours ?? []+ if (!span.rolling) return weeks.filter(r => r.week === span.start)+ const unsplit = weeks.filter(r => within(fallsAt(r.week), span)).map(r => ({ ...r, count: r.count+ - hours.reduce((sum, h) => sum + (h.hour >= r.week && h.hour < r.week + WEEK_MS && sameModel(h, r) ? h.count : 0), 0) }))+ return [...hours.filter(h => within(h.hour, span)), ...unsplit.filter(r => r.count > 0)]+}diff --git a/backend/src/superTabs/leaderboard/stats.ts b/backend/src/superTabs/leaderboard/stats.tsindex d5dc7ac0f..4b8234c3a 100644--- a/backend/src/superTabs/leaderboard/stats.ts+++ b/backend/src/superTabs/leaderboard/stats.ts@@ -9,6 +9,7 @@ import { isLeads, type Agent, type Conversation, type SuperTabState } from '../mimport { isBuddy, isSwarmBuddy } from '../buddies.js'import { agentProjectId, canReadProject, projectOf } from '../projects.js'import { firstAssignedAt, waitedOn, waitsNow, type RanOn, type Unblock } from './record.js'+import { lentIn, periodSpans, reviewsIn, weekSpan, within, type PeriodName, type Span } from './rolling.js'import { DAY_MS, WEEK_MS } from './week.js'import type { AgentScore, Leaderboard, Medal, ModelScore, ModelShare, PersonDetails, PersonScore, RecentModel, WeekGoal } from './contract.js'@@ -36,31 +37,43 @@ export interface LeaderboardInput {/** The Monday 00:00 UTC the week starts (week.ts). */week: numbernow: number+ /** A rolling period ending now to sum instead of [week] (rolling.ts); [week] is then only the answer's label. */+ period?: PeriodName+ /** Sum every one of these projects instead of [projectId] alone: the ones the reader may read, whose groups [groups] holds.+ * Everyone in the Swarm is then listed. [projectId] stays the board's project and its recent models. */+ allProjects?: string[]/** People's profile names by id, read with the board (read.ts profileNames); absent ones go by their email. */names?: ReadonlyMap<string, string>}-export function leaderboard({ state, groups, machines: visibleMachines, projectId, week, now, names }: LeaderboardInput): Leaderboard {+export function leaderboard({ state, groups, machines: visibleMachines, projectId, week, now, period, allProjects, names }: LeaderboardInput): Leaderboard {const project = projectOf(state, projectId)// The Lead conversation is where plans are approved: its answers count, though nothing there is a request that ships.- const visible = groups.filter(g => !isLeads(g) && !g.audience && (g.projectId ?? 'lead') === projectId)- const shared = visible.filter(g => g.id !== project.leadConversationId)+ const projectIds = new Set(allProjects ?? [projectId])+ const visible = groups.filter(g => !isLeads(g) && !g.audience && projectIds.has(g.projectId ?? 'lead'))+ const leadConversations = new Set([...projectIds].map(id => projectOf(state, id).leadConversationId))+ const shared = visible.filter(g => !leadConversations.has(g.id))const requests = shared.filter(g => !g.reviewOf)// Shipped with a PR: what agents and models are credited for. A person's points also need them to have asked (review// of #2097: a group opened from a Buddy's proposal may name no requester).const shippedRequests = requests.filter(g => g.ledger?.shippedAt != null && (g.pullRequestUrls?.length ?? 0) > 0)const landed = shippedRequests.filter(g => g.requesterId)- const players = state.people.filter(p => canReadProject(state, { kind: 'person', userId: p.id, email: p.email }, project))- const inWeek = (at: number, start = week) => at >= start && at < start + WEEK_MS+ const players = allProjects ? state.people : state.people.filter(p => canReadProject(state, { kind: 'person', userId: p.id, email: p.email }, project))+ const { current, previous } = period ? periodSpans(period, now) : { current: weekSpan(week), previous: weekSpan(week - WEEK_MS) }// Each person's records, gathered once: the board scores every player three times (Diego's issue file, 2026-10-27).const landedBy = byKey(landed, g => g.requesterId!)const answersBy = byKey(visible.flatMap(group => (group.ledger?.unblocks ?? []).map(unblock => ({ ...unblock, group }))), u => u.personId)const machinesBy = byKey(visibleMachines, m => m.contributorId)- const score = (personId: string, start: number) => {- const shippedHere = (landedBy.get(personId) ?? []).filter(g => inWeek(g.ledger!.shippedAt!, start))- const answers = (answersBy.get(personId) ?? []).filter(u => inWeek(u.at, start))+ // Under All projects, whether a board of this reader's already shows the person; a project's board lists only its own.+ const sharesBoard = (personId: string): boolean => {+ const person = state.people.find(p => p.id === personId)+ return !allProjects || (!!person && [...projectIds].some(id => canReadProject(state, { kind: 'person', userId: person.id, email: person.email }, projectOf(state, id))))+ }+ const score = (personId: string, span: Span) => {+ const shippedHere = (landedBy.get(personId) ?? []).filter(g => within(g.ledger!.shippedAt!, span))+ const answers = (answersBy.get(personId) ?? []).filter(u => within(u.at, span))const machines = (machinesBy.get(personId) ?? [])- .map(m => ({ name: m.name, busyMs: m.lent?.find(l => l.week === start)?.busyMs ?? 0 })).filter(m => m.busyMs > 0)+ .map(m => ({ name: m.name, busyMs: lentIn(m, span, now, { projects: projectIds, unsplit: sharesBoard(personId) }) })).filter(m => m.busyMs > 0)const freedMs = sum(answers.map(u => u.waitedMs)), lentMs = sum(machines.map(m => m.busyMs))const points = shippedHere.length * SHIPPED_POINTS + sum(answers.map(unblockPoints)) + Math.floor(lentMs / (LENT_HOURS_PER_POINT * HOUR_MS))const details: PersonDetails = {@@ -79,28 +92,31 @@ export function leaderboard({ state, groups, machines: visibleMachines, projectIdetails,}}- const goal = (start: number): WeekGoal => {- const shippedHere = landed.filter(g => inWeek(g.ledger!.shippedAt!, start))- return { shipped: shippedHere.length, points: sum(players.map(p => score(p.id, start).points)), medianAskToShipMs: median(askToShip(shippedHere)) }+ const goal = (span: Span): WeekGoal => {+ const shippedHere = landed.filter(g => within(g.ledger!.shippedAt!, span))+ return { shipped: shippedHere.length, points: sum(players.map(p => score(p.id, span).points)), medianAskToShipMs: median(askToShip(shippedHere)) }}- const today = Math.floor(Math.min(now, week + WEEK_MS - 1) / DAY_MS)+ const today = Math.floor(Math.min(now, current.end - 1) / DAY_MS)const scored = players.map(p => ({ personId: p.id, email: p.email, displayName: names?.get(p.id)?.trim() || p.email.split('@')[0]!,- ...score(p.id, week), prevWeekPoints: score(p.id, week - WEEK_MS).points,+ ...score(p.id, current), prevWeekPoints: previous && score(p.id, previous).points,streakDays: streak(new Set((landedBy.get(p.id) ?? []).map(g => Math.floor(g.ledger!.shippedAt! / DAY_MS))), today) })).sort((a, b) => b.points - a.points || a.email.localeCompare(b.email))const people: PersonScore[] = scored.map(({ email: _email, details, ...entry }) => {const rank = 1 + scored.filter(other => other.points > entry.points).lengthreturn { ...entry, rank, medal: entry.points > 0 ? MEDALS[rank - 1] ?? null : null, details }})+ const shippedNow = shippedRequests.filter(g => within(g.ledger!.shippedAt!, current))return {projectId, week,- goal: { openRequests: requests.filter(open).length, thisWeek: goal(week), lastWeek: goal(week - WEEK_MS) },+ ...period ? { period: { name: period, start: current.start, end: now } } : {},+ ...allProjects ? { allProjects: true as const } : {},+ goal: { openRequests: requests.filter(open).length, thisWeek: goal(current), lastWeek: previous && goal(previous) },people,waiting: waitingNow(state, shared),- models: { thisWeek: modelShare(requests, week), lastWeek: modelShare(requests, week - WEEK_MS) },- agents: agentScores(state, projectId, shippedRequests.filter(g => inWeek(g.ledger!.shippedAt!)), visibleMachines),- byModel: modelScores(requests, shippedRequests.filter(g => inWeek(g.ledger!.shippedAt!)), inWeek),- recentModels: recentModels(requests, now),+ models: { thisWeek: modelShare(requests, current), lastWeek: previous && modelShare(requests, previous) },+ agents: agentScores(state, projectIds, shippedNow, visibleMachines),+ byModel: modelScores(requests, shippedNow, current),+ recentModels: recentModels(requests.filter(g => (g.projectId ?? 'lead') === projectId), now),}}@@ -126,15 +142,15 @@ function recentModels(requests: Conversation[], now: number): RecentModel[] {* Buddy by the groups opened from its proposals. One credited this week stays listed after it was removed or replaced,* as "Former PM" or "Former Buddy" once the Swarm no longer has it (full review of #2097). Builders and Reviewers are* counted by model instead (modelScores). */-function agentScores(state: SuperTabState, projectId: string, shippedThisWeek: Conversation[], visibleMachines: readonly ContributedMachine[]): AgentScore[] {- const project = projectOf(state, projectId)- // A person's one Buddy belongs to no project (Dee, 10-31): it is listed in each project its person reads, and in none else,+function agentScores(state: SuperTabState, projectIds: ReadonlySet<string>, shippedThisWeek: Conversation[], visibleMachines: readonly ContributedMachine[]): AgentScore[] {+ const projects = [...projectIds].map(id => projectOf(state, id))+ // A person's one Buddy belongs to no project (Dee, 10-31): it is listed for each project summed that its person reads, and in none else,// so a private project never shows a Buddy, name or Mac of someone outside it. Its sessions are never rows of their own.const listedHere = (a: Agent): boolean => {if (!isBuddy(a) || a.buddySession) return false- if (!isSwarmBuddy(a)) return agentProjectId(state, a) === projectId+ if (!isSwarmBuddy(a)) return projectIds.has(agentProjectId(state, a) ?? '')const owner = state.people.find(p => p.id === a.buddyOf!.personId && p.generation === a.buddyOf!.generation)- return !!owner && canReadProject(state, { kind: 'person', userId: owner.id, email: owner.email }, project)+ return !!owner && projects.some(project => canReadProject(state, { kind: 'person', userId: owner.id, email: owner.email }, project))}// A proposal recorded before the credit moved to the one Buddy names its session: the person's one Buddy earns it.const creditee = (agentId: string): string => {@@ -143,10 +159,11 @@ function agentScores(state: SuperTabState, projectId: string, shippedThisWeek: Creturn state.agents.find(m => isSwarmBuddy(m) && !m.buddySession && listedHere(m)&& m.buddyOf!.personId === a.buddyOf!.personId && m.buddyOf!.generation === a.buddyOf!.generation)?.id ?? agentId}- const pmId = state.conversations.find(c => c.id === projectOf(state, projectId).leadConversationId)?.leadId+ const leads = new Set(projects.map(project => project.leadConversationId))+ const pmIds = new Set(state.conversations.filter(c => leads.has(c.id)).map(c => c.leadId))const shipped = new Map<string, { kind: 'pm' | 'buddy'; count: number }>()for (const a of state.agents) {- if (a.id === pmId || listedHere(a)) shipped.set(a.id, { kind: isBuddy(a) ? 'buddy' : 'pm', count: 0 })+ if (pmIds.has(a.id) || listedHere(a)) shipped.set(a.id, { kind: isBuddy(a) ? 'buddy' : 'pm', count: 0 })}const credit = (agentId: string, kind: 'pm' | 'buddy') => {const entry = shipped.get(agentId) ?? { kind, count: 0 }@@ -162,7 +179,7 @@ function agentScores(state: SuperTabState, projectId: string, shippedThisWeek: Cconst scored = [...shipped].map(([agentId, { kind, count }]) => {// Who it is now only while it is this project's: an agent id stays the same when its terminal is added again// elsewhere, and a private project's names and owners are not this board's to show (review of #2128).- const a = state.agents.find(agent => agent.id === agentId && (listedHere(agent) || (!isBuddy(agent) && agentProjectId(state, agent) === projectId)))+ const a = state.agents.find(agent => agent.id === agentId && (listedHere(agent) || (!isBuddy(agent) && projectIds.has(agentProjectId(state, agent) ?? ''))))// Its Mac only to a reader who sees that Mac: the one Buddy's is its person's, not the project's.const machineId = a && (!isSwarmBuddy(a) || visibleMachines.some(m => m.machineId === a.machineId)) ? a.machineId : ''return { agentId, displayName: a ? a.displayName ?? a.name : kind === 'pm' ? 'Former PM' : 'Former Buddy', kind,@@ -173,7 +190,7 @@ function agentScores(state: SuperTabState, projectId: string, shippedThisWeek: C/** Every model that worked this week: its attempts, the requests they shipped, their first reviews, and the review* verdicts it gave. A request ships on its last attempt before it shipped. */-function modelScores(requests: Conversation[], shippedThisWeek: Conversation[], inWeek: (at: number) => boolean): ModelScore[] {+function modelScores(requests: Conversation[], shippedThisWeek: Conversation[], span: Span): ModelScore[] {const rows = new Map<string, ModelScore & { attemptMs: number[]; requestMs: number[] }>()const row = (on: RanOn) => {const key = JSON.stringify([on.engine, on.model, on.effort ?? null])@@ -197,14 +214,14 @@ function modelScores(requests: Conversation[], shippedThisWeek: Conversation[],}for (const group of requests) {for (const run of group.ledger?.runs ?? []) {- if (!inWeek(run.at)) continue+ if (!within(run.at, span)) continueconst entry = row(run)entry.attempts++if (run.firstReview === undefined) continueentry.firstReview.reviewed++if (run.firstReview) entry.firstReview.passed++}- for (const counted of group.ledger?.reviews ?? []) if (inWeek(counted.week)) row(counted).reviews += counted.count+ for (const counted of reviewsIn(group.ledger ?? {}, span)) row(counted).reviews += counted.count}const scored = [...rows.values()].map(({ attemptMs, requestMs, ...entry }) => ({ ...entry,points: entry.shipped.count * SHIPPED_POINTS + entry.reviews * REVIEW_POINTS,@@ -218,9 +235,9 @@ const unblockPoints = (unblock: Unblock): number =>UNBLOCK_POINTS + Math.min(UNBLOCK_MAX_WAIT_POINTS, Math.floor(unblock.waitedMs / (UNBLOCK_HOURS_PER_POINT * HOUR_MS)))const newest = <T>(items: T[], at: (item: T) => number): T[] => [...items].sort((a, b) => at(b) - at(a)).slice(0, DETAILS_LIMIT)-/** The attempts started in the week starting [start], by the kind of model they ran on. */-function modelShare(requests: Conversation[], start: number): ModelShare {- const runs = requests.flatMap(g => g.ledger?.runs ?? []).filter(r => r.at >= start && r.at < start + WEEK_MS)+/** The attempts started in [span], by the kind of model they ran on. */+function modelShare(requests: Conversation[], span: Span): ModelShare {+ const runs = requests.flatMap(g => g.ledger?.runs ?? []).filter(r => within(r.at, span))const reviewed = runs.filter(r => r.firstReview !== undefined)const count = (list: typeof runs, grid: boolean) => list.filter(r => !!r.grid === grid).lengthconst passed = reviewed.filter(r => r.firstReview)diff --git a/backend/src/superTabs/machineReports.ts b/backend/src/superTabs/machineReports.tsindex 3c4502922..b28d8d45c 100644--- a/backend/src/superTabs/machineReports.ts+++ b/backend/src/superTabs/machineReports.ts@@ -20,6 +20,8 @@ export interface ReportRecord {stamp: number/** This machine's agents Lent counts for the next report (leaderboard/lent.ts lentAgents). */lentCount: number+ /** The same agents by the project of their task (lentProjects); absent from a record of an older server. */+ lentProjects?: Record<string, number>/** Whether any machine of the Swarm was being removed (machines.ts expireRemovals). */removals: boolean/** The earliest a worker here may lose its task to time (liveness.ts nextLossAt), at most DEADLINE_CAP_MS on. */@@ -49,7 +51,7 @@ export interface ReportRedis {set(key: string, value: string, px: 'PX', ms: number, nx: 'NX'): Promise<string | null>}-const record = z.object({ stamp: z.number().finite(), lentCount: z.number().int().nonnegative(), removals: z.boolean(), deadline: z.number().finite(),+const record = z.object({ stamp: z.number().finite(), lentCount: z.number().int().nonnegative(), lentProjects: z.record(z.string(), z.number().int().nonnegative()).optional(), removals: z.boolean(), deadline: z.number().finite(),team: z.boolean(), members: z.array(z.string()), preparable: z.array(z.string()), at: z.number().finite() })function parse(value: string | null): ReportRecord | undefined {diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.tsindex 440b009e3..972cd3dc0 100644--- a/backend/src/superTabs/machines.ts+++ b/backend/src/superTabs/machines.ts@@ -45,6 +45,8 @@ export interface ContributedMachine {buddyOnly?: true/** Agent-time Swarm agents here spent on other people's tasks, by leaderboard week, kept by its readings (leaderboard/lent.ts). */lent?: import('./leaderboard/lent.js').LentWeek[]+ /** The same by day, for the board's rolling periods. Only the leaderboard read gets it (model.ts visibleState). */+ lentDays?: import('./leaderboard/lent.js').LentDay[]/** Per engine, its failed starts here in a row, until one runs or they suspend it (engineHealth.ts). */engineFailures?: Record<string, number>/** Per engine, a suspension after failed starts: when, and whether its reading already said signed in with quota then. */diff --git a/backend/src/superTabs/mentions.ts b/backend/src/superTabs/mentions.tsindex 567076940..d9cce251c 100644--- a/backend/src/superTabs/mentions.ts+++ b/backend/src/superTabs/mentions.ts@@ -197,8 +197,8 @@ export async function markDone(tx: Tx, tabId: string, id: string, personId: stri}/** A person's unexpired tags in a Swarm, waiting or answered, newest first: the rows [readable] lists and counts. */-const tagRows = (tabId: string, personId: string, now: number, open: boolean) => ({- where: { tabId, personId, createdAt: { gt: new Date(now - MENTION_EXPIRY_MS) }, ...(open ? waiting : { resolvedAt: { not: null } }) },+const tagRows = (tabId: string, personId: string, now: number, open: boolean | null) => ({+ where: { tabId, personId, createdAt: { gt: new Date(now - MENTION_EXPIRY_MS) }, ...(open === null ? {} : open ? waiting : { resolvedAt: { not: null } }) },orderBy: { createdAt: 'desc' as const }, take: 500,})@@ -213,7 +213,7 @@ export async function waitingTagConversations(tx: Tx, tabId: string, personId: s* counts this same list. Ordinary loads leave quiet (dormant) conversations out of the state, so the ones a tag is in are* read here: the count and the list check the same conversations whichever state they get.* ponytail: capped at 500 per state; page it if a person ever gets more in 30 days. */-async function readable(tx: Tx, tabId: string, state: SuperTabState, actor: Extract<Actor, { kind: 'person' }>, now: number, open: boolean) {+async function readable(tx: Tx, tabId: string, state: SuperTabState, actor: Extract<Actor, { kind: 'person' }>, now: number, open: boolean | null) {person(state, actor.userId)const rows = await tx.superTabMention.findMany(tagRows(tabId, actor.userId, now, open))const groups = new Map(state.conversations.map(c => [c.id, c]))@@ -272,6 +272,40 @@ export async function listMentions(tx: Tx, tabId: string, state: SuperTabState,})}+/** A thread a person's own tag is in: the tagged message's thread (a reply's root, or a root itself), in the tag's conversation. */+export interface TaggedThread { conversationId: string; threadId: string; at: number }++/** The threads the person's own unexpired tags are in, waiting or answered, newest tag first, once each, at most `limit` of those+ * `keep` accepts (the caller's own filters apply before the count, so threads it drops never use up the limit) (the+ * Threads list, read/followedThreads.ts: a tag in a chat they never opened has no thread mark, so no other read finds it). Only+ * tags [readable] lists: conversations they can read, never a held Lead notice before its time. A message is taken only in the+ * conversation its tag names, and only its thread id leaves here, so a tag never names a thread of another chat. Its root+ * and replies are read and checked by the caller. The tags by one indexed read of at most 500 rows (tagRows), their messages by id+ * in one more. */+export async function taggedThreads(tx: Tx, tabId: string, state: SuperTabState, actor: Extract<Actor, { kind: 'person' }>, now: number,+ limit: number, keep: (thread: TaggedThread) => boolean = () => true): Promise<TaggedThread[]> {+ const tagged = await readable(tx, tabId, state, actor, now, null)+ if (!tagged.length) return []+ const found = await readBy(tx, 'SuperTabMessage', 'id', [{ $match: { _id: { $in: [...new Set(tagged.map(t => t.row.messageId))] }, tabId } },+ { $project: { conversationId: 1, thread: 1 } }])+ const messages = new Map(found.map(r => [r._id as string, r]))+ const seen = new Set<string>()+ const threads: TaggedThread[] = []+ for (const { row } of tagged) {+ const message = messages.get(row.messageId)+ const threadId = typeof message?.thread === 'string' ? message.thread : null+ if (!threadId || message!.conversationId !== row.conversationId) continue+ const key = `${row.conversationId}\u0000${threadId}`+ if (seen.has(key)) continue+ seen.add(key)+ const thread = { conversationId: row.conversationId, threadId, at: row.createdAt.getTime() }+ if (!keep(thread)) continue+ threads.push(thread)+ if (threads.length >= limit) break+ }+ return threads+}+/** For each tagged message that is a thread reply only (not also sent to the chat), its thread's root: the tag belongs to the* thread, not the chat's main stream (Desktop counts it on Threads, as Slack does). Only a root the person may read, in the* tag's own conversation, roots its own thread: an agent-only or delivered-copy root reads as none, so the tag counts as thediff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex 2af83a20b..6222de7c5 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -755,6 +755,8 @@ export function visibleState(state: SuperTabState, actor: Actor, now = Date.now(// A Buddy-only machine is no machine of the Swarm to anyone, its own person included (machines.ts buddyOnly): their Buddy// shows as a Buddy, and their machine stays theirs. Machines, status and the leaderboard's lent hours all read this.if (visible.machines) visible.machines = visible.machines.filter(m => !m.buddyOnly)+ // Rows by day and project that only the leaderboard read uses, and it takes them from the Swarm itself.+ for (const pool of visible.machines ?? []) delete pool.lentDays// Nor its id, which a Buddy's row carries (machineHiddenFrom).visible.agents = visible.agents.map(a => machineHiddenFrom(state, actor, a) ? agentWithoutMachine(a) : a)// The removed Leads conversation reaches nobody (leadsRemoved), its id included.diff --git a/backend/src/superTabs/parts/commit.test.ts b/backend/src/superTabs/parts/commit.test.tsindex adf584518..d3d94c7de 100644--- a/backend/src/superTabs/parts/commit.test.ts+++ b/backend/src/superTabs/parts/commit.test.ts@@ -52,6 +52,9 @@ describe('what a write tells host reads (review round 1)', () => {}expect(hostMarker('machine', machine({}, reading(1)), lent(15_000, reading(2)), none, 9)).toEqual({})expect(hostMarker('machine', lent(15_000), lent(30_000), none, 9)).toEqual({})+ // The daily rows move with every reading too.+ const days = (busyMs: number) => { const part = machine(); return { ...part, contribution: { ...part.contribution, lentDays: [{ day: 0, busyMs }] } } }+ expect(hostMarker('machine', days(1), days(2), none, 9)).toEqual({})})it('moves it for a change to the machine\'s settings or ledger, and when the part is added or removed', () => {diff --git a/backend/src/superTabs/parts/commit.ts b/backend/src/superTabs/parts/commit.tsindex 3b38c5082..dd534808d 100644--- a/backend/src/superTabs/parts/commit.ts+++ b/backend/src/superTabs/parts/commit.ts@@ -132,7 +132,7 @@ export function capReleased(state: SuperTabState): void {* that machine's host needs to hear about. */const withoutReading = (data: unknown) => {const machine = data as MachineData | undefined- return machine && { ...machine, contribution: machine.contribution && { ...machine.contribution, observation: undefined, lent: undefined } }+ return machine && { ...machine, contribution: machine.contribution && { ...machine.contribution, observation: undefined, lent: undefined, lentDays: undefined } }}/**diff --git a/backend/src/superTabs/parts/indexed.ts b/backend/src/superTabs/parts/indexed.tsindex 8f2b2d2d6..fa4b284ef 100644--- a/backend/src/superTabs/parts/indexed.ts+++ b/backend/src/superTabs/parts/indexed.ts@@ -184,7 +184,7 @@ export const groupsBy = (tx: Transaction, index: GroupIndex, pipeline: Prisma.In/** A project's quiet conversations last active since `since`, as the project index serves them. A conversation stored with no* project belongs to the first one (projects.ts groupProject); a null match is a missing field too. */-export function quietSince(tabId: string, projectId: string, since: number): Record<string, Prisma.InputJsonValue> {+export function quietSince(tabId: string, projectId: string | string[], since: number): Record<string, Prisma.InputJsonValue> {return { tabId, deleted: false, dormant: true, lastActivityAt: { $gte: { $date: new Date(since).toISOString() } },- projectId: { $in: projectId === 'lead' ? ['lead', null] : [projectId] } }+ projectId: { $in: [projectId].flat().flatMap(id => id === 'lead' ? ['lead', null] : [id]) } }}diff --git a/backend/src/superTabs/read/followedThreads.ts b/backend/src/superTabs/read/followedThreads.tsindex 0a0c2125a..b9e6d3fdf 100644--- a/backend/src/superTabs/read/followedThreads.ts+++ b/backend/src/superTabs/read/followedThreads.ts@@ -5,7 +5,11 @@** A read thread is listed only from the person's thread mark rows (a thread they opened on some device, or followed), in chats* they read now (the inbox's chats: active, unarchived, the messages read's check), most recently moved first, at most- * READ_CANDIDATES. One is listed when they follow it, or started it, replied in it or were tagged in it (root or reply), and it+ * READ_CANDIDATES; and from their own tags (mentions.ts taggedThreads), at most TAGGED_THREADS more, newest tag first: a thread+ * they are tagged in has no mark in a chat they never opened (the inbox counts that chat as read, so it lists none of its+ * threads), and the Threads view promises tagged threads. A thread with a mark row of theirs, an unfollowed one too, is judged by+ * the row alone; a tag only adds the threads they hold none of. The tag list is theirs alone and checked as the Activity list is+ * (chats they read now); the thread's root and replies are checked below as for any candidate. One is listed when they follow it, or started it, replied in it or were tagged in it (root or reply), and it* has a reply. Rows are those a page shows a person (inbox.ts readable): never an agent-only notice or a delivered copy.** Cost: the inbox's reads (without the chats' latest messages); the candidates' roots by id in one read; each candidate thread's@@ -20,6 +24,8 @@ import type { ThreadReply } from '../pageReads.js'import { threadSummaries } from '../threads.js'import { readBy } from '../parts/indexed.js'import type { SuperTabStore } from '../store.js'+import { taggedThreads } from '../mentions.js'+import type { ThreadMarkRow } from '../readMarks.js'import { FIELDS, inboxRead, INBOX_READS, INBOX_WINDOW_MS, isReply, MEMBER_SCAN, newestFirst, perRange, preview, readable, row, SCAN_FIELDS, threadKey,type InboxMessage, type InboxThread, type Row } from './inbox.js'@@ -27,6 +33,8 @@ import { FIELDS, inboxRead, INBOX_READS, INBOX_WINDOW_MS, isReply, MEMBER_SCAN,export const MAX_READ_THREADS = 30/** Thread mark rows checked for read threads, most recently moved first: room for those the person turns out not to be in. */export const READ_CANDIDATES = 2 * MAX_READ_THREADS+/** Threads found only by the person's tags that are checked as candidates, newest tag first, besides READ_CANDIDATES. */+export const TAGGED_THREADS = 30/** Rows read per candidate thread, newest first. */export const THREAD_SCAN = MEMBER_SCANexport const THREADS_READS = INBOX_READS@@ -55,8 +63,14 @@ export async function readFollowedThreads(store: SuperTabStore, user: AuthUser,const listed = new Set(unread.map(t => threadKey(t.conversationId, t.rootId)))const groups = new Map(chats.map(g => [g.id, g]))const eligible = threadRows.filter(r => r.follow !== false && groups.has(r.conversationId) && !listed.has(threadKey(r.conversationId, r.threadId)))- const candidates = eligible.slice(0, READ_CANDIDATES)- let more = inbox.more || eligible.length > READ_CANDIDATES+ // Threads they are tagged in and hold no mark row of: the inbox lists none in a chat they never opened.+ const held = new Set(threadRows.map(r => threadKey(r.conversationId, r.threadId)))+ // The filters run before the count, so tags in archived chats or in threads they hold a mark of never use up the cap.+ const tagged = await taggedThreads(db, tabId, state, { kind: 'person', userId: personId, email: user.email }, Date.now(), TAGGED_THREADS + 1,+ t => groups.has(t.conversationId) && !held.has(threadKey(t.conversationId, t.threadId)) && !listed.has(threadKey(t.conversationId, t.threadId)))+ const byTag: ThreadMarkRow[] = tagged.slice(0, TAGGED_THREADS).map(t => ({ conversationId: t.conversationId, threadId: t.threadId, sequence: 0, follow: null, updatedAt: t.at }))+ const candidates = [...eligible.slice(0, READ_CANDIDATES), ...byTag]+ let more = inbox.more || eligible.length > READ_CANDIDATES || tagged.length > TAGGED_THREADSif (!candidates.length) return { unread, read: [], more }// Every root by its id, in one read; a root counts only in the chat its mark names, and only one the person reads.const found = (await readBy(db, 'SuperTabMessage', 'id', [{ $match: { _id: { $in: candidates.map(c => c.threadId) }, tabId } },diff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.tsindex 2b7a79e6d..e47ae049d 100644--- a/backend/src/superTabs/read/service.ts+++ b/backend/src/superTabs/read/service.ts@@ -20,12 +20,13 @@ import { readChanged, readLastChangedAt, readLastChangedAts, readLight, readLighimport { migrateSwarm } from '../migration/migrate.js'import * as parts from '../parts/index.js'import type { GroupData, Part, SwarmParts } from '../parts/index.js'-import { canReadGroup, readConversation, readProject } from '../projects.js'+import { canReadGroup, canReadProject, projectsOf, readConversation, readProject } from '../projects.js'import { isBuddyReader } from '../buddies.js'import { workspacesRequired } from '../workspaceStore.js'import type { Leaderboard } from '../leaderboard/contract.js'import { profileNames, readableWeek, recentDormantGroups } from '../leaderboard/read.js'import { LEDGER_WEEKS } from '../leaderboard/record.js'+import type { PeriodName } from '../leaderboard/rolling.js'import { leaderboard } from '../leaderboard/stats.js'import { WEEK_MS } from '../leaderboard/week.js'import { READ_FORMAT, SWARM_MIGRATING, type Changes, type Derived, type DormantGroups, type FirstLoad, type OneGroup, type SwarmList } from './contract.js'@@ -320,17 +321,22 @@ export class SwarmReads {/** One project's leaderboard for a week (leaderboard/stats.ts), for the people who read the project. It sums only the* groups the reader may read, dormant ones of the kept weeks included, and never a private conversation. */- async leaderboard(user: AuthUser, tabId: string, projectId: string, week?: number): Promise<Leaderboard> {+ async leaderboard(user: AuthUser, tabId: string, projectId: string, week?: number, period?: PeriodName, allProjects = false): Promise<Leaderboard> {if (isTeamSession(user)) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)const now = this.now(), start = readableWeek(week, now)return this.read(user, tabId, async (tx, cached) => {const state = parts.reassemble(await readParts(tx, cached, tabId), { share: true })const actor = await this.store.actor(tx, user, state)readProject(state, actor, projectId)- const dormant = await recentDormantGroups(tx, tabId, projectId, now - LEDGER_WEEKS * WEEK_MS)+ // Every project this reader reads, by the same check as the one asked for; what they may not read is never loaded.+ const readable = allProjects ? projectsOf(state).filter(p => canReadProject(state, actor, p)).map(p => p.id) : undefined+ const dormant = await recentDormantGroups(tx, tabId, readable ?? projectId, now - LEDGER_WEEKS * WEEK_MS)const groups = [...state.conversations.filter(g => !g.dormant), ...dormant].filter(g => !isLeads(g) && canReadGroup(state, actor, g))const names = await profileNames(tx, state.people.map(p => p.id))- return leaderboard({ state, groups, machines: visibleState(state, actor, now).machines ?? [], projectId, week: start, now, names })+ // Which machines the reader sees, with the daily rows no other read carries.+ const machines = (visibleState(state, actor, now).machines ?? [])+ .map(m => ({ ...m, lentDays: state.machines?.find(own => own.machineId === m.machineId)?.lentDays }))+ return leaderboard({ state, groups, machines, projectId, week: start, now, period, allProjects: readable, names })})}diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 1844bebfd..bca545c19 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -65,7 +65,7 @@ import { QUIET_CLAIM, type HoldReason } from './holdReason.js'import { stuck } from './deliverySettle.js'import { agentDisplayName } from './agentNames.js'import { endedHolds, HOLDING, startedHolds, type WorkHold } from '../github/holds.js'-import { accrueLent, addLent, lentAgents } from './leaderboard/lent.js'+import { accrueLent, addLent, lentAgents, lentProjects } from './leaderboard/lent.js'import { mayDrive, TERMINAL_ANSWER_MS, TERMINAL_EXPIRY_MS, TERMINAL_PICKUP_MS, TERMINAL_RECHECK_MS, type TerminalEffect } from './terminal.js'import { costRows, failedStarts, summarizeCosts } from './costs/read.js'import { APPROVE, approvedLine, localDate, MAX_PROPOSALS, proposalQuestion, proposalTitle, REASK_DAYS, reflectionMessageId, routingReflection, type Proposal, type ReflectionInput } from './costs/reflection.js'@@ -2805,7 +2805,7 @@ export class SuperTabStore {const data = structuredClone(part.data), mine = data.contribution!const reading = storedObservation(mine, observation, { team: isTeamSession(user), now, preparable: id => record.preparable.includes(id) })if (!readingOnly(mine.observation, reading)) return null- addLent(mine, now, record.lentCount)+ addLent(mine, now, record.lentCount, record.lentProjects)mine.observation = readingconst suspended = JSON.stringify(mine.engineSuspensions)readingClearsSuspensions(mine, now)@@ -2891,6 +2891,7 @@ export class SuperTabStore {// What the next reports of this machine need to skip the load, as this commit leaves the Swarm.const mine = state.machines?.find(m => m.machineId === machineId)return { ...written, ...mine ? { record: { lentCount: lentAgents(state, mine, mine.observation?.runningHarnessIds ?? []),+ lentProjects: lentProjects(state, mine, mine.observation?.runningHarnessIds ?? []),removals: !!state.machines?.some(m => m.removal), deadline: Math.min(nextLossAt(state, machineId) ?? Infinity, now + DEADLINE_CAP_MS),team: teamByRecord(state, machineId), members: state.people.map(p => p.id),preparable: (state.starts ?? []).filter(s => preparableStart(s, machineId)).map(s => s.id), at: now } } : {} }diff --git a/cli/src/lib/buddyGuard.spec.ts b/cli/src/lib/buddyGuard.spec.tsindex 4a4318273..63847a8dc 100644--- a/cli/src/lib/buddyGuard.spec.ts+++ b/cli/src/lib/buddyGuard.spec.ts@@ -6,6 +6,7 @@ import { tmpdir } from 'node:os'import { inspect } from 'node:util'import { basename, dirname, join } from 'node:path'import { afterAll, beforeEach, describe, expect, it } from 'vitest'+import { BUDDY_COPIES_FILE } from '../superTabs/buddyHome.js'import { allowBuddyReads, artifactLinks, buddyGuardCommand, buddyGuardSource, buddyReadsOf, forgetBuddyReads, grantBuddyWide, recordBuddyApprovals,SentListsError } from './buddyGuard.js'@@ -380,6 +381,10 @@ describe('a Buddy\'s guard (Ken, 10-29: reads without a prompt, refuses everythiconst working = spawnSync('/bin/sh', ['-c', buddyGuardCommand(process.execPath, script)],{ input: JSON.stringify({ tool_name: 'Read', tool_input: { file_path: join(root, 'a.txt') } }), encoding: 'utf8' })expect([working.status, JSON.parse(working.stdout).hookSpecificOutput.permissionDecision]).toEqual([0, 'allow'])+ // What its prompt tells a person's one Buddy to read about its project copies (superTabs/buddyHome.ts): a name the guard allows.+ const copies = spawnSync('/bin/sh', ['-c', buddyGuardCommand(process.execPath, script)],+ { input: JSON.stringify({ tool_name: 'Read', tool_input: { file_path: join(root, BUDDY_COPIES_FILE) } }), encoding: 'utf8' })+ expect(JSON.parse(copies.stdout).hookSpecificOutput.permissionDecision).toBe('allow')})})diff --git a/cli/src/lib/gitProject.ts b/cli/src/lib/gitProject.tsindex 75cc90df2..549010a20 100644--- a/cli/src/lib/gitProject.ts+++ b/cli/src/lib/gitProject.ts@@ -32,7 +32,7 @@ async function git(path: string, args: string[], timeout = 4000, base: NodeJS.Prenv: gitEnv(base),})).stdout.replace(/\r?\n$/, '')}-function gitEnv(base: NodeJS.ProcessEnv): NodeJS.ProcessEnv {+export function gitEnv(base: NodeJS.ProcessEnv): NodeJS.ProcessEnv {const env = { ...base, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'Never', GIT_OPTIONAL_LOCKS: '0' }for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_NAMESPACE', 'GIT_PREFIX']) delete (env as NodeJS.ProcessEnv)[key]return env@@ -203,7 +203,7 @@ export async function readGitProject(requested: string, options: { refresh?: boo}/** `refs/remotes/origin/fix/typo` → origin, fix/typo, and a refspec updating exactly that ref. */-function remoteBranch(ref: string | undefined): { remote: string; branch: string; refspec: string } | null {+export function remoteBranch(ref: string | undefined): { remote: string; branch: string; refspec: string } | null {const match = /^refs\/remotes\/([A-Za-z0-9._][A-Za-z0-9._-]*)\/([A-Za-z0-9._]\S*)$/.exec(ref ?? '')if (!match || match[2] === 'HEAD') return nullreturn { remote: match[1]!, branch: match[2]!, refspec: `+refs/heads/${match[2]}:refs/remotes/${match[1]}/${match[2]}` }@@ -211,7 +211,7 @@ function remoteBranch(ref: string | undefined): { remote: string; branch: string/** The remote's default branch as the ref a clone keeps it in: `origin/HEAD`, else `origin/main` or* `origin/master`, as `readGitProject` offers it. Null when the repository has no such ref. */-async function originDefaultRef(path: string): Promise<string | null> {+export async function originDefaultRef(path: string): Promise<string | null> {const head = await git(path, ['symbolic-ref', '--quiet', 'refs/remotes/origin/HEAD']).catch(() => null)for (const ref of [head, 'refs/remotes/origin/main', 'refs/remotes/origin/master']) {if (ref && await git(path, ['show-ref', '--verify', '--quiet', '--', ref]).then(() => true, () => false)) return refdiff --git a/cli/src/superTabs/buddyHome.spec.ts b/cli/src/superTabs/buddyHome.spec.tsindex 1c94f5ae2..5d0ae9fac 100644--- a/cli/src/superTabs/buddyHome.spec.ts+++ b/cli/src/superTabs/buddyHome.spec.ts@@ -1,9 +1,9 @@import { execFileSync } from 'node:child_process'-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'-import { afterEach, describe, expect, it } from 'vitest'-import { buddyProjectsOf, folderName, prepareBuddyHome, pruneBuddyHome, removeBuddyHome, trustBuddyHome } from './buddyHome.js'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { BUDDY_COPIES_FILE, buddyProjectsOf, folderName, prepareBuddyHome, pruneBuddyHome, buddyHomeDue, refreshBuddyHome, removeBuddyHome, trustBuddyHome } from './buddyHome.js'// A person's one Buddy's folder (spec 2026-10-31-one-buddy-per-swarm, Folder): one worktree per project checkout on the// machine, each from its own checkout, and a lost project's out before the next turn. Real git, in a throwaway folder.@@ -158,3 +158,269 @@ describe('a person\'s one Buddy\'s folder', () => {.toEqual([{ id: 'a', name: 'A', cwd: '/x' }])})})++// Scholes, 11-02: the Buddy kept saying a merged button was "not in my copy of the code yet". Real git: a bare origin, the+// person's clone of it, and new commits pushed from another clone.+// Each test here runs dozens of real git commands: a busy machine takes more than the default 5 s (seen with a hook added).+describe('a Buddy\'s copy of a project follows its default branch', { timeout: 30_000 }, () => {+ const commit = (dir: string, file: string, text: string) => {+ writeFileSync(join(dir, file), text)+ git(dir, 'add', file)+ git(dir, '-c', '[email protected]', '-c', 'user.name=t', 'commit', '-q', '-m', file)+ }+ /** origin, the person's clone, and a teammate's clone that pushes. */+ function project(r: string) {+ const first = checkout(r, 'first'), origin = join(r, 'origin.git')+ git(r, 'clone', '-q', '--bare', first, origin)+ const clone = join(r, 'clone'), teammate = join(r, 'teammate')+ git(r, 'clone', '-q', origin, clone)+ git(r, 'clone', '-q', origin, teammate)+ return { origin, clone, teammate, home: join(r, 'home'), web: [{ id: 'web', name: 'Web', cwd: clone }] }+ }+ const advance = (teammate: string, file = 'NEW', text = 'new\n') => { commit(teammate, file, text); git(teammate, 'push', '-q', 'origin', 'main') }+ const head = (dir: string) => git(dir, 'rev-parse', 'HEAD').trim()+ const copy = (home: string) => join(home, 'projects', 'Web')+ const copies = (home: string) => readFileSync(join(home, BUDDY_COPIES_FILE), 'utf8')++ it('moves a Buddy home made at an old commit to the new origin head on the next prepare, and says where it is', async () => {+ const p = project(root())+ await prepareBuddyHome(p.home, p.web)+ const old = head(copy(p.home))+ expect(copies(p.home)).toContain(`Web: at ${old.slice(0, 7)}`)+ advance(p.teammate)+ await prepareBuddyHome(p.home, p.web)+ expect(head(copy(p.home))).toBe(head(p.teammate))+ expect(readFileSync(join(copy(p.home), 'NEW'), 'utf8')).toBe('new\n')+ // Still detached, as a Buddy holds no branch.+ expect(() => git(copy(p.home), 'symbolic-ref', '--quiet', 'HEAD')).toThrow()+ expect(copies(p.home)).toContain(`Web: at ${head(p.teammate).slice(0, 7)}`)+ expect(copies(p.home)).toContain('latest default branch')+ })++ it('makes a new copy at the default branch too, not at wherever its person\'s checkout stands', async () => {+ const p = project(root())+ git(p.clone, 'checkout', '-q', '-b', 'my-private-work')+ commit(p.clone, 'PRIVATE', 'mine\n')+ await prepareBuddyHome(p.home, p.web)+ expect(existsSync(join(copy(p.home), 'PRIVATE'))).toBe(false)+ expect(head(copy(p.home))).toBe(head(p.teammate))+ })++ it('leaves the person\'s checkout as it is: HEAD, branches, working files, tags, FETCH_HEAD and hooks', async () => {+ const p = project(root())+ git(p.clone, 'checkout', '-q', '-b', 'my-work')+ commit(p.clone, 'MINE', 'mine\n')+ writeFileSync(join(p.clone, 'WHO'), 'uncommitted\n')+ writeFileSync(join(p.clone, 'UNTRACKED'), 'untracked\n')+ const marker = join(p.clone, 'HOOK_RAN')+ writeFileSync(join(p.clone, '.git', 'hooks', 'post-checkout'), `#!/bin/sh\ntouch ${marker}\n`, { mode: 0o755 })+ await prepareBuddyHome(p.home, p.web)+ rmSync(marker, { force: true })+ git(p.teammate, 'tag', 'v9')+ advance(p.teammate)+ git(p.teammate, 'push', '-q', 'origin', 'v9')+ git(p.teammate, 'push', '-q', 'origin', 'main:refs/heads/other')+ const before = { head: head(p.clone), status: git(p.clone, 'status', '--porcelain'), mine: git(p.clone, 'rev-parse', 'refs/heads/main'),+ branch: git(p.clone, 'symbolic-ref', 'HEAD'), config: readFileSync(join(p.clone, '.git', 'config'), 'utf8') }+ const fetchHead = join(p.clone, '.git', 'FETCH_HEAD'), fetched = existsSync(fetchHead) ? readFileSync(fetchHead, 'utf8') : null+ await refreshBuddyHome(p.home)+ expect(head(copy(p.home))).toBe(head(p.teammate))+ expect({ head: head(p.clone), status: git(p.clone, 'status', '--porcelain'), mine: git(p.clone, 'rev-parse', 'refs/heads/main'),+ branch: git(p.clone, 'symbolic-ref', 'HEAD'), config: readFileSync(join(p.clone, '.git', 'config'), 'utf8') }).toEqual(before)+ expect(readFileSync(join(p.clone, 'WHO'), 'utf8')).toBe('uncommitted\n')+ expect(existsSync(fetchHead) ? readFileSync(fetchHead, 'utf8') : null).toBe(fetched)+ expect(existsSync(marker)).toBe(false)+ // Only the one remote-tracking ref moved.+ expect(git(p.clone, 'tag')).toBe('')+ expect(git(p.clone, 'rev-parse', 'refs/remotes/origin/main').trim()).toBe(head(p.teammate))+ expect(() => git(p.clone, 'rev-parse', '--verify', '--quiet', 'refs/remotes/origin/other')).toThrow()+ })++ it.each([+ ['a changed file', (dir: string) => { chmodSync(join(dir, 'WHO'), 0o644); writeFileSync(join(dir, 'WHO'), 'changed\n') }],+ ['an untracked file', (dir: string) => writeFileSync(join(dir, 'SCRATCH'), 'x\n')],+ ])('leaves a copy with %s alone, and says it may be behind', async (_, dirty) => {+ const p = project(root())+ await prepareBuddyHome(p.home, p.web)+ const old = head(copy(p.home))+ dirty(copy(p.home))+ advance(p.teammate)+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ await refreshBuddyHome(p.home)+ expect(warn).toHaveBeenCalledTimes(1)+ warn.mockRestore()+ expect(head(copy(p.home))).toBe(old)+ expect(copies(p.home)).toContain('may be behind')+ })++ it('leaves a missing copy missing, and still moves the others', async () => {+ const r = root(), p = project(r), other = checkout(r, 'other-src')+ await prepareBuddyHome(p.home, [...p.web, { id: 'other', name: 'Other', cwd: other }])+ rmSync(copy(p.home), { recursive: true, force: true })+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ await refreshBuddyHome(p.home)+ warn.mockRestore()+ expect(existsSync(copy(p.home))).toBe(false)+ expect(copies(p.home)).toContain('Web: revision not known')+ expect(copies(p.home)).toContain('Other: at')+ expect(copies(p.home)).toContain('no remote default branch')+ })++ it('moves nothing above a copy that lost its .git: another repository around it is left alone', async () => {+ const r = root(), p = project(r), outer = checkout(r, 'outer')+ const home = join(outer, 'home')+ git(outer, 'remote', 'add', 'origin', p.origin)+ git(outer, 'fetch', '-q', 'origin')+ await prepareBuddyHome(home, p.web)+ rmSync(join(copy(home), '.git'))+ const before = head(outer)+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ await refreshBuddyHome(home)+ warn.mockRestore()+ expect(head(outer)).toBe(before)+ expect(copies(home)).toContain('Web: revision not known')+ })++ it('offline: keeps the old copy, says so, logs one line with no address, and tries no more that pass', async () => {+ const p = project(root())+ await prepareBuddyHome(p.home, p.web)+ const old = head(copy(p.home))+ git(p.clone, 'remote', 'set-url', 'origin', 'https://user:[email protected]:9/nothing.git')+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ await refreshBuddyHome(p.home)+ expect(warn).toHaveBeenCalledTimes(1)+ expect(String(warn.mock.calls[0])).not.toMatch(/s3cret|127\.0\.0\.1/)+ warn.mockRestore()+ expect(head(copy(p.home))).toBe(old)+ expect(copies(p.home)).toContain('may be behind')+ expect(copies(p.home)).not.toContain('s3cret')+ })++ it('locks again the files a move wrote, and never a link\'s target', async () => {+ const r = root(), p = project(r), target = join(r, 'outside')+ writeFileSync(target, 'x', { mode: 0o644 })+ await prepareBuddyHome(p.home, p.web)+ // As the launch's lock leaves it.+ chmodSync(join(copy(p.home), 'WHO'), 0o444)+ commit(p.teammate, 'WHO', 'changed\n')+ symlinkSync(target, join(p.teammate, 'LINK'))+ git(p.teammate, 'add', 'LINK')+ advance(p.teammate, 'RUN', 'new\n')+ chmodSync(join(p.teammate, 'RUN'), 0o755)+ git(p.teammate, 'add', 'RUN')+ git(p.teammate, '-c', '[email protected]', '-c', 'user.name=t', 'commit', '-q', '-m', 'run')+ git(p.teammate, 'push', '-q', 'origin', 'main')+ await refreshBuddyHome(p.home)+ expect(readFileSync(join(copy(p.home), 'WHO'), 'utf8')).toBe('changed\n')+ for (const file of ['WHO', 'RUN']) expect(statSync(join(copy(p.home), file)).mode & 0o222).toBe(0)+ expect(statSync(join(copy(p.home), 'RUN')).mode & 0o111).not.toBe(0)+ expect(statSync(target).mode & 0o222).not.toBe(0)+ // The lock reads as no change, or the next pass would leave it behind.+ expect(git(copy(p.home), 'status', '--porcelain')).toBe('')+ advance(p.teammate, 'LATER')+ await refreshBuddyHome(p.home)+ expect(head(copy(p.home))).toBe(head(p.teammate))+ })++ it('locks a file a move wrote whatever its name: a leading space, a line break, a folder (security review 2 of #2524)', async () => {+ const p = project(root()), names = [' leading.txt', 'trailing.txt ', 'line\nbreak.txt', 'plain.txt']+ await prepareBuddyHome(p.home, p.web)+ mkdirSync(join(p.teammate, ' folder'))+ for (const name of [...names, ' folder/ inner.txt']) writeFileSync(join(p.teammate, name), 'x\n')+ git(p.teammate, 'add', '-A')+ git(p.teammate, '-c', '[email protected]', '-c', 'user.name=t', 'commit', '-q', '-m', 'names')+ git(p.teammate, 'push', '-q', 'origin', 'main')+ await refreshBuddyHome(p.home)+ expect(head(copy(p.home))).toBe(head(p.teammate))+ for (const name of [...names, ' folder/ inner.txt']) expect([name, statSync(join(copy(p.home), name)).mode & 0o222]).toEqual([name, 0])+ })++ // macOS refuses such a name; CI's Linux takes it.+ it.skipIf(process.platform === 'darwin')('locks a file a move wrote whose name is not UTF-8 (security review 2 of #2524)', async () => {+ const p = project(root()), name = Buffer.from([0x66, 0xff, 0x2e, 0x74])+ await prepareBuddyHome(p.home, p.web)+ writeFileSync(Buffer.concat([Buffer.from(`${p.teammate}/`), name]), 'x\n')+ git(p.teammate, 'add', '-A')+ git(p.teammate, '-c', '[email protected]', '-c', 'user.name=t', 'commit', '-q', '-m', 'bytes')+ git(p.teammate, 'push', '-q', 'origin', 'main')+ await refreshBuddyHome(p.home)+ expect(head(copy(p.home))).toBe(head(p.teammate))+ expect(statSync(Buffer.concat([Buffer.from(`${copy(p.home)}/`), name])).mode & 0o222).toBe(0)+ })++ it('never locks a file outside through a folder a commit turned into a link (review of #2524)', async () => {+ const r = root(), p = project(r), outside = join(r, 'outside')+ mkdirSync(outside)+ writeFileSync(join(outside, 'b.txt'), 'theirs', { mode: 0o644 })+ mkdirSync(join(p.teammate, 'a'))+ commit(p.teammate, 'a/b.txt', 'in the folder\n')+ git(p.teammate, 'push', '-q', 'origin', 'main')+ await prepareBuddyHome(p.home, p.web)+ expect(existsSync(join(copy(p.home), 'a', 'b.txt'))).toBe(true)+ git(p.teammate, 'rm', '-q', '-r', 'a')+ symlinkSync(outside, join(p.teammate, 'a'))+ git(p.teammate, 'add', 'a')+ git(p.teammate, '-c', '[email protected]', '-c', 'user.name=t', 'commit', '-q', '-m', 'link')+ git(p.teammate, 'push', '-q', 'origin', 'main')+ await refreshBuddyHome(p.home)+ expect(head(copy(p.home))).toBe(head(p.teammate))+ expect(statSync(join(outside, 'b.txt')).mode & 0o222).not.toBe(0)+ })++ it('is due at most hourly, across restarts, by the age of its file; a clock moved back does not stop it for good', async () => {+ const p = project(root())+ await prepareBuddyHome(p.home, p.web)+ const file = join(p.home, BUDDY_COPIES_FILE), now = Date.now()+ expect(buddyHomeDue(p.home, now + 59 * 60_000)).toBe(false)+ expect(buddyHomeDue(p.home, now + 61 * 60_000)).toBe(true)+ const later = new Date(now + 3_600_000)+ utimesSync(file, later, later)+ expect(buddyHomeDue(p.home, now)).toBe(true)+ rmSync(file)+ expect(buddyHomeDue(p.home)).toBe(true)+ })++ it('a lost project: its name leaves the file, and a pass running then stops and writes nothing back', async () => {+ const r = root(), p = project(r), otherRoot = join(r, 'o')+ mkdirSync(otherRoot)+ const other = project(otherRoot)+ const both = [...p.web, { id: 'secret', name: 'Secret', cwd: other.clone }]+ await prepareBuddyHome(p.home, both)+ expect(copies(p.home)).toContain('Secret')+ advance(p.teammate)+ const pass = refreshBuddyHome(p.home)+ expect(await pruneBuddyHome(p.home, new Set(['web']))).toEqual(['Secret'])+ await pass+ expect(existsSync(join(p.home, BUDDY_COPIES_FILE))).toBe(false)+ expect(existsSync(join(p.home, 'projects', 'Secret'))).toBe(false)+ await refreshBuddyHome(p.home)+ expect(copies(p.home)).not.toContain('Secret')+ expect(copies(p.home)).toContain('Web: at')+ })++ it('a Buddy ending during a pass: the folder goes whole and nothing comes back', async () => {+ const p = project(root())+ await prepareBuddyHome(p.home, p.web)+ advance(p.teammate)+ let finished = false+ void refreshBuddyHome(p.home).then(() => { finished = true })+ await removeBuddyHome(p.home)+ // Nothing of the pass is left running to write in the folder after it is gone.+ expect(finished).toBe(true)+ expect(existsSync(p.home)).toBe(false)+ expect(git(p.clone, 'worktree', 'list').trim().split('\n')).toHaveLength(1)+ })++ it('joins a pass already running instead of starting a second, and never throws for a folder that is a link', async () => {+ const r = root(), p = project(r)+ await prepareBuddyHome(p.home, p.web)+ expect(refreshBuddyHome(p.home)).toBe(refreshBuddyHome(p.home))+ await refreshBuddyHome(p.home)+ const linked = join(r, 'linked')+ symlinkSync(p.home, linked)+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ await expect(refreshBuddyHome(linked)).resolves.toBeUndefined()+ expect(warn).toHaveBeenCalledTimes(1)+ warn.mockRestore()+ })+})diff --git a/cli/src/superTabs/buddyHome.ts b/cli/src/superTabs/buddyHome.tsindex 94e007b50..de0207f75 100644--- a/cli/src/superTabs/buddyHome.ts+++ b/cli/src/superTabs/buddyHome.ts@@ -2,17 +2,18 @@* A person's one Buddy's folder (docs/specs/2026-10-31-one-buddy-per-swarm.md, Folder; Dee, 10-31). The Buddy reads every* project its person reads, so its folder is no project's checkout: it holds `projects/<name>`, one detached worktree per* project whose checkout is already on this machine, each made from that project's own checkout, so no two projects' files- * ever mix. Nothing is fetched or cloned for it. Its guard confines its reads to this folder, and the lock its launch applies- * makes every file in it read-only (lib/swarmSkills.ts lockBuddyFolder). A project its person no longer reads leaves the- * folder before the Buddy's next turn (pruneBuddyHome).+ * ever mix. Nothing is cloned for it. Each copy follows its project's default branch (refreshBuddyHome): a worktree made once+ * and kept read days-old code, and the Buddy kept telling its person so (Scholes, 11-02). Its guard confines its reads to this+ * folder, and the lock its launch applies makes every file in it read-only (lib/swarmSkills.ts lockBuddyFolder). A project its+ * person no longer reads leaves the folder before the Buddy's next turn (pruneBuddyHome).*/import { execFile } from 'node:child_process'-import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'+import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'import { join } from 'node:path'import { promisify } from 'node:util'import { launchEnvironment } from '../engines/kit/launchExecutable.js'import { folderTrust } from '../engines/launchPrep.js'-import { insideGitCheckout } from '../lib/gitProject.js'+import { gitEnv, insideGitCheckout, originDefaultRef, remoteBranch } from '../lib/gitProject.js'const run = promisify(execFile)/** A project as the backend lists it in a Swarm-wide Buddy's start (AgentStartRequest.buddyProjects). */@@ -27,6 +28,15 @@ export const BUDDY_HOMES = 'buddy-home'/** At most this many, as the backend lists (machines.ts MAX_BUDDY_PROJECTS). */export const MAX_BUDDY_PROJECTS = 50const ID = /^[A-Za-z0-9_-]{1,64}$/+/** What the Buddy reads to learn where each copy is. A file, as a copy moves while it runs and its prompt is fixed at its start,+ * and the main Buddy's shell has no repository to run git in (spec 2026-10-31, Folder). Its age also says when the last pass+ * was, so "at most hourly" holds across a daemon restart. */+export const BUDDY_COPIES_FILE = 'project-copies.txt'+const REFRESH_EVERY_MS = 60 * 60_000+/** All of one pass's fetches share this: 50 projects offline must not hold a Buddy's start for 50 timeouts. */+const FETCH_BUDGET_MS = 30_000+const FETCH_TIMEOUT_MS = 20_000+const FETCHES_AT_ONCE = 4/** The projects a start lists, as far as they are well formed: an id, a name and an absolute folder. */export function buddyProjectsOf(request: Record<string, unknown>): BuddyProject[] {@@ -66,10 +76,12 @@ function writeListed(home: string, rows: Listed[]): void {/*** Makes [home] with a worktree of each of [projects] whose checkout is on this machine, and says which are there and which- * are not (their code is not on this machine; the Buddy still reads their chats and tasks). A worktree made before is kept;- * one that cannot be made is left out, never retried in a loop. The person's own checkouts are only read from.+ * are not (their code is not on this machine; the Buddy still reads their chats and tasks). A worktree made before is kept and+ * brought to its project's default branch, as a new one is (refreshBuddyHome); one that cannot be made is left out, never+ * retried in a loop. The person's own working files and branches are never touched.*/export async function prepareBuddyHome(home: string, projects: readonly BuddyProject[]): Promise<{ ready: string[]; missing: string[] }> {+ await refreshing.get(home)?.doneownFolders(home, true)mkdirSync(join(home, 'projects'), { recursive: true, mode: 0o700 })ownFolders(home)@@ -96,17 +108,159 @@ export async function prepareBuddyHome(home: string, projects: readonly BuddyPro} catch { missing.push(project.name) }}writeListed(home, rows)+ await refreshBuddyHome(home)return { ready, missing }}+/** Where one copy stands after a pass, for the Buddy's file and the pass's one log line. */+type CopyState = { name: string; revision: string | null; state: 'latest' | 'noRemote' | 'changed' | 'failed' }+const refreshing = new Map<string, { stop: AbortController; done: Promise<void> }>()++/**+ * Brings each of [home]'s copies to its project's default branch and writes what the Buddy reads about them. Only one pass runs+ * per folder; a second call joins it. It never throws: a copy that cannot move stays as it is, says so in the file, and the pass+ * logs one line, with no retry before the next start or the next due delivery. Offline is ordinary.+ */+export function refreshBuddyHome(home: string): Promise<void> {+ const running = refreshing.get(home)+ if (running) return running.done+ const stop = new AbortController()+ const done = refreshPass(home, stop.signal)+ .catch((error: unknown) => { console.warn(`[super-tabs] a Buddy's project copies were not refreshed: ${(error as NodeJS.ErrnoException).code ?? 'error'}`) })+ .finally(() => { refreshing.delete(home) })+ refreshing.set(home, { stop, done })+ return done+}++/** Whether the last pass was an hour ago. Read at a delivery, not on a timer, as only then does anything read the copies: an idle+ * Buddy costs its person no fetches. */+export function buddyHomeDue(home: string, now = Date.now()): boolean {+ const last = lstatSync(join(home, BUDDY_COPIES_FILE), { throwIfNoEntry: false })?.mtimeMs+ return last === undefined || now < last || now - last >= REFRESH_EVERY_MS+}++/** The pass running in [home], if any. */+export const buddyHomeRefreshing = (home: string): Promise<void> | undefined => refreshing.get(home)?.done++/** Whether [home] holds a project outside [readable], so that it must be pruned before its Buddy's next turn. */+export const buddyHomeHoldsLost = (home: string, readable: ReadonlySet<string>): boolean => listed(home).some(row => !readable.has(row.id))++/** Tells a running pass to stop, without waiting for it: the delivery loop serves every agent on the machine (review of #2524). */+export function stopBuddyHomeRefresh(home: string): void { refreshing.get(home)?.stop.abort() }++async function refreshPass(home: string, signal: AbortSignal): Promise<void> {+ ownFolders(home)+ const rows = listed(home), states: CopyState[] = [], deadline = Date.now() + FETCH_BUDGET_MS+ let next = 0+ const worker = async () => {+ while (next < rows.length && !signal.aborted) {+ const at = next++, row = rows[at]!+ states[at] = await refreshCopy(join(home, 'projects', row.dir), row.name, deadline, signal)+ }+ }+ await Promise.all(Array.from({ length: FETCHES_AT_ONCE }, worker))+ // Stopped because a project is leaving: its name must not go back in the file, and the next pass writes a whole one.+ if (signal.aborted) return+ writeCopies(home, states)+ const failed = states.filter(state => state.state === 'failed' || state.state === 'changed').length+ // A count alone: git's own words can hold a remote's address, and an address can hold a token.+ if (failed) console.warn(`[super-tabs] ${failed} of ${states.length} of a Buddy's project copies were left where they are.`)+}++/** One copy. The fetch runs in the Buddy's own worktree: git keeps FETCH_HEAD per worktree, so of the person's checkout it moves+ * only the one remote-tracking ref named. Their hooks do not run: a post-checkout hook is written for their own work. */+async function refreshCopy(path: string, name: string, deadline: number, signal: AbortSignal): Promise<CopyState> {+ const state = (next: CopyState['state'], revision: string | null = null): CopyState => ({ name, revision, state: next })+ const entry = lstatSync(path, { throwIfNoEntry: false })+ if (!entry || !entry.isDirectory()) return state('failed')+ const words = (args: string[]) => ['--no-optional-locks', '-c', 'core.fsmonitor=false', '-c', 'core.hooksPath=/dev/null', '-C', path, ...args]+ const git = async (args: string[], options: { timeout?: number; signal?: AbortSignal } = {}) => (await run('git', words(args),+ { timeout: options.timeout ?? 60_000, maxBuffer: 64 * 1024 * 1024, env: gitEnv(process.env), ...(options.signal ? { signal: options.signal } : {}) })).stdout.trim()+ let at: string | null = null+ const here = async () => await git(['log', '-1', '--no-show-signature', '--format=%h %cs']).catch(() => null)+ try {+ // A folder that lost its .git would otherwise find whichever repository is above it, and move that one.+ if (realpathSync(await git(['rev-parse', '--show-toplevel'])) !== realpathSync(path)) return state('failed')+ at = await here()+ const detached = await git(['symbolic-ref', '--quiet', 'HEAD']).then(() => false, () => true)+ if (!detached || await git(['status', '--porcelain'])) return state('changed', at)+ const remote = remoteBranch(await originDefaultRef(path) ?? undefined)+ if (!remote) return state('noRemote', at)+ const left = deadline - Date.now()+ if (left <= 0 || signal.aborted) return state('failed', at)+ await git(['-c', 'gc.auto=0', '-c', 'maintenance.auto=false', 'fetch', '--quiet', '--no-tags', '--no-prune', '--no-recurse-submodules', remote.remote, remote.refspec],+ { timeout: Math.min(left, FETCH_TIMEOUT_MS), signal })+ const [from, to] = [await git(['rev-parse', 'HEAD']), await git(['rev-parse', `refs/remotes/${remote.remote}/${remote.branch}^{commit}`])]+ if (from !== to && !signal.aborted) {+ // Read first, so whatever the move does the files it wrote are locked again. Only those: a walk of the whole tree every+ // hour would cost a large project's every file, and git rewrites no others.+ // As bytes, untrimmed: a name may start with a space or not be UTF-8, and one read otherwise was never found to lock+ // (security review 2 of #2524).+ const changed = fileNames((await run('git', words(['diff', '--name-only', '--no-renames', '-z', from, to]),+ { timeout: 60_000, maxBuffer: 64 * 1024 * 1024, env: gitEnv(process.env), encoding: 'buffer' })).stdout)+ try { await git(['checkout', '--quiet', '--detach', '--no-recurse-submodules', to], { timeout: 120_000 }) }+ finally { lockFiles(path, changed) }+ }+ return state(await git(['rev-parse', 'HEAD']) === to ? 'latest' : 'failed', await here())+ } catch { return state('failed', at) }+}++/** The names in git's NUL-separated list, each its exact bytes. */+function fileNames(list: Buffer): Buffer[] {+ const names: Buffer[] = []+ for (let from = 0, end; (end = list.indexOf(0, from)) >= 0; from = end + 1) if (end > from) names.push(list.subarray(from, end))+ return names+}++/** The lock a launch applies (lib/swarmSkills.ts lockBuddyFolder) for the files a move wrote: git makes them writable. */+function lockFiles(path: string, names: readonly Buffer[]): void {+ const real = Buffer.from(realpathSync(path))+ for (const name of names) {+ const slash = name.lastIndexOf(0x2f)+ const folder = slash < 0 ? real : Buffer.concat([real, Buffer.from('/'), name.subarray(0, slash)])+ const file = Buffer.concat([real, Buffer.from('/'), name])+ const entry = lstatSync(file, { throwIfNoEntry: false })+ // Never through a link, the file's own or a folder's on its way: a commit replacing folder a with a link still lists a/b.txt,+ // and a chmod there changed a file outside (review of #2524).+ if (entry?.isFile() && realpathSync(folder, { encoding: 'buffer' }).equals(folder)) chmodSync(file, entry.mode & 0o555)+ }+}++function writeCopies(home: string, states: readonly CopyState[]): void {+ const line = (copy: CopyState) => {+ const name = copy.name.replace(/\s+/g, ' ')+ const at = copy.revision ? `at ${copy.revision}` : 'revision not known'+ if (copy.state === 'latest') return `${name}: ${at}. This is the latest default branch.`+ if (copy.state === 'noRemote') return `${name}: ${at}. This checkout has no remote default branch to follow.`+ return `${name}: ${at}. It could not be updated at the last refresh, so it may be behind the default branch.`+ }+ const path = join(home, BUDDY_COPIES_FILE), next = `${path}.next`+ rmSync(next, { force: true })+ writeFileSync(next, `Your copy of each project's code, refreshed ${new Date().toISOString()}:\n${states.map(line).join('\n')}\n`, { mode: 0o444 })+ renameSync(next, path)+}++/** A running pass stops before any more fetches or moves, and its running move finishes: a move killed part way would leave a+ * half-moved copy that every later pass reads as changed. */+async function stopRefresh(home: string): Promise<void> {+ const running = refreshing.get(home)+ if (!running) return+ running.stop.abort()+ await running.done+}+/** Takes out of [home] each worktree whose project is not in [readable] (ids): its person lost it, or it was deleted. */export async function pruneBuddyHome(home: string, readable: ReadonlySet<string>): Promise<string[]> {const rows = listed(home)const gone = rows.filter(r => !readable.has(r.id))if (!gone.length) return []ownFolders(home)+ // No pass may be working in, or naming, a project on its way out.+ await stopRefresh(home)for (const row of gone) await removeWorktree(home, row.dir)writeListed(home, rows.filter(r => readable.has(r.id)))+ // It names the lost project. Gone, the next pass is due and writes a whole one.+ rmSync(join(home, BUDDY_COPIES_FILE), { force: true })return gone.map(r => r.name)}@@ -126,6 +280,7 @@ export async function trustBuddyHome(home: string, engine: unknown): Promise<voi/** Takes every worktree out of [home] and removes it: its Buddy ended. */export async function removeBuddyHome(home: string): Promise<void> {+ await stopRefresh(home)// Through a link nothing is removed but the link itself (rm never follows one inside the folder it removes).const own = (() => { try { ownFolders(home); return true } catch { return false } })()if (own) for (const row of listed(home)) await removeWorktree(home, row.dir)diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.tsindex 66db19a59..014ba9914 100644--- a/cli/src/superTabs/host.spec.ts+++ b/cli/src/superTabs/host.spec.ts@@ -4,12 +4,18 @@ import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync,import { tmpdir } from 'node:os'import { basename, dirname, join } from 'node:path'import { prepareSwarmSkill } from '../lib/swarmSkills.js'+import { BUDDY_COPIES_FILE, BUDDY_HOME_MANIFEST, buddyHomeRefreshing, refreshBuddyHome, stopBuddyHomeRefresh } from './buddyHome.js'import { allowBuddyReads, buddyAccountFile, buddyApprovalsOf, buddyGuardSource, buddyLaunchFile, buddyReadsOf, buddyWideOf, forgetBuddyReads } from '../lib/buddyGuard.js'import { env } from '../config/env.js'import { PASTE_DROPS_DIR } from '../lib/pasteDropFiles.js'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'// The real lists cleanup, which one test makes throw what it never throws today: an error that is not its own.+// The real folder code, with the calls the delivery loop makes held open by the tests that need a pass to be running.+vi.mock('./buddyHome.js', async original => {+ const real = await original<typeof import('./buddyHome.js')>()+ return { ...real, refreshBuddyHome: vi.fn(real.refreshBuddyHome), buddyHomeRefreshing: vi.fn(real.buddyHomeRefreshing), stopBuddyHomeRefresh: vi.fn(real.stopBuddyHomeRefresh) }+})vi.mock('../lib/buddyGuard.js', async original => {const actual = await original<typeof import('../lib/buddyGuard.js')>()return { ...actual, forgetBuddyReads: vi.fn(actual.forgetBuddyReads) }@@ -1489,6 +1495,36 @@ describe('Super Tab attachments in delivered input', () => {const delivered = () => vi.mocked(t.core.turns.deliver).mock.calls.map(c => `${String(c[0])}: ${String(c[1]).match(/(The model\.|Hello\.|Next\.)/)?.[0]}`)return { delivered }}+ // Review of #2524: this loop hands every agent on the machine its input.+ it('a Buddy\'s project copies moving hold its messages, in order, and no other agent\'s', async () => {+ const t = setup(), folder = realpathSync(mkdtempSync(join(tmpdir(), 'buddy-copies-'))); roots.push(folder)+ mkdirSync(join(folder, 'projects'))+ writeFileSync(join(folder, BUDDY_HOME_MANIFEST), '[]\n')+ const { delivered } = swarmOf(t, [{ id: 'a', deliveries: [{ id: 'first', text: 'The model.' }, { id: 'second', text: 'Next.' }] }, { id: 'z', deliveries: [{ id: 'plain', text: 'Hello.' }] }])+ const answer = vi.mocked(t.call).getMockImplementation()!+ vi.mocked(t.call).mockImplementation(async (method, path, body) => path.includes('asAgentId=')+ ? { status: 200, body: { success: true, data: swarmReply(path, { conversations: [{ id: 'lead' }], agents: [{ id: 'a', buddyScope: 'swarm' }] }) } } : answer(method, path, body))+ vi.mocked(t.core.agents.byAgent).mockImplementation(((id: string) => ({ agentId: id, cwd: folder, ...id === 'harness-a' ? { swarmSkill: { role: 'buddy', key: 'k' } } : {} })) as never)+ let open = () => {}+ const pass = new Promise<void>(resolve => { open = resolve })+ vi.mocked(refreshBuddyHome).mockReturnValueOnce(pass)+ vi.mocked(buddyHomeRefreshing).mockImplementation(() => vi.mocked(refreshBuddyHome).mock.calls.length ? pass : undefined)+ let now = 1_000_000+ const host = t.open({ now: () => now })+ await host.tick()+ expect(delivered()).toEqual(['harness-z: Hello.'])+ // The first tried at 1, 3 and 7 s, then backing off to 15 s. At 12 s the wait is over, and the second still stays behind it.+ for (const at of [1_000, 3_000, 7_000, 12_000]) {+ now = 1_000_000 + at+ await host.tick()+ expect(delivered()).toEqual(['harness-z: Hello.'])+ }+ vi.mocked(buddyHomeRefreshing).mockReset()+ open()+ writeFileSync(join(folder, BUDDY_COPIES_FILE), 'fresh')+ await vi.waitFor(async () => { now += 60_000; await host.tick(); expect(delivered().filter(line => line.startsWith('harness-a'))).toEqual(['harness-a: The model.', 'harness-a: Next.']) })+ vi.mocked(refreshBuddyHome).mockReset()+ })/** A download that ends when [finish] is called, for messages with files. */function slowFiles() {let finish!: () => void@@ -1568,7 +1604,7 @@ describe('what a Buddy\'s own person sends it in their Buddy chat', () => {beforeEach(() => rmSync(buddyReadsOf(key).file, { force: true }))/** A Buddy's delivery of [message] from its chat, its Swarm read as it holds [agents] and [conversations]. */- function buddyOn(message: Record<string, unknown> = {}, read: { agents?: unknown[]; conversations?: unknown[] } = {}, claim: Record<string, unknown> = {}) {+ function buddyOn(message: Record<string, unknown> = {}, read: { agents?: unknown[]; conversations?: unknown[] } = {}, claim: Record<string, unknown> = {}, options: SuperTabHostOptions = {}) {const t = setup({ conversationId: 'chat', text: `Have a look: ${LINK}?v=2`, author: person, attachments: [picture], ...message }, claim)t.row.agent.id = AGENTt.from(String(message.conversationId ?? 'chat'))@@ -1596,7 +1632,7 @@ describe('what a Buddy\'s own person sends it in their Buddy chat', () => {? { text: `Attached files:\n- ${shot} (sent as "screen.png", 3 B)`, complete: true, paths: [shot] } : { text: '', complete: true, paths: [] })const delivered: { text: string; list: unknown }[] = []vi.mocked(t.core.turns.deliver).mockImplementation((_harness, text) => { delivered.push({ text: String(text), list: listed() }) })- const host = t.open({ attachedFiles })+ const host = t.open({ attachedFiles, ...options })return { t, host, shot, state, reads, delivered, refuse: (value: boolean) => { refuse = value } }}@@ -1619,6 +1655,108 @@ describe('what a Buddy\'s own person sends it in their Buddy chat', () => {// its person's files but never wide reads, which could reach another project's clone in their home.const swarmChat = { ...buddyChat, kind: 'swarm-buddy', projectId: undefined }const swarmBuddy = { ...buddyAgent, projectId: undefined, buddyScope: 'swarm' }+ // Scholes, 11-02. At a delivery, as only then does anything read the copies; after the access check, so a person who lost a+ // project gets none of its new code; and never holding the loop that serves every agent on the machine (review of #2524).+ describe('its project copies at a delivery', () => {+ const folderOf = (t: ReturnType<typeof buddyOn>['t']) => String(vi.mocked(t.core.agents.byAgent).getMockImplementation()?.('harness' as never)?.cwd)+ const withHome = (t: ReturnType<typeof buddyOn>['t'], rows: unknown[] = []) => {+ mkdirSync(join(folderOf(t), 'projects'))+ writeFileSync(join(folderOf(t), BUDDY_HOME_MANIFEST), `${JSON.stringify(rows)}\n`)+ }+ const swarm = () => buddyOn({}, { agents: [swarmBuddy], conversations: [swarmChat] })+ const deferred = () => { let open = () => {}; const done = new Promise<void>(resolve => { open = resolve }); return { done, open } }+ afterEach(() => { vi.mocked(refreshBuddyHome).mockReset(); vi.mocked(buddyHomeRefreshing).mockReset() })++ it('holds only this Buddy\'s message while a due pass runs, and delivers it when the pass ends', async () => {+ const { host, t, delivered } = swarm(), pass = deferred()+ withHome(t)+ vi.mocked(refreshBuddyHome).mockReturnValue(pass.done)+ // Back while the pass still runs: the loop was not held.+ await host.tick()+ expect(refreshBuddyHome).toHaveBeenCalledWith(folderOf(t))+ expect(delivered).toEqual([])+ pass.open()+ await vi.waitFor(() => expect(delivered).toHaveLength(1))+ })+ it('delivers once its wait is over, with the pass still running', async () => {+ let now = 1_000_000+ const { host, t, delivered } = buddyOn({}, { agents: [swarmBuddy], conversations: [swarmChat] }, {}, { now: () => now }), pass = deferred()+ withHome(t)+ vi.mocked(refreshBuddyHome).mockReturnValue(pass.done)+ vi.mocked(buddyHomeRefreshing).mockImplementation(() => vi.mocked(refreshBuddyHome).mock.calls.length ? pass.done : undefined)+ await host.tick()+ expect(delivered).toEqual([])+ now += 11 * 60_000+ await host.tick()+ expect(delivered).toHaveLength(1)+ pass.open()+ })+ it('stops a running pass for a project just lost, waits for it, and prunes before the Buddy hears the message', async () => {+ let now = 1_000_000+ const { host, t, delivered } = buddyOn({}, { agents: [swarmBuddy], conversations: [swarmChat] }, {}, { now: () => now }), pass = deferred(), folder = () => join(folderOf(t), 'projects', 'Secret')+ withHome(t, [{ id: 'secret', name: 'Secret', dir: 'Secret' }])+ mkdirSync(folder())+ vi.mocked(buddyHomeRefreshing).mockReturnValue(pass.done)+ const heard: boolean[] = []+ vi.mocked(t.core.turns.deliver).mockImplementation(() => { heard.push(existsSync(folder())) })+ await host.tick()+ expect(stopBuddyHomeRefresh).toHaveBeenCalledWith(folderOf(t))+ expect(heard).toEqual([])+ expect(existsSync(folder())).toBe(true)+ vi.mocked(buddyHomeRefreshing).mockReturnValue(undefined)+ vi.mocked(refreshBuddyHome).mockResolvedValue(undefined)+ pass.open()+ // Its wake-up may land in a pass already running; the host's own timer then tries again, as this does.+ await vi.waitFor(async () => { now += 60_000; await host.tick(); expect(heard).toEqual([false]) })+ expect(delivered).toEqual([])+ })+ it('delivers after a pass that could not write its file, instead of starting another for ever', async () => {+ let now = 1_000_000+ const { host, t, delivered } = buddyOn({}, { agents: [swarmBuddy], conversations: [swarmChat] }, {}, { now: () => now })+ withHome(t)+ vi.mocked(refreshBuddyHome).mockResolvedValue(undefined)+ await vi.waitFor(async () => { now += 60_000; await host.tick(); expect(delivered).toHaveLength(1) })+ expect(refreshBuddyHome).toHaveBeenCalledTimes(1)+ expect(existsSync(join(folderOf(t), BUDDY_COPIES_FILE))).toBe(false)+ })+ it('writes the copies file again at once after a project leaves, not an hour on (security review 2 of #2524)', async () => {+ let now = 1_000_000+ const { host, t, delivered } = buddyOn({}, { agents: [swarmBuddy], conversations: [swarmChat] }, {}, { now: () => now }), pass = deferred()+ withHome(t)+ vi.mocked(refreshBuddyHome).mockReturnValueOnce(pass.done).mockResolvedValue(undefined)+ await host.tick()+ expect(refreshBuddyHome).toHaveBeenCalledTimes(1)+ // Lost during that pass's hold: the message tried again prunes it, within the hour.+ writeFileSync(join(folderOf(t), BUDDY_HOME_MANIFEST), `${JSON.stringify([{ id: 'secret', name: 'Secret', dir: 'Secret' }])}\n`)+ pass.open()+ await vi.waitFor(async () => { now += 1_000; await host.tick(); expect(delivered).toHaveLength(1) })+ expect(refreshBuddyHome).toHaveBeenCalledTimes(2)+ })+ it('starts no pass when the access read is refused, and delivers nothing', async () => {+ // From an agent, with nothing attached: no earlier read refuses it first, so this one is what stops it.+ const { host, t, delivered, refuse } = buddyOn({ author: { kind: 'agent', id: 'lead-agent', name: 'PM', membershipGeneration: 'g' }, attachments: [], text: 'news' },+ { agents: [swarmBuddy], conversations: [swarmChat] })+ withHome(t)+ refuse(true)+ await host.tick()+ expect(refreshBuddyHome).not.toHaveBeenCalled()+ expect(delivered).toEqual([])+ })+ it('starts no pass for a Buddy of one project, whose folder is its worktree', async () => {+ const { host, t } = buddyOn()+ withHome(t)+ await host.tick()+ expect(refreshBuddyHome).not.toHaveBeenCalled()+ })+ it('starts no pass an hour has not passed for', async () => {+ const { host, t, delivered } = swarm()+ withHome(t)+ writeFileSync(join(folderOf(t), BUDDY_COPIES_FILE), 'fresh')+ await host.tick()+ expect(refreshBuddyHome).not.toHaveBeenCalled()+ expect(delivered).toHaveLength(1)+ })+ })it('grants its person\'s one Buddy in their one chat, wide reads included', async () => {const { host, shot, delivered } = buddyOn({}, { agents: [swarmBuddy], conversations: [swarmChat] })await host.tick()diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.tsindex 95dd20bde..6a0acc34c 100644--- a/cli/src/superTabs/host.ts+++ b/cli/src/superTabs/host.ts@@ -9,7 +9,7 @@ import { createHash, randomUUID } from 'node:crypto'import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs'import { readdir, readFile } from 'node:fs/promises'import { basename, dirname, isAbsolute, join, normalize, relative, sep } from 'node:path'-import { BUDDY_HOME_MANIFEST, BUDDY_HOMES, pruneBuddyHome, removeBuddyHome } from './buddyHome.js'+import { BUDDY_HOME_MANIFEST, BUDDY_HOMES, buddyHomeDue, buddyHomeHoldsLost, buddyHomeRefreshing, pruneBuddyHome, refreshBuddyHome, removeBuddyHome, stopBuddyHomeRefresh } from './buddyHome.js'import type { BackendNotice, CoreApi, TurnDelivery } from '../core/api.js'import { shellQuote } from '../orchestrator/prompts.js'import { agentCommandPrefix, fullCommandPrefix } from './shortCommand.js'@@ -280,6 +280,11 @@ const CONTEXT_WAIT_MS = 3_000* each try claims it again with the same claim id: that writes the delivery, so the backend never takes the claim for one* nobody holds (backend deliverySettle.ts CLAIM_QUIET_MS, 10 minutes). Said once, not as a failure. */class FilesDownloading extends Error {}+/** A Buddy's project copies are moving (buddyHome.ts): its message waits, quietly, in the same way, and nobody else's does. */+class BuddyCopiesMoving extends FilesDownloading {}+/** How long a Buddy's messages wait on a pass over its copies, so a first message after a quiet hour reads new code. */+const BUDDY_COPIES_WAIT_MS = 10_000+const BUDDY_COPIES_RETRY_MS = 60 * 60_000/** A delivery's files on their way. [stop] ends them when the delivery leaves (attachments.ts stops a file once no delivery* wants it, and removes its part); [result] is set once they are in; [said]: a pass stopped waiting on it. */interface Download {@@ -406,6 +411,10 @@ export class SuperTabHost {/** The files those downloads are fetching, so two deliveries of one file download it once at a time (attachments.ts). */private readonly inFlight: FilesInFlight = new Map()private readonly downloadWaitMs: number+ /** Each Buddy folder with a pass running that held a message: since when, and which deliveries. */+ private readonly copiesHeld = new Map<string, { since: number; deliveries: Set<string> }>()+ /** When this host last started a pass over each Buddy folder. One small number per folder, for as long as the daemon runs. */+ private readonly copiesTried = new Map<string, number>()private readonly contextWaitMs: number/** This pass's one wait on the downloads it starts (DOWNLOAD_WAIT_MS), shared by all of them; null until one starts. */private passWait: Promise<null> | null = null@@ -1029,7 +1038,7 @@ export class SuperTabHost {const claimKey = `claim:${delivery.id}`if (this.backedOff(claimKey)) {const download = this.downloads.get(delivery.id)- if (download?.said && !download.result) held = true+ if (download?.said && !download.result || [...this.copiesHeld.values()].some(hold => hold.deliveries.has(String(delivery.id)))) held = truecontinue}// Checked before anything is typed: a new delivery, or one held while its agent may since have stopped leading. A@@ -1740,7 +1749,7 @@ export class SuperTabHost {}// A person's one Buddy reads only the projects its person reads now: a project they lost leaves its folder before this// turn (buddyHome.ts; spec 2026-10-31-one-buddy-per-swarm, Access). A read that fails withholds the delivery, tried again.- if (this.isBuddy(entry)) await this.pruneBuddyFolder(entry)+ if (this.isBuddy(entry)) await this.pruneBuddyFolder(entry, deliveryId, `list:${target.tabId}:${target.agent.id}`)this.prefix ??= this.agentCommand(this.core, this.machineId).catch(() => fullCommandPrefix(this.core.daemon, this.machineId))const command = await this.prefixlet quote = this.quotes.get(deliveryId)@@ -1782,16 +1791,54 @@ export class SuperTabHost {}/** Takes out of a person's one Buddy's folder each project worktree whose project its person no longer reads, as the Swarm- * says to the Buddy now. Nothing for any other Buddy: its folder is one project's worktree. */- private async pruneBuddyFolder(entry: Entry): Promise<void> {+ * says to the Buddy now, then brings the rest to their default branches when that is due. Nothing for any other Buddy: its+ * folder is one project's worktree. No pass is ever waited for here: this loop hands every agent on the machine its input+ * (review of #2524). A message waits instead, as one whose files are downloading does. */+ private async pruneBuddyFolder(entry: Entry, deliveryId: string, listKey: string): Promise<void> {const cwd = this.core.agents.byAgent(entry.harnessId)?.cwdif (!cwd || !existsSync(join(cwd, BUDDY_HOME_MANIFEST))) returnconst { state } = await this.sources.reads.read(entry.tabId, entry.agentId)const agent = (Array.isArray(state.agents) ? state.agents.map(object) : []).find(a => a.id === entry.agentId)if (agent?.buddyScope !== 'swarm') returnconst readable = new Set((Array.isArray(state.projects) ? state.projects.map(object) : []).flatMap(p => identifier(p.id) ? [p.id] : []))- const gone = await pruneBuddyHome(cwd, readable)- if (gone.length) this.log(`Took ${gone.length} project folder(s) out of Buddy ${entry.harnessId.slice(0, 8)}'s folder: its person no longer reads them.`)+ let pass = buddyHomeRefreshing(cwd)+ // A project just lost must leave before this turn, however long the pass takes to stop: never delivered past it.+ const mustWait = !!pass && buddyHomeHoldsLost(cwd, readable)+ if (mustWait) stopBuddyHomeRefresh(cwd)+ if (!pass) {+ const gone = await pruneBuddyHome(cwd, readable)+ if (gone.length) {+ this.log(`Took ${gone.length} project folder(s) out of Buddy ${entry.harnessId.slice(0, 8)}'s folder: its person no longer reads them.`)+ // Pruning took the copies file, which named the lost project. The next pass writes it, now, not an hour on: the Buddy's+ // prompt tells it to read that file (security review 2 of #2524).+ this.copiesTried.delete(cwd)+ }+ // After the check above, whose failed read throws: new code of a project reaches only a person who still reads it.+ // Started once an hour here too: a pass that cannot write its file (a folder refused, a full disk) leaves it due, and its+ // message, tried again when the pass ends, would otherwise start another for ever and never go in.+ const tried = this.copiesTried.get(cwd)+ if (buddyHomeDue(cwd) && (tried === undefined || Math.abs(this.now() - tried) >= BUDDY_COPIES_RETRY_MS)) {+ this.copiesTried.set(cwd, this.now())+ pass = refreshBuddyHome(cwd)+ }+ }+ if (!pass) return+ let hold = this.copiesHeld.get(cwd)+ if (!hold) {+ const started = hold = { since: this.now(), deliveries: new Set<string>() }+ this.copiesHeld.set(cwd, started)+ void pass.then(() => {+ this.copiesHeld.delete(cwd)+ if (this.stopped) return+ // Delivered at once, not after its back-off.+ for (const id of started.deliveries) this.deliveryRetries.delete(`claim:${id}`)+ this.pushes.add(listKey)+ void this.tick()+ })+ }+ if (!mustWait && this.now() - hold.since >= BUDDY_COPIES_WAIT_MS) { hold.deliveries.delete(deliveryId); return }+ hold.deliveries.add(deliveryId)+ throw new BuddyCopiesMoving('Its project copies are moving.')}/** A delivery's files, downloaded off the poll loop. A pass waits only on the downloads it starts, all together for at mostdiff --git a/cli/src/superTabs/start.spec.ts b/cli/src/superTabs/start.spec.tsindex 82e9aa1f2..99d8c9f4e 100644--- a/cli/src/superTabs/start.spec.ts+++ b/cli/src/superTabs/start.spec.ts@@ -9,7 +9,8 @@ import { SuperTabHostError } from './wire.js'const teamDaemon = vi.hoisted(() => ({ value: false, relayed: true, offered: null as null | { slugs: string[]; listed: string[] } }))vi.mock('./teamDaemon.js', async (original) => ({ ...await original<object>(), isTeamDaemon: () => teamDaemon.value }))vi.mock('../team/relay.js', async (original) => ({ ...await original<object>(), teamRelayed: () => teamDaemon.relayed, offeredCodexModels: async () => teamDaemon.offered }))-vi.mock('./buddyHome.js', async (original) => ({ ...await original<object>(), prepareBuddyHome: async () => ({ ready: [], missing: [] }), trustBuddyHome: async () => {} }))+const prepared = vi.hoisted(() => ({ value: { ready: [] as string[], missing: [] as string[] } }))+vi.mock('./buddyHome.js', async (original) => ({ ...await original<object>(), prepareBuddyHome: async () => prepared.value, trustBuddyHome: async () => {} }))const where = { port: 14001, machineId: 'lead-machine', dataDir: '/fixture' }/** A queued start is watched before the Lead moves on (startAgent); these tests read the queued answer at once. */const noPause = async () => {}@@ -347,6 +348,19 @@ it('admits a person\'s one Buddy by the disk its folder is made on, as the folde} finally { rmSync(root, { recursive: true, force: true }) }})+it('tells a person\'s one Buddy where to read which revision each project copy is at, and when it may say it is behind', async () => {+ const f = fixture()+ f.start.request = { ...f.start.request, cwd: join(tmpdir(), 'swarm-buddy-prompt', '.buddy-peer'), worktree: false, buddyScope: 'swarm', buddyOf: { personId: 'peer', generation: 'g' } } as typeof f.start.request+ // The mocked folder has its copies ready.+ prepared.value = { ready: ['Web'], missing: [] }+ try {+ await startAgent({ action: 'start', tabId: 'tab', operationId: 'one-buddy-copies', request: f.start.request }, f.scoped, where, f.open)+ const prompt = String(f.request.mock.calls.find(call => call[0] === 'agent_create')![1]!.prompt)+ expect(prompt).toContain('project-copies.txt')+ expect(prompt).toContain('Say your copy is behind only when that file says it may be')+ } finally { prepared.value = { ready: [], missing: [] } }+})+it.each(['claude'])('starts a %s thread session as a Buddy in every way, told its thread and to answer only there, with no message text', async engine => {const plain = fixture()plain.start.request = { ...plain.start.request, engine, buddyOf: { personId: 'peer', generation: 'g' } } as typeof plain.start.requestdiff --git a/cli/src/superTabs/start.ts b/cli/src/superTabs/start.tsindex 82a90fa16..f5c9c4883 100644--- a/cli/src/superTabs/start.ts+++ b/cli/src/superTabs/start.ts@@ -10,7 +10,7 @@ import { permissionModeFlags } from '../lib/engineLaunch.js'import type { AgentEngine } from '../engines/types.js'import { isSwarmSkillMode, swarmSkillUse, wireRole, type SwarmSkillMode } from '../lib/swarmSkills.js'import { isTeamDaemon, pmEngineHome } from './teamDaemon.js'-import { BUDDY_HOMES, buddyProjectsOf, prepareBuddyHome, trustBuddyHome } from './buddyHome.js'+import { BUDDY_COPIES_FILE, BUDDY_HOMES, buddyProjectsOf, prepareBuddyHome, trustBuddyHome } from './buddyHome.js'import { markBuddyNarrow } from '../lib/buddyGuard.js'import { projectsRoot } from '../lib/projectFolder.js'import { worktreeFolderName } from '../lib/agentNames.js'@@ -89,7 +89,7 @@ function buddySessionPrompt(tabId: string, chat: string, thread: string, mode: S* reads, each project's code in its own folder under projects/, and writes only in its person's chat. Names only, never a* message's text: a start record is listed in the Lead's status. */function swarmBuddyPrompt(tabId: string, chat: string, home: { ready: string[]; missing: string[] }, mode: SwarmSkillMode | null): string {- const code = home.ready.length ? `Each project's code is in its own folder under projects/ (${home.ready.join(', ')}).` : 'No project\'s code is on this machine.'+ const code = home.ready.length ? `Each project's code is in its own folder under projects/ (${home.ready.join(', ')}). Each copy follows its project's default branch, moved at your start and at most hourly after that. ${BUDDY_COPIES_FILE} in your folder says which revision each copy is at: read it before saying what the code does or does not have. Say your copy is behind only when that file says it may be; otherwise, what is not in the copy is not on the default branch yet.` : 'No project\'s code is on this machine.'const none = home.missing.length ? ` Not on this machine: ${home.missing.join(', ')}; you still read their chats and tasks.` : ''return `You are a person's one Buddy in a shared Super Tab, for every project they read. ${mode ? `${swarmSkillUse({ role: 'buddy' }, mode)} ` : ''}Run harness super-tab --tab ${tabId} status until this harness appears in the roster: it lists your owner's projects, one line each, and the newest tasks; status --project NAME reads one project's tasks. ${code}${none} Your chat with your owner is conversation ${chat}: read it with harness super-tab --tab ${tabId} messages ${chat}, and reply there with harness super-tab --tab ${tabId} post ${chat} 'your message' UNIQUE_OPERATION_ID. You send nothing into a project: when your owner wants something sent to a project's PM, tell them to start a New session in that project. Then greet your owner there and ask what they have in mind. If sandbox restrictions block this local command, request permission to run it outside the sandbox.`}diff --git a/desktop/lib/agent_messages/agent_messages_view.dart b/desktop/lib/agent_messages/agent_messages_view.dartindex 07f0bef75..5e240fcef 100644--- a/desktop/lib/agent_messages/agent_messages_view.dart+++ b/desktop/lib/agent_messages/agent_messages_view.dart@@ -16,6 +16,7 @@ import 'shared_tab_tasks.dart';import 'tab_people.dart';import 'update_harness.dart';import 'shared_tabs.dart' show SharedTabsState;+import '../widgets/laid_out_list.dart';/// The parts of a shared tab's Agent Messages panel.enum AgentMessagesTab {@@ -284,7 +285,7 @@ class _AgentMessagesViewState extends State<AgentMessagesView> {);} else {// Reversed, so the newest sits at the bottom and the list opens there.- body = ListView.builder(+ body = LaidOutListView.builder(reverse: true,shrinkWrap: true,itemCount: messages.length,diff --git a/desktop/lib/agent_messages/shared_tab_people.dart b/desktop/lib/agent_messages/shared_tab_people.dartindex 7f37d16e3..ac577146c 100644--- a/desktop/lib/agent_messages/shared_tab_people.dart+++ b/desktop/lib/agent_messages/shared_tab_people.dart@@ -12,6 +12,7 @@ import 'shared_tab_errors.dart';import 'shared_tab_placement.dart' show plainSharedText, shortSharedText;import 'shared_tabs.dart';import 'shared_tabs_model.dart';+import '../widgets/laid_out_list.dart';/// The plain words for a warning about a shared tab (1c spec, Errors).String sharedTabAlertText(String code) => switch (code) {@@ -206,7 +207,7 @@ class _SharedTabPeopleState extends State<SharedTabPeople> {final menu = sharedTabMenu(app, widget.deskTabId);final pending = [for (final i in tab.pendingInvites) i];- return ListView(+ return LaidOutListView(key: const ValueKey('shared-tab-people'),shrinkWrap: true,padding: EdgeInsets.zero,diff --git a/desktop/lib/agent_messages/shared_tab_tasks.dart b/desktop/lib/agent_messages/shared_tab_tasks.dartindex 2bfc7ef71..2e367df28 100644--- a/desktop/lib/agent_messages/shared_tab_tasks.dart+++ b/desktop/lib/agent_messages/shared_tab_tasks.dart@@ -12,6 +12,7 @@ import 'task_step.dart';import 'shared_tab_placement.dart' show plainSharedText, shortSharedText;import 'shared_tabs.dart';import 'shared_tabs_model.dart';+import '../widgets/laid_out_list.dart';/// One line for why a tab's tasks could not be read (1c spec, Errors).String sharedTasksErrorText(String code) => switch (code) {@@ -90,7 +91,7 @@ class SharedTabTasksState extends State<SharedTabTasks> {semanticsLabel: 'Loading tasks',);}- return ListView(+ return LaidOutListView(key: const ValueKey('shared-tasks'),shrinkWrap: true,padding: EdgeInsets.zero,diff --git a/desktop/lib/agent_messages/tab_activity_sidebar.dart b/desktop/lib/agent_messages/tab_activity_sidebar.dartindex 5c0920edc..f05b368c0 100644--- a/desktop/lib/agent_messages/tab_activity_sidebar.dart+++ b/desktop/lib/agent_messages/tab_activity_sidebar.dart@@ -18,6 +18,7 @@ import 'shared_tabs.dart';import 'shared_tabs_model.dart';import 'tab_activity.dart';import 'task_step.dart';+import '../widgets/laid_out_list.dart';/// Whether each tab's Tab Activity is open, and its width, on this computer/// (`tab_activity.open.<tabId>`, `tab_activity.width.<tabId>`). A tab never@@ -734,7 +735,7 @@ class _TabActivitySidebarState extends State<TabActivitySidebar> {child: LayoutBuilder(builder: (context, constraints) {final width = constraints.maxWidth;- return ListView(+ return LaidOutListView(padding: const EdgeInsets.only(bottom: 12),children: [_section(diff --git a/desktop/lib/agent_messages/tab_people.dart b/desktop/lib/agent_messages/tab_people.dartindex a525675fa..d55f4bf51 100644--- a/desktop/lib/agent_messages/tab_people.dart+++ b/desktop/lib/agent_messages/tab_people.dart@@ -11,6 +11,7 @@ import 'shared_tab_dialogs.dart';import 'shared_tab_people.dart'show PeopleRow, PeopleRowAction, toggleLeaderReportingError;import 'shared_tab_placement.dart' show shortSharedText;+import '../widgets/laid_out_list.dart';/// People in a tab that is not shared: this account's harnesses in it/// (engine, computer, whether it works), Make Leader / Remove Leader, and@@ -84,7 +85,7 @@ class _TabPeopleState extends State<TabPeople> {}rows.add(_row(pane.machineId, agentId, state));}- return ListView(+ return LaidOutListView(key: const ValueKey('tab-people'),shrinkWrap: true,padding: EdgeInsets.zero,diff --git a/desktop/lib/finder/widgets/finder_changes_view.dart b/desktop/lib/finder/widgets/finder_changes_view.dartindex 3d6853f7a..7d6a17790 100644--- a/desktop/lib/finder/widgets/finder_changes_view.dart+++ b/desktop/lib/finder/widgets/finder_changes_view.dart@@ -14,6 +14,7 @@ import '../finder_models.dart';import 'finder_change_row.dart';import 'finder_click.dart';import 'finder_dialogs.dart';+import '../../widgets/laid_out_list.dart';/// The Changes half of the sidebar, Orca's Source Control list: Conflicts/// first, then Changes, Staged Changes and Untracked Files, each with its@@ -53,7 +54,7 @@ class _FinderChangesViewState extends State<FinderChangesView> {message: 'Everything here matches the last commit.',compact: true,),- FinderLoaded(:final value?) => ListView(+ FinderLoaded(:final value?) => LaidOutListView(key: const ValueKey('finder-changes'),padding: const EdgeInsets.symmetric(vertical: 4),children: [diff --git a/desktop/lib/finder/widgets/finder_tab_bar.dart b/desktop/lib/finder/widgets/finder_tab_bar.dartindex 84193ab47..07b461ce8 100644--- a/desktop/lib/finder/widgets/finder_tab_bar.dart+++ b/desktop/lib/finder/widgets/finder_tab_bar.dart@@ -8,6 +8,7 @@ import '../../theme/app_theme.dart';import '../finder_models.dart';import '../finder_tabs.dart';import 'finder_click.dart';+import '../../widgets/laid_out_list.dart';/// The open tabs, as Orca's tab bar draws them: a preview tab in italics/// (the next single click replaces it), a dot for unsaved edits that turns@@ -24,7 +25,7 @@ class FinderTabBar extends StatelessWidget {grid.AppTheme.watch(context);return SizedBox(height: 32,- child: ListView(+ child: LaidOutListView(scrollDirection: Axis.horizontal,children: [for (final tab in tabs.tabs)diff --git a/desktop/lib/orchestrator/orchestrator_workspace.dart b/desktop/lib/orchestrator/orchestrator_workspace.dartindex 7f571e285..670743b4f 100644--- a/desktop/lib/orchestrator/orchestrator_workspace.dart+++ b/desktop/lib/orchestrator/orchestrator_workspace.dart@@ -12,6 +12,7 @@ import '../state/terminal_pane.dart';import '../widgets/web_pane_panel.dart';import 'orchestrator_controller.dart';import 'orchestrator_launcher.dart';+import '../widgets/laid_out_list.dart';class OrchestratorWorkspace extends StatefulWidget {const OrchestratorWorkspace({@@ -452,7 +453,7 @@ class _OrchestratorWorkspaceState extends State<OrchestratorWorkspace> {),Expanded(child: SelectionArea(- child: ListView.builder(+ child: LaidOutListView.builder(key: const ValueKey('orchestrator-conversation'),controller: _messagesScroll,padding: const EdgeInsets.all(18),diff --git a/desktop/lib/settings/sections/connectors_section.dart b/desktop/lib/settings/sections/connectors_section.dartindex d83088b4d..d340d11e0 100644--- a/desktop/lib/settings/sections/connectors_section.dart+++ b/desktop/lib/settings/sections/connectors_section.dart@@ -13,6 +13,7 @@ import '../../shared/widgets/section_scaffold.dart';import '../../shared/widgets/toolbar_pill.dart';import '../../state/app_state.dart';import '../../widgets/restart_agent_action.dart';+import '../../widgets/laid_out_list.dart';/// Settings ▸ Connectors: connect a service once on this computer, and every/// local agent (Claude Code, Codex, OpenCode) gets it. The same list and@@ -175,7 +176,7 @@ class _ConnectorsSectionState extends State<ConnectorsSection> {Expanded(child: _controller.cards.isEmpty && _controller.loading? const Center(child: Text('Loading connectors…'))- : ListView(+ : LaidOutListView(children: [_group(context, 'Connected', on,query.isEmpty ? 'Nothing connected yet. Choose a service below.' : 'No connected service matches.'),diff --git a/desktop/lib/settings/sections/debug_section.dart b/desktop/lib/settings/sections/debug_section.dartindex d9dad553a..24acb1cdb 100644--- a/desktop/lib/settings/sections/debug_section.dart+++ b/desktop/lib/settings/sections/debug_section.dart@@ -12,6 +12,7 @@ import 'debug_filter_bar.dart';import 'debug_log_tile.dart';import 'debug_paths_card.dart';import 'debug_toolbar.dart';+import '../../widgets/laid_out_list.dart';/// Settings ▸ Debug — the app's own log, as this session still holds it.///@@ -205,7 +206,7 @@ class _DebugSectionState extends State<DebugSection> {Widget _list(bool nothingLogged, List<LogEntry> visible) {if (visible.isNotEmpty) {- return ListView.separated(+ return LaidOutListView.separated(itemCount: visible.length,separatorBuilder: (_, _) => const SizedBox(height: 6),itemBuilder: (context, i) => DebugLogTile(entry: visible[i]),diff --git a/desktop/lib/settings/sections/usage_section.dart b/desktop/lib/settings/sections/usage_section.dartindex eca8466cf..c90afae6d 100644--- a/desktop/lib/settings/sections/usage_section.dart+++ b/desktop/lib/settings/sections/usage_section.dart@@ -40,6 +40,7 @@ import 'usage_panels.dart';import 'usage_header.dart';import 'usage_provider_pane.dart';import 'usage_subscriptions.dart';+import '../../widgets/laid_out_list.dart';/// What the overview opens on — the last 30 days, which is what Orca's default/// range shows and therefore what a figure here can be compared against.@@ -157,7 +158,7 @@ class _UsageSectionState extends State<UsageSection> {}Widget _body(BuildContext context) {- return ListView(+ return LaidOutListView(padding: EdgeInsets.zero,children: [StatsSummaryCards(summary: _stats.summary),diff --git a/desktop/lib/settings/sections/usage_subscriptions.dart b/desktop/lib/settings/sections/usage_subscriptions.dartindex 24cb03cf0..e47ec9c3c 100644--- a/desktop/lib/settings/sections/usage_subscriptions.dart+++ b/desktop/lib/settings/sections/usage_subscriptions.dart@@ -8,6 +8,7 @@ import '../../shared/widgets/empty_state.dart';import '../../shared/widgets/setting_row.dart';import '../../usage/models_menu_controller.dart';import '../../widgets/workspace_subscription_usage.dart';+import '../../widgets/laid_out_list.dart';/// Settings ▸ Usage in a browser: the account's Claude Code and Codex/// subscriptions, read from its computers as the footer reads them. A browser@@ -45,7 +46,7 @@ class _UsageSubscriptionsState extends State<UsageSubscriptions> {'computers is online and signed in to them.',);}- return ListView(+ return LaidOutListView(padding: EdgeInsets.zero,children: [for (final account in accounts)diff --git a/desktop/lib/settings/settings_nav.dart b/desktop/lib/settings/settings_nav.dartindex 287fc9261..4467eea1f 100644--- a/desktop/lib/settings/settings_nav.dart+++ b/desktop/lib/settings/settings_nav.dart@@ -8,6 +8,7 @@ import '../shared/theme/app_theme.dart' as grid;import '../shared/widgets/section_scaffold.dart';import '../widgets/finger_target.dart';import 'settings_section.dart';+import '../widgets/laid_out_list.dart';/// The settings list: the way back, a field that narrows the list to what you/// type, then one row per screen with the open one highlighted.@@ -193,7 +194,7 @@ class _SettingsNavState extends State<SettingsNav> {Widget _navList() {final visible = _visible;if (visible.isEmpty) return const _NoMatches();- return ListView(+ return LaidOutListView(padding: const EdgeInsets.only(bottom: 10),children: [for (final group in visible) ...[diff --git a/desktop/lib/sharing/harness_comments.dart b/desktop/lib/sharing/harness_comments.dartindex e382220f2..9b87d1c35 100644--- a/desktop/lib/sharing/harness_comments.dart+++ b/desktop/lib/sharing/harness_comments.dart@@ -6,6 +6,7 @@ import 'package:flutter/material.dart';import '../shared/theme/app_theme.dart' as grid;import '../widgets/desktop_chrome.dart';import '../ws/ws_conn.dart';+import '../widgets/laid_out_list.dart';typedef CommentAction = Future<Map<String, dynamic>> Function(String action,@@ -241,7 +242,7 @@ class _HarnessCommentsState extends State<HarnessComments> {),);}- return ListView.separated(+ return LaidOutListView.separated(key: const ValueKey('comments-list'),primary: false,itemCount: _comments.length,diff --git a/desktop/lib/shortcuts/shortcuts_browser.dart b/desktop/lib/shortcuts/shortcuts_browser.dartindex 69eb65e1c..ce0a76b12 100644--- a/desktop/lib/shortcuts/shortcuts_browser.dart+++ b/desktop/lib/shortcuts/shortcuts_browser.dart@@ -15,6 +15,7 @@ import 'keymap.dart';import 'keymap_settings.dart';import 'keyboard_practice.dart';import 'shortcut_recorder.dart';+import '../widgets/laid_out_list.dart';/// Searchable help built from the same resolved bindings that handle input./// Shared by the shortcut dialog and Settings; no separate shortcut catalog.@@ -347,7 +348,7 @@ class _ShortcutsBrowserState extends State<ShortcutsBrowser> {: 1;return Scrollbar(controller: _scroll,- child: ListView(+ child: LaidOutListView(controller: _scroll,padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),children: [diff --git a/desktop/lib/store/store_screen.dart b/desktop/lib/store/store_screen.dartindex dd04dcc85..986b3dffa 100644--- a/desktop/lib/store/store_screen.dart+++ b/desktop/lib/store/store_screen.dart@@ -42,6 +42,7 @@ import 'store_search.dart';import 'store_sessions.dart';import 'store_showcase.dart';import 'store_viewers.dart';+import '../widgets/laid_out_list.dart';/// The Harness Store, the content of its tab: every harness the registry/// knows and every built-in engine, as a shelf of cards; one becomes its page@@ -723,7 +724,7 @@ class _StoreNav extends StatelessWidget {child: Column(children: [Expanded(- child: ListView(+ child: LaidOutListView(padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 22),children: [for (final choice in of(_ShelfKind.browse))diff --git a/desktop/lib/store/store_viewers.dart b/desktop/lib/store/store_viewers.dartindex 9ae3c9199..37ae9d7c3 100644--- a/desktop/lib/store/store_viewers.dart+++ b/desktop/lib/store/store_viewers.dart@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';import '../core/dsh_catalog.dart';import '../shared/theme/app_theme.dart' as grid;import 'store_host.dart';+import '../widgets/laid_out_list.dart';/// Shared packages are inspected here, separately from browsing harnesses.class StoreViewers extends StatelessWidget {@@ -24,7 +25,7 @@ class StoreViewers extends StatelessWidget {@overrideWidget build(BuildContext context) {- return ListView(+ return LaidOutListView(key: const ValueKey('store-viewers'),padding: const EdgeInsets.all(28),children: [diff --git a/desktop/lib/super_tabs/account_keys.dart b/desktop/lib/super_tabs/account_keys.dartindex c14406f55..910ccd2c6 100644--- a/desktop/lib/super_tabs/account_keys.dart+++ b/desktop/lib/super_tabs/account_keys.dart@@ -10,6 +10,7 @@ import '../core/local_key_value_store.dart';/// or New Project;/// - `super_tab.hidden.<account>`: the Swarms hidden on this browser;/// - `super_tab.personal.<account>`: the Swarm last chosen in the switcher;+/// - `super_tab.scope.<account>.<swarm>`: whether the roster lists the whole Swarm or the open project;/// - `super_tab.repos.<account>`: the projects made for their repos in their/// Personal Swarm (personal_projects.dart)./// The saved views' own keys (`super_tab.view…`, `super_tab.saved_by`) are@@ -19,6 +20,7 @@ String? swarmKeyAccount(String key) {final parts = key.substring('super_tab.'.length).split('.');return switch (parts) {['launch', final account, _, ...] => account,+ ['scope', final account, _] => account,['hidden' || 'personal' || 'repos', final account] => account,['view' || 'views' || 'saved_by' || 'signed_out', ...] => null,[final account, _] => account,diff --git a/desktop/lib/super_tabs/leaderboard/model.dart b/desktop/lib/super_tabs/leaderboard/model.dartindex 7878bde5c..57bfa5260 100644--- a/desktop/lib/super_tabs/leaderboard/model.dart+++ b/desktop/lib/super_tabs/leaderboard/model.dart@@ -14,11 +14,34 @@ List<Map<String, dynamic>> _list(Object? value) =>String? _text(Object? value) =>value is String && value.isNotEmpty ? value : null;+/// The rolling periods the board offers, the default in the middle (Dee,+/// 2026-11-02).+const leaderboardPeriods = ['24h', '7d', '30d'];+const leaderboardDefaultPeriod = '7d';++/// "Last 7d": a period in the menu.+String leaderboardPeriodLabel(String period) => 'Last $period';++String _periodLength(String period) => switch (period) {+ '24h' => '24 hours',+ '30d' => '30 days',+ _ => '7 days',+};+class SuperTabLeaderboard {SuperTabLeaderboard.fromJson(Map<String, dynamic> json): projectId = json['projectId'] as String? ?? '',week = _int(json['week']),- people = _list(json['people']).map(SuperTabPersonScore.fromJson).toList(),+ period = _text(_map(json['period'])['name']),+ allProjects = json['allProjects'] == true,+ people = _list(json['people'])+ .map(+ (row) => SuperTabPersonScore.fromJson(+ row,+ period: _text(_map(json['period'])['name']),+ ),+ )+ .toList(),waiting = SuperTabWaiting.fromJson(_map(json['waiting'])),agents = _list(json['agents']).map(SuperTabAgentScore.fromJson).toList(),byModel = _list(json['byModel'])@@ -35,6 +58,17 @@ class SuperTabLeaderboard {/// The week's Monday 00:00 UTC, in epoch milliseconds.final int week;+ /// The rolling period this sums; null from a server that sums weeks.+ final String? period;++ /// Sums every project the reader may read, not only [projectId], and lists+ /// everyone in the Swarm: the roster's All projects.+ final bool allProjects;++ /// "in the last 7 days"; null for a week, which goes by its own name.+ String? get spanName =>+ period == null ? null : 'in the last ${_periodLength(period!)}';+/// Most points first.final List<SuperTabPersonScore> people;final SuperTabWaiting waiting;@@ -125,8 +159,14 @@ class SuperTabModelScore {}class SuperTabPersonScore {- SuperTabPersonScore.fromJson(Map<String, dynamic> json)- : personId = json['personId'] as String? ?? '',+ SuperTabPersonScore.fromJson(Map<String, dynamic> json, {String? period})+ : spanName = period == null+ ? 'this week'+ : 'in the last ${_periodLength(period)}',+ earlierName = period == null+ ? 'last week'+ : 'the ${_periodLength(period)} before',+ personId = json['personId'] as String? ?? '',points = _int(json['points']),rank = _int(json['rank']),medal = SuperTabMedal.values.asNameMap()[json['medal']],@@ -144,6 +184,10 @@ class SuperTabPersonScore {? SuperTabPersonDetails.fromJson(_map(json['details'])): null;+ /// What [points] covers and what [prevWeekPoints] covers, as a sentence+ /// says them: "in the last 7 days", "the 7 days before".+ final String spanName, earlierName;+final String personId;final int points, rank;final SuperTabMedal? medal;@@ -156,7 +200,8 @@ class SuperTabPersonScore {/// The profile name, else the email's local part; null from a server before names.final String? displayName;- /// The same scoring for the week before; null from a server before it.+ /// The same scoring for the time before; null from a server before it, and+ /// for Last 30d, which has no comparison.final int? prevWeekPoints;/// What the numbers are made of; null from a server before details.diff --git a/desktop/lib/super_tabs/leaderboard/person_row.dart b/desktop/lib/super_tabs/leaderboard/person_row.dartindex b7e4fb58d..179c026f0 100644--- a/desktop/lib/super_tabs/leaderboard/person_row.dart+++ b/desktop/lib/super_tabs/leaderboard/person_row.dart@@ -277,8 +277,8 @@ class LeaderboardPersonWeek extends StatelessWidget {('Points',score.medal == null- ? '${score.points} this week'- : '${score.points} this week · place ${score.rank}',+ ? '${score.points} ${score.spanName}'+ : '${score.points} ${score.spanName} · place ${score.rank}',),('Shipped',@@ -439,8 +439,8 @@ class _LeaderboardPersonDetailsState extends State<_LeaderboardPersonDetails> {children: [Text([- '${plural(score.points, 'point')} this week',- if (before != null) '$before last week',+ '${plural(score.points, 'point')} ${score.spanName}',+ if (before != null) '$before ${score.earlierName}',].join(' · '),style: quiet,),diff --git a/desktop/lib/super_tabs/leaderboard/reader.dart b/desktop/lib/super_tabs/leaderboard/reader.dartindex d5cd818b8..5fe568ddc 100644--- a/desktop/lib/super_tabs/leaderboard/reader.dart+++ b/desktop/lib/super_tabs/leaderboard/reader.dart@@ -23,6 +23,9 @@ class SuperTabLeaderboardReader extends ChangeNotifier {String? error;String? _projectId;int? _week;+ String _period = leaderboardDefaultPeriod;+ bool _weeksOnly = false;+ bool _allProjects = true;int _read = 0;Timer? _timer;bool _disposed = false;@@ -30,6 +33,34 @@ class SuperTabLeaderboardReader extends ChangeNotifier {/// The Monday 00:00 UTC of the week shown; null for this week.int? get week => _week;+ /// The rolling period shown; null while the server only sums weeks (a+ /// server before periods), which keeps the week menu. Told once per reader:+ /// a server that is upgraded later is seen on the next launch.+ String? get period => _weeksOnly ? null : _period;++ /// Sums every project the reader may read, or only the one shown: the+ /// roster's scope, All projects by default. A server before periods sums+ /// only the one shown.+ Future<void> showAllProjects(bool allProjects) {+ if (allProjects == _allProjects) return Future.value();+ _allProjects = allProjects;+ // Whole-Swarm numbers under one project's name would mislead, and its+ // list of people would say who is in the project.+ board = null;+ _notify();+ return refresh();+ }++ /// Shows another rolling period.+ Future<void> showPeriod(String period) {+ if (period == _period) return Future.value();+ _period = period;+ // Another period's numbers under this one's name would mislead.+ board = null;+ _notify();+ return refresh();+ }+/// Shows another week, null for this one.Future<void> showWeek(int? week) {if (week == _week) return Future.value();@@ -71,19 +102,31 @@ class SuperTabLeaderboardReader extends ChangeNotifier {Future<void> refresh() async {final projectId = _projectId;if (projectId == null || _disposed) return;- final read = ++_read, week = _week;+ final read = ++_read, week = _week, period = this.period;+ final allProjects = _allProjects;try {final answer = await request('GET','/api/super-tabs/${Uri.encodeComponent(tabId)}/leaderboard''?projectId=${Uri.encodeQueryComponent(projectId)}'- '${week == null ? '' : '&week=$week'}',+ '${period != null+ ? '&period=$period${allProjects ? '&scope=all' : ''}'+ : week == null+ ? ''+ : '&week=$week'}',);if (read != _read) return;board = SuperTabLeaderboard.fromJson(answer);+ if (board!.period == null) _weeksOnly = true;error = null;} on SuperTabFailure catch (failure) {if (read != _read) return;+ // A server before periods refuses the question, and only that one: any+ // other failure, however early, leaves the periods on for the next read.+ if (failure.statusCode == 400 && period != null) {+ _weeksOnly = true;+ return refresh();+ }// A server from before the leaderboard has none: Humans just list names.// A project the reader may no longer read is forgotten alike, its// numbers and the server's words about it.diff --git a/desktop/lib/super_tabs/roster.dart b/desktop/lib/super_tabs/roster.dartindex 9e0ad6e51..00da3d233 100644--- a/desktop/lib/super_tabs/roster.dart+++ b/desktop/lib/super_tabs/roster.dart@@ -3,6 +3,7 @@ import 'dart:async';import 'package:collection/collection.dart' show mergeSort;import 'package:flutter/material.dart';+import '../core/local_key_value_store.dart';import '../core/relative_time.dart';import '../shared/theme/app_theme.dart' as grid;@@ -28,6 +29,7 @@ import 'leaderboard/reader.dart';import 'leaderboard/waiting_line.dart';import 'model.dart';import 'profile_sheet.dart';+import 'roster_scope.dart';import 'section_heading.dart';import 'agent_line.dart';import '../widgets/laid_out_list.dart';@@ -46,6 +48,7 @@ class SuperTabRoster extends StatefulWidget {required this.onAnswer,this.app,this.board,+ this.storage,this.now = DateTime.now,});final SuperTabController controller;@@ -61,6 +64,10 @@ class SuperTabRoster extends StatefulWidget {/// The open project's week board, shared with the sidebar's Models; the/// roster reads its own when not given.final SuperTabLeaderboardReader? board;++ /// Where the scope choice is kept on this computer; kept for this visit+ /// only when null.+ final LocalKeyValueStore? storage;final DateTime Function() now;@overrideState<SuperTabRoster> createState() => _SuperTabRosterState();@@ -74,13 +81,60 @@ class _SuperTabRosterState extends State<SuperTabRoster> {late final SuperTabLeaderboardReader _board =widget.board ?? (_ownBoard = SuperTabProjectBoard(c));+ /// Whole Swarm or the open project, remembered per account and Swarm.+ late final _choice = SuperTabRosterScopeChoice(+ storage: widget.storage,+ accountId: c.accountId,+ tabId: c.tabId,+ );+/// One tick for the whole list, so ages and leases stay true on a quiet/// Swarm (review of #2281); a change in the Swarm rebuilds it anyway.Timer? _tick;+ /// The project the list is narrowed to now, so its loss is told from the+ /// person simply opening another project's chat.+ String? _scopedId;++ /// The scope follows the project open in the chat. A project that leaves+ /// the Swarm the reader sees (access revoked, deleted) while it is the one+ /// narrowing the list puts the choice back on All projects, and saves that,+ /// rather than carrying it over to whichever project opens next.+ void _scopeMoved() {+ _followScope();+ if (_choice.scope != SuperTabRosterScope.project) {+ _scopedId = null;+ return;+ }+ final state = c.snapshot;+ final last = _scopedId;+ if (last != null && state != null && state.projectById(last) == null) {+ _scopedId = null;+ _choice.choose(SuperTabRosterScope.all);+ return;+ }+ final open = c.selected?.projectId;+ if (open != null && open.isNotEmpty && state?.projectById(open) != null) {+ _scopedId = open;+ }+ }++ /// The board sums what the list shows: every readable project under All+ /// projects, the open one under its own name.+ void _followScope() => unawaited(+ _board.showAllProjects(_choice.scope == SuperTabRosterScope.all),+ );+@overridevoid initState() {super.initState();+ c.addListener(_scopeMoved);+ _choice.addListener(_scopeMoved);+ // A board shared with a roster of an earlier visit follows this one, after+ // this build: others are listening to it.+ scheduleMicrotask(() {+ if (mounted) _followScope();+ });_tick = Timer.periodic(const Duration(seconds: 30),(_) => mounted ? setState(() {}) : null,@@ -90,7 +144,10 @@ class _SuperTabRosterState extends State<SuperTabRoster> {@overridevoid dispose() {_tick?.cancel();+ c.removeListener(_scopeMoved);+ _choice.removeListener(_scopeMoved);_ownBoard?.dispose();+ _choice.dispose();super.dispose();}@@ -482,17 +539,44 @@ class _SuperTabRosterState extends State<SuperTabRoster> {: c.selected?.projectId;// Who reads a private conversation still decides its +, never the list.final audience = c.selected?.audience;+ // The project the list is narrowed to, only while the person chose it and+ // a project they can read is open; otherwise the whole Swarm (Dee,+ // 2026-11-02). Read from the live snapshot, so a project that is gone or+ // no longer readable never narrows anything.+ final scoped =+ _choice.scope == SuperTabRosterScope.project && projectId != null+ ? state?.projectById(projectId)+ : null;final members = state?.teamAgents ?? const <SuperTabAgent>[];- final leads = members.where((a) => state!.isLead(a.id)).toList();- final agents = members.where((a) => !state!.isLead(a.id)).toList();- final people = state?.people ?? const <SuperTabPerson>[];+ bool inScope(SuperTabAgent a) =>+ scoped == null ||+ (state!.leadProjectForAgent(a.id)?.id ?? _agentProjectId(a)) ==+ scoped.id;+ final leads = members+ .where((a) => state!.isLead(a.id) && inScope(a))+ .toList();+ final agents = members+ .where((a) => !state!.isLead(a.id) && inScope(a))+ .toList();// Only the open project's board: an answer for any other never lends// its numbers to these rows.final board = switch (_board.board) {- final board? when projectId != null && board.projectId == projectId =>+ // Nor numbers of another scope: a whole-Swarm board says nothing of who+ // is in this project. A board of a week is the open project's alone.+ final board?+ when projectId != null &&+ board.projectId == projectId &&+ (board.period == null ||+ board.allProjects ==+ (_choice.scope == SuperTabRosterScope.all)) =>board,_ => null,};+ final people = [+ for (final person in state?.people ?? const <SuperTabPerson>[])+ if (scoped == null || personInProject(scoped, person.id, board: board))+ person,+ ];final scores = {for (final score in board?.people ?? const []) score.personId: score,};@@ -542,35 +626,83 @@ class _SuperTabRosterState extends State<SuperTabRoster> {context,points: board.people.map((s) => s.points),);- final week = weekName(_board.week, current);+ final week = board?.spanName ?? weekName(_board.week, current);+ final openProject = projectId == null+ ? null+ : state?.projectById(projectId);+ final showWeek =+ board != null ||+ _board.week != null ||+ (_board.period ?? leaderboardDefaultPeriod) != leaderboardDefaultPeriod;+ Widget weekSelect({double? width}) => switch (_board.period) {+ final period? => AppSelectField<String>(+ key: const ValueKey('leaderboard-period'),+ value: period,+ width: width,+ height: DesktopChrome.compactControlHeight,+ semanticLabel: 'Period',+ options: [+ for (final option in leaderboardPeriods)+ SelectOption(value: option, label: leaderboardPeriodLabel(option)),+ ],+ onChanged: (period) => unawaited(_board.showPeriod(period)),+ ),+ // A server before periods keeps the weeks.+ null => AppSelectField<int>(+ key: const ValueKey('leaderboard-week'),+ value: _board.week ?? current,+ width: width,+ height: DesktopChrome.compactControlHeight,+ semanticLabel: 'Week',+ options: [+ for (var back = 0; back < 4; back++)+ SelectOption(+ value: current - back * weekMs,+ label: capitalized(weekName(current - back * weekMs, current)),+ ),+ ],+ onChanged: (week) =>+ unawaited(_board.showWeek(week == current ? null : week)),+ ),+ };return [// Humans and Agents: the two roles in one team (Dee, 2026-10-29).SuperTabSectionHeading('Humans',- actions: [- if (board != null || _board.week != null)- AppSelectField<int>(- key: const ValueKey('leaderboard-week'),- value: _board.week ?? current,- width: 112,- height: DesktopChrome.compactControlHeight,- semanticLabel: 'Week',- options: [- for (var back = 0; back < 4; back++)- SelectOption(- value: current - back * weekMs,- label: capitalized(- weekName(current - back * weekMs, current),- ),- ),- ],- onChanged: (week) =>- unawaited(_board.showWeek(week == current ? null : week)),- ),- ],+ actions: [if (showWeek) weekSelect(width: 112)],onAdd: c.isOwner ? widget.onInvite : null,addTooltip: 'Invite people',),+ if (openProject != null)+ Padding(+ padding: const EdgeInsets.fromLTRB(+ DesktopChrome.groupGap,+ 0,+ DesktopChrome.groupGap,+ DesktopChrome.controlGap,+ ),+ // The pane is too narrow for the scope beside the week on the+ // heading's line, so it takes the line below.+ child: AppSelectField<SuperTabRosterScope>(+ key: const ValueKey('roster-scope'),+ value: scoped == null+ ? SuperTabRosterScope.all+ : SuperTabRosterScope.project,+ height: DesktopChrome.compactControlHeight,+ semanticLabel: 'Show',+ options: [+ const SelectOption(+ value: SuperTabRosterScope.all,+ label: 'All projects',+ ),+ SelectOption(+ value: SuperTabRosterScope.project,+ label: openProject.name,+ ),+ ],+ onChanged: _choice.choose,+ ),+ ),if (_board.error case final error?)Padding(padding: const EdgeInsets.fromLTRB(@@ -624,6 +756,7 @@ class _SuperTabRosterState extends State<SuperTabRoster> {listenable: Listenable.merge([c,_board,+ _choice,if (widget.app != null) ...[widget.app!, widget.app!.agentUnread],terminalThemeStore,appearancePrefsStore,diff --git a/desktop/lib/super_tabs/roster_scope.dart b/desktop/lib/super_tabs/roster_scope.dartnew file mode 100644index 000000000..6f64a8db1--- /dev/null+++ b/desktop/lib/super_tabs/roster_scope.dart@@ -0,0 +1,92 @@+import 'dart:async';++import 'package:flutter/foundation.dart';++import '../core/local_key_value_store.dart';+import 'leaderboard/model.dart';+import 'model.dart';++/// Which people and agents the right pane lists (Dee, 2026-11-02): the whole+/// Swarm, as before, or only the project open in the chat.+enum SuperTabRosterScope { all, project }++/// The roster's scope choice, kept per account and Swarm on this computer.+///+/// It stores only the choice, never a project's id, name or members: the+/// project it applies to is always the one open now, read from the controller's+/// own snapshot, so a project the reader can no longer read is simply not+/// there and the list falls back to the whole Swarm.+class SuperTabRosterScopeChoice extends ChangeNotifier {+ SuperTabRosterScopeChoice({+ required this.storage,+ required this.accountId,+ required this.tabId,+ }) {+ unawaited(_restore());+ }++ final LocalKeyValueStore? storage;+ final String accountId, tabId;++ /// What `swarmKeyAccount` sweeps with the account's other keys at sign-out.+ static String keyFor(String accountId, String tabId) =>+ 'super_tab.scope.$accountId.$tabId';++ SuperTabRosterScope _scope = SuperTabRosterScope.all;+ int _edit = 0;+ Future<void> _writing = Future.value();+ bool _disposed = false;++ SuperTabRosterScope get scope => _scope;++ Future<void> _restore() async {+ final edit = ++_edit, store = storage;+ if (store == null) return;+ try {+ final raw = await store.read(keyFor(accountId, tabId));+ // A choice made while this read was out wins; so does a disposal.+ if (_disposed || edit != _edit) return;+ final scope = SuperTabRosterScope.values.asNameMap()[raw];+ if (scope == null || scope == _scope) return;+ _scope = scope;+ notifyListeners();+ } catch (_) {+ // An unreadable preference leaves the whole Swarm, the default.+ }+ }++ void choose(SuperTabRosterScope scope) {+ if (_disposed || scope == _scope) return;+ _edit++;+ _scope = scope;+ notifyListeners();+ final store = storage;+ if (store == null) return;+ final key = keyFor(accountId, tabId), value = scope.name;+ _writing = _writing+ .then((_) => store.write(key, value))+ .catchError((Object _) {});+ }++ @override+ void dispose() {+ _disposed = true;+ super.dispose();+ }+}++/// Whether [personId] belongs to [project] as far as this reader can tell.+/// The open project's board names exactly the people who can read it; before+/// that board lands, or when it failed, a private project is its owner and+/// invited members, and a public one is everyone in the Swarm.+bool personInProject(+ SuperTabProject project,+ String personId, {+ SuperTabLeaderboard? board,+}) {+ if (board != null && board.projectId == project.id) {+ return board.people.any((score) => score.personId == personId);+ }+ if (!project.isPrivate) return true;+ return project.ownerId == personId || project.memberIds.contains(personId);+}diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 9fb053832..d873446a0 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -3991,6 +3991,7 @@ class _SuperTabViewState extends State<SuperTabView>controller: c,app: widget.app,board: _board,+ storage: widget.app?.localStore,onInvite: widget.onInvite,onOpenAgent: (agent) {setState(() {diff --git a/desktop/lib/widgets/laid_out_list.dart b/desktop/lib/widgets/laid_out_list.dartindex 90a2e049a..cf2509440 100644--- a/desktop/lib/widgets/laid_out_list.dart+++ b/desktop/lib/widgets/laid_out_list.dart@@ -51,6 +51,25 @@ class LaidOutListView extends ListView {super.clipBehavior,}) : super.builder();+ LaidOutListView.separated({+ super.key,+ super.scrollDirection,+ super.reverse,+ super.controller,+ super.primary,+ super.physics,+ super.shrinkWrap,+ super.padding,+ required super.itemBuilder,+ required super.separatorBuilder,+ required super.itemCount,+ super.findChildIndexCallback,+ super.scrollCacheExtent,+ super.keyboardDismissBehavior,+ super.restorationId,+ super.clipBehavior,+ }) : super.separated();+@overrideWidget buildChildLayout(BuildContext context) =>LaidOutSliverList(delegate: childrenDelegate);diff --git a/desktop/test/laid_out_list_test.dart b/desktop/test/laid_out_list_test.dartindex c89783a8e..df515ad55 100644--- a/desktop/test/laid_out_list_test.dart+++ b/desktop/test/laid_out_list_test.dart@@ -147,6 +147,49 @@ void main() {expect(find.text('row 112'), findsWidgets);});+ testWidgets('a separated list leaving as its tooltip opens stays safe', (+ tester,+ ) async {+ final controller = ScrollController(initialScrollOffset: 4000);+ addTearDown(controller.dispose);+ await tester.pumpWidget(+ _frame(+ LaidOutListView.separated(+ controller: controller,+ itemCount: 200,+ itemBuilder: (context, i) => _row(i),+ separatorBuilder: (context, i) => const SizedBox.shrink(),+ ),+ ),+ );+ final mouse = await _openTooltipAsRowLeaves(tester, controller);+ expect(tester.takeException(), isNull);+ await mouse.moveTo(const Offset(5, 100));+ expect(tester.takeException(), isNull);+ });++ testWidgets('a grid is safe as a plain GridView', (tester) async {+ final controller = ScrollController(initialScrollOffset: 4000);+ addTearDown(controller.dispose);+ await tester.pumpWidget(+ _frame(+ GridView.builder(+ controller: controller,+ gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(+ crossAxisCount: 1,+ mainAxisExtent: _rowHeight,+ ),+ itemCount: 200,+ itemBuilder: (context, i) => _row(i),+ ),+ ),+ );+ final mouse = await _openTooltipAsRowLeaves(tester, controller);+ expect(tester.takeException(), isNull);+ await mouse.moveTo(const Offset(5, 100));+ expect(tester.takeException(), isNull);+ });+testWidgets('a list with an item extent is safe as a plain ListView', (tester,) async {@@ -169,32 +212,32 @@ void main() {});});- test(- 'Swarm lists use LaidOutListView unless their rows are tightly sized',- () {- final bare = RegExp(r'(?<![\w.<])(ListView(\.builder)?|SliverList)\(');- final offenders = <String>[];- for (final dir in ['lib/super_tabs', 'lib/widgets']) {- for (final file in Directory(dir).listSync(recursive: true)) {- if (file is! File || !file.path.endsWith('.dart')) continue;- if (file.path.endsWith('laid_out_list.dart')) continue;- final source = file.readAsStringSync();- for (final match in bare.allMatches(source)) {- var depth = 0;- var end = match.end - 1;- do {- if (source[end] == '(') depth++;- if (source[end] == ')') depth--;- end++;- } while (depth > 0 && end < source.length);- final call = source.substring(match.start, end);- if (!call.contains('itemExtent')) {- offenders.add('${file.path}: ${match.group(0)}');- }+ test('Lists use LaidOutListView unless their rows are tightly sized', () {+ final bare = RegExp(+ r'(?<![\w.<])(ListView(\.builder|\.separated|\.custom)?'+ r'|SliverList(\.builder|\.list|\.separated)?)\(',+ );+ final offenders = <String>[];+ for (final dir in ['lib']) {+ for (final file in Directory(dir).listSync(recursive: true)) {+ if (file is! File || !file.path.endsWith('.dart')) continue;+ if (file.path.endsWith('laid_out_list.dart')) continue;+ final source = file.readAsStringSync();+ for (final match in bare.allMatches(source)) {+ var depth = 0;+ var end = match.end - 1;+ do {+ if (source[end] == '(') depth++;+ if (source[end] == ')') depth--;+ end++;+ } while (depth > 0 && end < source.length);+ final call = source.substring(match.start, end);+ if (!call.contains('itemExtent')) {+ offenders.add('${file.path}: ${match.group(0)}');}}}- expect(offenders, isEmpty);- },- );+ }+ expect(offenders, isEmpty);+ });}diff --git a/desktop/test/settings_review_render_test.dart b/desktop/test/settings_review_render_test.dartindex c5aeadc0b..a8b01a900 100644--- a/desktop/test/settings_review_render_test.dart+++ b/desktop/test/settings_review_render_test.dart@@ -25,6 +25,7 @@ import 'package:harness/update/desktop_updater.dart';import 'package:harness/update/manual_update_check.dart';import 'package:harness/widgets/shortcuts_sheet.dart';import 'package:harness/widgets/update_notice.dart';+import 'package:harness/widgets/laid_out_list.dart';import 'support/experimental_settings.dart';import 'support/real_fonts.dart';@@ -264,7 +265,7 @@ void main() {200,scrollable: find.descendant(- of: find.byType(ListView),+ of: find.byType(LaidOutListView),matching: find.byType(Scrollable),).last,diff --git a/desktop/test/shortcuts_browser_test.dart b/desktop/test/shortcuts_browser_test.dartindex 3a1fde2f3..561b0fe62 100644--- a/desktop/test/shortcuts_browser_test.dart+++ b/desktop/test/shortcuts_browser_test.dart@@ -12,6 +12,7 @@ import 'package:harness/shortcuts/shortcuts_browser.dart';import 'package:harness/shared/theme/app_theme.dart' as grid;import 'package:harness/shortcuts/key_cap.dart';import 'package:harness/terminal/terminal_text.dart';+import 'package:harness/widgets/laid_out_list.dart';import 'package:xterm/xterm.dart';import 'keymap_host_test.dart' show key;@@ -215,7 +216,7 @@ void main() {await key(tester, direction);await tester.pumpAndSettle();expect(selected, findsOneWidget);- final viewport = tester.getRect(find.byType(ListView));+ final viewport = tester.getRect(find.byType(LaidOutListView));expect(viewport.contains(tester.getCenter(selected)), isTrue);expect(tester.takeException(), isNull);}diff --git a/desktop/test/super_tab_humans_test.dart b/desktop/test/super_tab_humans_test.dartindex 5b3bad944..6f60a96e2 100644--- a/desktop/test/super_tab_humans_test.dart+++ b/desktop/test/super_tab_humans_test.dart@@ -866,7 +866,7 @@ void main() {final server = humansSwarm();final controller = await show(tester, server);expect(server.leaderboardReads, [- '/api/super-tabs/tab/leaderboard?projectId=lead',+ '/api/super-tabs/tab/leaderboard?projectId=lead&period=7d&scope=all',]);await close(tester, controller);});diff --git a/desktop/test/super_tab_leaderboard_test.dart b/desktop/test/super_tab_leaderboard_test.dartindex cb90c43ee..87075ccf6 100644--- a/desktop/test/super_tab_leaderboard_test.dart+++ b/desktop/test/super_tab_leaderboard_test.dart@@ -257,12 +257,178 @@ void main() {await reader.show('lead');await reader.showWeek(week - 7 * 86400000);expect(requests.paths, [- 'GET /api/super-tabs/tab%201/leaderboard?projectId=lead',+ // Answered as a server before periods answers: by week, from then on.+ 'GET /api/super-tabs/tab%201/leaderboard?projectId=lead&period=7d&scope=all','GET /api/super-tabs/tab%201/leaderboard?projectId=lead&week=${week - 7 * 86400000}',]);expect(reader.board?.week, week);});+ group('the rolling periods', () {+ Map<String, dynamic> rolling(String name, {bool all = true}) => {+ ...answer(),+ 'period': {'name': name, 'start': 1, 'end': 2},+ if (all) 'allProjects': true,+ };+ const older = SuperTabFailure(+ 'VALIDATION',+ 'Unrecognized key',+ statusCode: 400,+ );++ test(+ 'reads Last 7d of All projects first, and another by name',+ () async {+ final paths = <String>[];+ final reader = SuperTabLeaderboardReader(+ tabId: 't',+ request: (method, path, {body}) async {+ paths.add(path);+ return rolling(+ path.contains('period=30d') ? '30d' : '7d',+ all: path.contains('scope=all'),+ );+ },+ );+ addTearDown(reader.dispose);+ await reader.show('lead');+ expect(reader.period, '7d');+ expect(reader.board?.period, '7d');+ expect(reader.board?.allProjects, isTrue);+ var cleared = false;+ reader.addListener(() => cleared = cleared || reader.board == null);+ await reader.showPeriod('30d');+ expect(+ cleared,+ isTrue,+ reason: "another period's numbers never wear this one's name",+ );+ final narrowed = reader.showAllProjects(false);+ expect(+ reader.board,+ isNull,+ reason: 'whole-Swarm numbers under one project',+ );+ await narrowed;+ expect(reader.board?.allProjects, isFalse);+ expect(paths, [+ '/api/super-tabs/t/leaderboard?projectId=lead&period=7d&scope=all',+ '/api/super-tabs/t/leaderboard?projectId=lead&period=30d&scope=all',+ '/api/super-tabs/t/leaderboard?projectId=lead&period=30d',+ ]);+ },+ );++ test('a server before periods keeps the weeks, after one refusal, and asks no scope', () async {+ final paths = <String>[];+ final reader = SuperTabLeaderboardReader(+ tabId: 't',+ request: (method, path, {body}) async {+ paths.add(path);+ if (path.contains('period=')) {+ throw older;+ }+ return answer();+ },+ );+ addTearDown(reader.dispose);+ await reader.show('lead');+ expect(reader.period, isNull);+ expect(reader.error, isNull);+ expect(reader.board?.week, week);+ await reader.refresh();+ expect(paths, [+ '/api/super-tabs/t/leaderboard?projectId=lead&period=7d&scope=all',+ '/api/super-tabs/t/leaderboard?projectId=lead',+ '/api/super-tabs/t/leaderboard?projectId=lead',+ ]);+ });++ test('a failed first read leaves the periods on, and recovers', () async {+ var fail = true;+ final reader = SuperTabLeaderboardReader(+ tabId: 't',+ request: (method, path, {body}) async {+ if (fail) {+ throw const SuperTabFailure(+ 'OFFLINE',+ 'No connection.',+ statusCode: 503,+ );+ }+ return rolling('7d');+ },+ );+ addTearDown(reader.dispose);+ await reader.show('lead');+ expect(reader.period, '7d');+ expect(reader.error, 'No connection.');+ fail = false;+ await reader.refresh();+ expect(reader.board?.period, '7d');+ expect(reader.error, isNull);+ });++ test('an answer or a refusal left behind changes nothing', () async {+ final slow = Completer<Map<String, dynamic>>(),+ refused = Completer<Map<String, dynamic>>();+ final reader = SuperTabLeaderboardReader(+ tabId: 't',+ request: (method, path, {body}) {+ if (path.contains('period=7d')) return slow.future;+ if (path.contains('period=24h')) return refused.future;+ return Future.value(rolling('30d'));+ },+ );+ addTearDown(reader.dispose);+ final first = reader.show('lead');+ final second = reader.showPeriod('24h');+ await reader.showPeriod('30d');+ slow.complete(rolling('7d'));+ refused.completeError(older);+ await first;+ await second;+ expect(reader.board?.period, '30d');+ expect(reader.period, '30d');+ });++ test(+ 'access lost: a read in flight is dropped and the board forgotten',+ () async {+ final slow = Completer<Map<String, dynamic>>();+ final reader = SuperTabLeaderboardReader(+ tabId: 't',+ request: (method, path, {body}) => slow.future,+ );+ addTearDown(reader.dispose);+ final first = reader.show('lead');+ reader.clear();+ slow.complete(rolling('7d'));+ await first;+ expect(reader.board, isNull);+ },+ );++ test('a period says itself in a person\'s words; a week as before', () {+ final score = SuperTabLeaderboard.fromJson(rolling('24h')).people.first;+ expect(score.spanName, 'in the last 24 hours');+ expect(score.earlierName, 'the 24 hours before');+ expect(+ SuperTabLeaderboard.fromJson(answer()).people.first.spanName,+ 'this week',+ );+ expect(+ SuperTabLeaderboard.fromJson(rolling('7d')).spanName,+ 'in the last 7 days',+ );+ expect(leaderboardPeriods.map(leaderboardPeriodLabel), [+ 'Last 24h',+ 'Last 7d',+ 'Last 30d',+ ]);+ });+ });+test('shows no numbers while another week is read, so one week never wears another\'s name', () async {final requests = FakeRequests();final pending = Completer<Map<String, dynamic>>();diff --git a/desktop/test/super_tab_roster_scope_test.dart b/desktop/test/super_tab_roster_scope_test.dartnew file mode 100644index 000000000..9d24ed655--- /dev/null+++ b/desktop/test/super_tab_roster_scope_test.dart@@ -0,0 +1,503 @@+import 'dart:async';+import 'dart:io';++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/local_key_value_store.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/account_keys.dart';+import 'package:harness/super_tabs/leaderboard/model.dart';+import 'package:harness/super_tabs/model.dart';+import 'package:harness/super_tabs/roster_scope.dart';++import 'super_tab_roster_test.dart' show RosterFixture;+import 'support/capture.dart';+import 'support/super_tab_fixture.dart' show projectFixture;++/// The roster's scope menu (Dee, 2026-11-02): the whole Swarm, or only the+/// project open in the chat, for Humans and Agents alike.+class _Memory implements LocalKeyValueStore {+ final values = <String, String>{};+ final writes = <String>[];++ /// Reads wait on this while set, as a slow disk does.+ Completer<void>? hold;+ bool failWrites = false;++ @override+ Future<String?> read(String key) async {+ // The value as it was when asked, however long the disk takes to answer.+ final value = values[key];+ await hold?.future;+ return value;+ }++ @override+ Future<void> write(String key, String value) async {+ if (failWrites) throw StateError('disk full');+ writes.add(key);+ values[key] = value;+ }++ @override+ Future<void> delete(String key) async => values.remove(key);+}++void main() {+ final captureDir = Platform.environment['HARNESS_ROSTER_CAPTURE_DIR'];+ setUpAll(() => loadCaptureFonts(captureDir));++ Finder person(String id) => find.byKey(ValueKey('super-person-$id'));+ Finder agent(int i) => find.byKey(ValueKey('super-member-agent-$i'));+ final scope = find.byKey(const ValueKey('roster-scope'));++ Map<String, dynamic> score(String id, int points, int rank) => {+ 'personId': id,+ 'points': points,+ 'rank': rank,+ 'medal': null,+ 'shipped': {'count': 0, 'medianAskToShipMs': null},+ 'unblocked': {'count': 0, 'agentMs': 0, 'medianAnswerMs': null},+ 'lent': {'machines': 0, 'agentMs': 0},+ 'streakDays': 0,+ };++ /// A Swarm of three people and two projects; only Ken and Dee can read+ /// openharness, Tony only autonomous-os (the board names the readers).+ Future<RosterFixture> swarm(+ WidgetTester tester, {+ _Memory? store,+ bool open = true,+ bool board = true,+ }) async {+ await tester.binding.setSurfaceSize(const Size(280, 760));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final f = RosterFixture();+ f.storage = store;+ await f.initialize();+ addTearDown(f.dispose);+ (f.server.state['people'] as List).addAll([+ {'id': 'dee', 'email': '[email protected]', 'role': 'collaborator'},+ {'id': 'tony', 'email': '[email protected]', 'role': 'collaborator'},+ ]);+ if (board) {+ f.server.leaderboard = {+ 'projectId': 'lead',+ 'week': DateTime.utc(2026, 10, 26).millisecondsSinceEpoch,+ 'people': [score('owner', 30, 1), score('dee', 12, 2)],+ 'waiting': {'total': 0, 'people': <Object>[]},+ };+ }+ await f.controller.refresh();+ if (open) await f.controller.select('lead');+ return f;+ }++ Future<void> choose(WidgetTester tester, String label) async {+ await tester.tap(scope);+ await tester.pumpAndSettle();+ await tester.tap(find.text(label).last);+ await tester.pumpAndSettle();+ }++ void expectWholeSwarm() {+ for (final id in ['owner', 'dee', 'tony']) {+ expect(person(id), findsOneWidget, reason: id);+ }+ for (var i = 0; i < 4; i++) {+ expect(agent(i), findsOneWidget, reason: 'agent-$i');+ }+ }++ testWidgets('starts on All projects: everyone and every agent, as before', (+ tester,+ ) async {+ final store = _Memory();+ final f = await swarm(tester, store: store);+ await f.show(tester);+ expectWholeSwarm();+ expect(+ find.descendant(of: scope, matching: find.text('All projects')),+ findsOneWidget,+ );+ expect(store.writes, isEmpty, reason: 'reading the default writes nothing');+ await f.close(tester);+ });++ testWidgets("the project's people and agents only, with its own points", (+ tester,+ ) async {+ final f = await swarm(tester);+ await f.show(tester);+ await choose(tester, 'openharness');+ // The board of openharness names Ken and Dee; Tony cannot read it.+ expect(person('owner'), findsOneWidget);+ expect(person('dee'), findsOneWidget);+ expect(person('tony'), findsNothing);+ expect(+ find.descendant(of: person('dee'), matching: find.textContaining('12')),+ findsWidgets,+ );+ // Its agents: the PM and two others; the other project's PM is not listed.+ expect(agent(0), findsOneWidget);+ expect(agent(1), findsOneWidget);+ expect(agent(3), findsOneWidget);+ expect(agent(2), findsNothing);+ // And back to everyone.+ await choose(tester, 'All projects');+ expectWholeSwarm();+ await f.close(tester);+ });++ testWidgets('another project open lists only its own agents, never the first '+ "project's board", (tester) async {+ final f = await swarm(tester);+ await f.show(tester);+ await choose(tester, 'openharness');+ await f.controller.select('os-lead');+ await tester.pumpAndSettle();+ // The scope follows the project now open: autonomous-os.+ expect(agent(2), findsOneWidget);+ expect(agent(0), findsNothing);+ expect(agent(1), findsNothing);+ expect(agent(3), findsNothing);+ // openharness's board never lends its Ken/Dee numbers or its member list+ // to this project (the board read is for the project open now).+ expect(+ f.server.leaderboardReads.last,+ contains('projectId=os'),+ reason: 'the board is re-read for the project now open',+ );+ await f.close(tester);+ });++ testWidgets(+ 'remembered per account and Swarm, and restored after a restart',+ (tester) async {+ final store = _Memory();+ final f = await swarm(tester, store: store);+ await f.show(tester);+ await choose(tester, 'openharness');+ final key = SuperTabRosterScopeChoice.keyFor('owner', f.controller.tabId);+ expect(store.values[key], 'project');+ // The web sweeps it with the account's other keys at sign-out.+ expect(swarmKeyAccount(key), 'owner');+ await f.close(tester);++ final again = await swarm(tester, store: store);+ await again.show(tester);+ expect(person('tony'), findsNothing);+ expect(agent(2), findsNothing);+ expect(+ find.descendant(of: scope, matching: find.text('openharness')),+ findsOneWidget,+ );+ await again.close(tester);++ // Another Swarm of the same account keeps its own choice.+ expect(+ SuperTabRosterScopeChoice.keyFor('owner', 'other-tab'),+ isNot(key),+ );+ },+ );++ testWidgets('a choice made while the saved one is still loading wins', (+ tester,+ ) async {+ final store = _Memory();+ store.values[SuperTabRosterScopeChoice.keyFor('owner', 'tab')] = 'project';+ store.hold = Completer<void>();+ final f = await swarm(tester, store: store);+ await f.show(tester);+ expect(f.controller.tabId, 'tab');+ // All projects is picked (the project is not saved yet), then the disk answers.+ await choose(tester, 'openharness');+ await choose(tester, 'All projects');+ store.hold!.complete();+ await tester.pumpAndSettle();+ expectWholeSwarm();+ expect(+ store.values[SuperTabRosterScopeChoice.keyFor('owner', 'tab')],+ 'all',+ );+ await f.close(tester);+ });++ testWidgets('a project you cannot read any more falls back to All projects', (+ tester,+ ) async {+ final store = _Memory();+ final f = await swarm(tester, store: store);+ await f.show(tester);+ await choose(tester, 'openharness');+ expect(person('tony'), findsNothing);+ // The Swarm stops sending the project and its chat (access revoked).+ (f.server.state['projects'] as List).removeWhere((p) => p['id'] == 'lead');+ (f.server.state['conversations'] as List).removeWhere(+ (g) => g['projectId'] == 'lead' || g['id'] == 'lead',+ );+ await f.controller.refresh();+ await tester.pumpAndSettle();+ for (final id in ['owner', 'dee', 'tony']) {+ expect(person(id), findsOneWidget, reason: id);+ }+ expect(+ find.text('openharness'),+ findsNothing,+ reason: 'no name left behind',+ );+ expect(scope, findsOneWidget);+ // The choice went back to All projects for good: it does not carry over to+ // the project the chat moved to, nor come back on its own.+ expect(agent(0), findsOneWidget);+ expect(agent(1), findsOneWidget);+ expect(agent(2), findsOneWidget);+ expect(agent(3), findsOneWidget);+ expect(+ store.values[SuperTabRosterScopeChoice.keyFor('owner', 'tab')],+ 'all',+ );+ await f.close(tester);+ });++ testWidgets('no project open: the whole Swarm, and no scope menu', (+ tester,+ ) async {+ final f = await swarm(tester, open: false);+ f.controller.selectedId = 'missing';+ await f.show(tester);+ expect(scope, findsNothing);+ expectWholeSwarm();+ await f.close(tester);+ });++ testWidgets(+ 'a failed board read does not strand the list: a public project keeps its people',+ (tester) async {+ final f = await swarm(tester, board: false);+ f.server.failLeaderboardReads = 1;+ await f.show(tester);+ await choose(tester, 'openharness');+ expect(person('owner'), findsOneWidget);+ expect(person('dee'), findsOneWidget);+ expect(person('tony'), findsOneWidget, reason: 'public: everyone');+ expect(agent(2), findsNothing);+ await f.close(tester);+ },+ );++ testWidgets(+ 'a failed board read on a private project lists only its owner and invited members',+ (tester) async {+ final f = await swarm(tester, board: false);+ final project = (f.server.state['projects'] as List).firstWhere(+ (p) => p['id'] == 'lead',+ );+ project['visibility'] = 'private';+ project['members'] = [+ {'id': 'dee'},+ ];+ await f.controller.refresh();+ await f.show(tester);+ await choose(tester, 'openharness');+ expect(person('owner'), findsOneWidget);+ expect(person('dee'), findsOneWidget);+ expect(person('tony'), findsNothing);+ await f.close(tester);+ },+ );++ testWidgets(+ 'a store that cannot write still lets the choice stand for this visit',+ (tester) async {+ final store = _Memory()..failWrites = true;+ final f = await swarm(tester, store: store);+ await f.show(tester);+ await choose(tester, 'openharness');+ expect(person('tony'), findsNothing);+ expect(tester.takeException(), isNull);+ await f.close(tester);+ },+ );++ group('with the rolling periods', () {+ /// A server that answers by period: All projects sums to 90 for the owner,+ /// the open project to 30, and tony is listed only in the whole-Swarm sum.+ void rolling(RosterFixture f) => f.server.leaderboardAnswer = (path) {+ final all = path.contains('scope=all');+ final name = RegExp(r'period=(\w+)').firstMatch(path)?.group(1) ?? '7d';+ return {+ 'projectId': 'lead',+ 'week': DateTime.utc(2026, 10, 26).millisecondsSinceEpoch,+ 'period': {'name': name, 'start': 1, 'end': 2},+ if (all) 'allProjects': true,+ 'people': [+ score('owner', all ? 90 : 30, 1),+ if (all) score('tony', 40, 2),+ score('dee', 12, all ? 3 : 2),+ ],+ 'waiting': {'total': 0, 'people': <Object>[]},+ };+ };++ Finder points(String id, String value) =>+ find.descendant(of: person(id), matching: find.textContaining(value));++ testWidgets('All projects shows Swarm-wide points for the chosen period; '+ 'a project its own', (tester) async {+ final f = await swarm(tester);+ rolling(f);+ await f.show(tester);+ expect(f.server.leaderboardReads.last, endsWith('&period=7d&scope=all'));+ expect(points('owner', '90'), findsWidgets);+ expect(points('tony', '40'), findsWidgets);+ expect(find.byKey(const ValueKey('leaderboard-week')), findsNothing);++ await tester.tap(find.byKey(const ValueKey('leaderboard-period')));+ await tester.pumpAndSettle();+ expect(find.text('Last 24h'), findsWidgets);+ expect(find.text('Last 30d'), findsWidgets);+ await tester.tap(find.text('Last 30d').last);+ await tester.pumpAndSettle();+ expect(f.server.leaderboardReads.last, endsWith('&period=30d&scope=all'));++ await choose(tester, 'openharness');+ expect(f.server.leaderboardReads.last, endsWith('&period=30d'));+ expect(points('owner', '30'), findsWidgets);+ expect(points('owner', '90'), findsNothing);+ expect(person('tony'), findsNothing);++ await choose(tester, 'All projects');+ expect(f.server.leaderboardReads.last, endsWith('&period=30d&scope=all'));+ expect(points('owner', '90'), findsWidgets);+ expect(person('tony'), findsOneWidget);+ await f.close(tester);+ });++ testWidgets('never lends whole-Swarm numbers or names to a project while '+ 'its own read is out', (tester) async {+ final f = await swarm(tester);+ rolling(f);+ await f.show(tester);+ final gate = Completer<void>();+ f.server.leaderboardGate = gate.future;+ await tester.tap(scope);+ await tester.pumpAndSettle();+ await tester.tap(find.text('openharness').last);+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 300));+ expect(points('owner', '90'), findsNothing);+ gate.complete();+ await tester.pumpAndSettle();+ expect(points('owner', '30'), findsWidgets);+ await f.close(tester);+ });++ testWidgets('a project lost while narrowed goes back to All projects and '+ 'reads it', (tester) async {+ final f = await swarm(tester);+ rolling(f);+ await f.show(tester);+ await choose(tester, 'openharness');+ expect(f.server.leaderboardReads.last, isNot(contains('scope=all')));+ f.server.state['projects'] = (f.server.state['projects'] as List)+ .where((p) => (p as Map)['id'] != 'lead')+ .toList();+ await f.controller.refresh();+ await tester.pumpAndSettle();+ expect(points('owner', '30'), findsNothing);+ await f.close(tester);+ });++ testWidgets('light and dark, both menus and Swarm-wide points', (+ tester,+ ) async {+ final f = await swarm(tester);+ rolling(f);+ final saved = grid.AppTheme.brightness.value;+ addTearDown(() => grid.AppTheme.brightness.value = saved);+ for (final brightness in Brightness.values) {+ grid.AppTheme.brightness.value = brightness;+ await f.show(tester, brightness: brightness);+ FocusManager.instance.primaryFocus?.unfocus();+ await tester.pumpAndSettle();+ expect(tester.takeException(), isNull);+ expect(+ find.descendant(+ of: find.byKey(const ValueKey('leaderboard-period')),+ matching: find.text('Last 7d'),+ ),+ findsOneWidget,+ );+ if (captureDir != null) {+ await captureBoundary(+ tester,+ f.boundary.currentContext!.findRenderObject()!+ as RenderRepaintBoundary,+ captureDir,+ 'roster-period-${brightness.name}',+ );+ }+ }+ await f.close(tester);+ });++ testWidgets('from a server before periods: the week menu, its own project '+ 'as before', (tester) async {+ final f = await swarm(tester);+ await f.show(tester);+ expect(find.byKey(const ValueKey('leaderboard-week')), findsOneWidget);+ expect(find.byKey(const ValueKey('leaderboard-period')), findsNothing);+ expect(points('owner', '30'), findsWidgets);+ await f.close(tester);+ });+ });++ test("another project's board never decides who is in this one", () {+ final project = SuperTabProject.fromJson({+ ...projectFixture(+ 'os',+ 'autonomous-os',+ 'os-lead',+ visibility: 'private',+ ),+ 'members': [+ {'id': 'tony'},+ ],+ });+ final other = SuperTabLeaderboard.fromJson({+ 'projectId': 'lead',+ 'people': [score('dee', 1, 1)],+ });+ expect(personInProject(project, 'dee', board: other), isFalse);+ expect(personInProject(project, 'tony', board: other), isTrue);+ expect(personInProject(project, 'owner', board: other), isTrue);+ });++ testWidgets('light and dark, with both menus', (tester) async {+ final f = await swarm(tester);+ final saved = grid.AppTheme.brightness.value;+ addTearDown(() => grid.AppTheme.brightness.value = saved);+ for (final brightness in Brightness.values) {+ grid.AppTheme.brightness.value = brightness;+ await f.show(tester, brightness: brightness);+ await choose(tester, 'openharness');+ FocusManager.instance.primaryFocus?.unfocus();+ await tester.pumpAndSettle();+ expect(tester.takeException(), isNull);+ if (captureDir != null) {+ await captureBoundary(+ tester,+ f.boundary.currentContext!.findRenderObject()!+ as RenderRepaintBoundary,+ captureDir,+ 'roster-scope-${brightness.name}',+ );+ }+ await choose(tester, 'All projects');+ }+ await f.close(tester);+ });+}diff --git a/desktop/test/super_tab_roster_test.dart b/desktop/test/super_tab_roster_test.dartindex 90751847e..794eb776d 100644--- a/desktop/test/super_tab_roster_test.dart+++ b/desktop/test/super_tab_roster_test.dart@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';import 'package:flutter/rendering.dart';import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/local_key_value_store.dart';import 'package:harness/core/models.dart';import 'package:harness/core/relative_time.dart';import 'package:harness/notify/alert_sounds.dart';@@ -33,6 +34,9 @@ class RosterFixture {SuperTabConversation? added;String? answered;final boundary = GlobalKey();++ /// Where the roster keeps its scope choice; none by default.+ LocalKeyValueStore? storage;bool disposed = false;Future<void> initialize() async {@@ -98,6 +102,7 @@ class RosterFixture {onAddAgent: (group) => added = group,onAnswer: (id) => answered = id,onOpenAgent: (agent) => opened = agent,+ storage: storage,now: now ?? DateTime.now,),),@@ -1749,7 +1754,7 @@ void main() {'agents on another computer show their Swarm state with the tabs\' marks, most urgent first',(tester) async {final f = await fixture(tester);- await tester.binding.setSurfaceSize(const Size(280, 540));+ await tester.binding.setSurfaceSize(const Size(280, 600));final now = DateTime.now().millisecondsSinceEpoch;// This Mac reads neither computer itself: only the Swarm says how they are.f.server.state['machines'] = [diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dartindex 6982c0d1f..30651245f 100644--- a/desktop/test/support/super_tab_fixture.dart+++ b/desktop/test/support/super_tab_fixture.dart@@ -511,6 +511,12 @@ class ConversationServer {Map<String, dynamic>? leaderboard;final leaderboardReads = <String>[];+ /// Answers by the read's path instead of [leaderboard], as a server does.+ Map<String, dynamic> Function(String path)? leaderboardAnswer;++ /// Holds the next reads' answers until it completes.+ Future<void>? leaderboardGate;+/// How many leaderboard reads fail as a server that is down does, before/// they answer again.var failLeaderboardReads = 0;@@ -1580,7 +1586,8 @@ class ConversationServer {statusCode: 503,);}- final board = leaderboard;+ if (leaderboardGate case final gate?) await gate;+ final board = leaderboardAnswer?.call(path) ?? leaderboard;if (board == null) {throw const SuperTabFailure('NOT_FOUND', 'Not found.', statusCode: 404);}diff --git a/docs/specs/2026-10-31-one-buddy-per-swarm.md b/docs/specs/2026-10-31-one-buddy-per-swarm.mdindex ae49cc6f6..a048b0f0b 100644--- a/docs/specs/2026-10-31-one-buddy-per-swarm.md+++ b/docs/specs/2026-10-31-one-buddy-per-swarm.md@@ -88,6 +88,9 @@ choice, as when they post in a project chat themselves.repository folder, so they run in project sessions; the main Buddy reads files with Read, Grep and Glob.- Before each delivery, the host compares the folder with the projects its person reads now and removes a worktree thatis no longer listed, so a lost project's code leaves the folder before the Buddy's next turn.+- Each worktree follows its project's default branch (Scholes, 11-02): at every start, and at a delivery when the last pass+ was an hour ago, the worktree fetches that one branch and moves when it has no changes. `project-copies.txt` in the home+ folder says which revision each copy is at and whether it may be behind. A copy that cannot move stays as it is.- A project session runs in a worktree of its project's checkout, exactly as today's Buddy does.**Staying within one context in a Swarm with many projects** (River, 10-31). The main Buddy reads on demand and preloadsdiff --git a/docs/swarms.md b/docs/swarms.mdindex 0f6a9d1a4..cba292766 100644--- a/docs/swarms.md+++ b/docs/swarms.md@@ -383,16 +383,34 @@ the project chat. (On 2026-10-29 production held 9 such chats in 4 Swarms, and n## Leaderboard-The leaderboard shows how each person helped the team ship this week. People+The leaderboard shows how each person helped the team ship over a period. Peoplecompete for fun, but the reward is shared: the team's goal is on top, andeveryone's points count toward it. In Desktop and the web app it is the rightpane's Humans section; there is no separate view. The team goal is one line at-the top, beside a small week picker. Below it, everyone is listed, with no+the top, beside a small period picker. Below it, everyone is listed, with nocut-off and most points first. Each person is one row: avatar, name and pointsin fixed columns, with a quiet line of their Shipped, Unblocked and Lent under it.It shows the project of the open conversation to the people who can read thatproject. A server without a leaderboard leaves the names without numbers.+The picker offers Last 24h, Last 7d and Last 30d, ending now; Last 7d is the+default. Each period is compared with the one of the same length before it,+except Last 30d, which shows no comparison because the board keeps five weeks of+records. Ship times, answers and attempts have exact times. Review verdicts are+kept by hour, and Lent by day and by the project of the task it went to. A day's+Lent is shared out evenly when a period starts or ends inside it, so Last 24h's+lent hours are an estimate. Weekly records are still written for older apps, which+keep their week picker, as a new app does on an older server. Time recorded by+week before the finer records began counts once, in the middle of its week.+A period's Lent is what the board's own project earned, plus any of that older+weekly time, which names no project.++On Desktop, All projects sums every project the reader can read, for the chosen+period, and lists everyone in the Swarm. A project the reader can't read adds+nothing to anyone's numbers. Older Lent recorded by week names no project, so it+counts only for someone who is on a project the reader can read. Choosing one+project shows that project's own. The phone's board is always one project's.+Each person has three numbers:- **Shipped**: requests the person asked for whose pull request merged. A groupdiff --git a/mobile/lib/swarm/swarm_leaderboard.dart b/mobile/lib/swarm/swarm_leaderboard.dartindex c9c1e08c3..716e5032b 100644--- a/mobile/lib/swarm/swarm_leaderboard.dart+++ b/mobile/lib/swarm/swarm_leaderboard.dart@@ -416,10 +416,11 @@ class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage> {children: [?_inviteButton(),_WeekButton(- label: swarmWeekName(reader?.week, current),+ label: _shownLabel(reader, current),+ period: reader?.period != null,onTap: reader == null? null- : () => unawaited(_pickWeek(context, reader, current)),+ : () => unawaited(_pick(context, reader, current)),),],),@@ -476,7 +477,8 @@ class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage> {),if (board != null)_TeamLine(- week: swarmWeekName(reader?.week, current),+ week: _shownLabel(reader, current),+ period: reader?.period,shipped: board.shipped,before: board.shippedBefore,onWeek: null,@@ -554,10 +556,10 @@ class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage> {final person? => score.displayName ?? superTabPersonName(person.email),null => 'Former member',};- final week = swarmWeekName(reader?.week, current);+ final week = _shownLabel(reader, current);final pickWeek = reader == null? null- : () => unawaited(_pickWeek(context, reader, current));+ : () => unawaited(_pick(context, reader, current));final columns = board == null || board.people.isEmpty? null: _Columns.of(context, board.people);@@ -565,6 +567,7 @@ class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage> {return [_TeamLine(week: week,+ period: reader?.period,shipped: board?.shipped,before: board?.shippedBefore,onWeek: pickWeek,@@ -652,6 +655,50 @@ class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage> {return SwarmInviteButton(session: session, reader: swarm);}+ /// "Last 7d", or from a server before periods the week shown.+ String _shownLabel(SwarmLeaderboardReader? reader, int current) =>+ switch (reader == null ? swarmDefaultPeriod : reader.period) {+ final period? => swarmPeriodLabel(period),+ null => swarmWeekName(reader?.week, current),+ };++ /// The rolling periods in a sheet, or the weeks from a server before them.+ Future<void> _pick(+ BuildContext context,+ SwarmLeaderboardReader reader,+ int current,+ ) => reader.period == null+ ? _pickWeek(context, reader, current)+ : _pickPeriod(context, reader);++ Future<void> _pickPeriod(+ BuildContext context,+ SwarmLeaderboardReader reader,+ ) async {+ final route = swarmSheetRoute<String>(+ context,+ isScrollControlled: false,+ builder: (context) => _Sheet(+ title: 'Period',+ closeKey: 'swarm-leaderboard-week-close',+ children: [+ for (final period in swarmPeriods)+ _WeekOption(+ key: ValueKey('swarm-leaderboard-period-$period'),+ label: swarmPeriodLabel(period),+ selected: reader.period == period,+ onTap: () => Navigator.of(context).pop(period),+ ),+ ],+ ),+ );+ _picker = route;+ final period = await Navigator.of(context).push(route);+ if (identical(_picker, route)) _picker = null;+ if (period == null || !mounted || !identical(reader, _board)) return;+ await reader.showPeriod(period);+ }+/// The four weeks the board keeps, this one first, in a sheet.Future<void> _pickWeek(BuildContext context,@@ -747,12 +794,16 @@ class _TeamLine extends StatelessWidget {required this.shipped,required this.before,required this.onWeek,+ this.period,this.picker = true,});- /// "This week", "Last week", …: the week shown.+ /// "This week", "Last week", …: the week shown; "Last 7d": the period.final String week;+ /// The rolling period shown; null for a week.+ final String? period;+/// Null until the board is read.final int? shipped, before;final VoidCallback? onWeek;@@ -764,7 +815,13 @@ class _TeamLine extends StatelessWidget {Widget build(BuildContext context) {AppTheme.watch(context);final shipped = this.shipped, before = this.before;- final earlier = week == 'This week' ? 'last week' : 'the week before';+ final period = this.period;+ final span = period == null ? week.toLowerCase() : swarmPeriodSpan(period);+ final earlier = period != null+ ? swarmPeriodEarlier(period)+ : week == 'This week'+ ? 'last week'+ : 'the week before';return Padding(key: const ValueKey('swarm-leaderboard-team'),padding: const EdgeInsets.only(left: AppSpace.s, bottom: AppSpace.xs),@@ -774,12 +831,13 @@ class _TeamLine extends StatelessWidget {child: shipped == null? const SizedBox.shrink(): Text(- '$shipped shipped ${week.toLowerCase()} · '- '$before $earlier',+ '$shipped shipped $span'+ '${earlier == null ? '' : ' · $before $earlier'}',style: AppType.caption(color: AppPalette.textSecondary),),),- if (picker) _WeekButton(label: week, onTap: onWeek),+ if (picker)+ _WeekButton(label: week, period: period != null, onTap: onWeek),],),);@@ -1095,15 +1153,22 @@ class _Trend extends StatelessWidget {/// The week shown and its arrow: opens the week picker.class _WeekButton extends StatelessWidget {- const _WeekButton({required this.label, required this.onTap});+ const _WeekButton({+ required this.label,+ required this.onTap,+ this.period = false,+ });final String label;++ /// A rolling period, not a week: says so to a screen reader.+ final bool period;final VoidCallback? onTap;@overrideWidget build(BuildContext context) => Semantics(button: true,- label: 'Week: $label',+ label: '${period ? 'Period' : 'Week'}: $label',excludeSemantics: true,child: InkWell(key: const ValueKey('swarm-leaderboard-week'),diff --git a/mobile/lib/swarm/swarm_leaderboard_reader.dart b/mobile/lib/swarm/swarm_leaderboard_reader.dartindex 4da366b6e..5dab278cc 100644--- a/mobile/lib/swarm/swarm_leaderboard_reader.dart+++ b/mobile/lib/swarm/swarm_leaderboard_reader.dart@@ -29,16 +29,30 @@ Map<String, dynamic> _map(Object? value) =>class SwarmLeaderboard {SwarmLeaderboard.fromJson(Map<String, dynamic> json): week = _int(json['week']),+ period = switch (_map(json['period'])['name']) {+ final String name when name.isNotEmpty => name,+ _ => null,+ },shipped = _int(_map(_map(json['goal'])['thisWeek'])['shipped']),shippedBefore = _int(_map(_map(json['goal'])['lastWeek'])['shipped']),people = List.unmodifiable([for (final row in json['people'] as List? ?? const [])- if (row is Map) SwarmScore.fromJson(_map(row)),+ if (row is Map)+ SwarmScore.fromJson(+ _map(row),+ period: switch (_map(json['period'])['name']) {+ final String name when name.isNotEmpty => name,+ _ => null,+ },+ ),]);/// The week's Monday 00:00 UTC, in epoch milliseconds.final int week;+ /// The rolling period this sums; null from a server that sums weeks.+ final String? period;+/// What the project shipped in the week.final int shipped;@@ -49,10 +63,35 @@ class SwarmLeaderboard {final List<SwarmScore> people;}+/// The rolling periods the board offers, the default in the middle (the+/// desktop's `leaderboardPeriods`).+const swarmPeriods = ['24h', '7d', '30d'];+const swarmDefaultPeriod = '7d';++/// "Last 7d": a period in the picker.+String swarmPeriodLabel(String period) => 'Last $period';++String _periodLength(String period) => switch (period) {+ '24h' => '24 hours',+ '30d' => '30 days',+ _ => '7 days',+};++/// "in the last 7 days": what a period's numbers cover, in a sentence.+String swarmPeriodSpan(String period) => 'in the last ${_periodLength(period)}';++/// "the 7 days before"; null for Last 30d, which has no comparison.+String? swarmPeriodEarlier(String period) =>+ period == '30d' ? null : 'the ${_periodLength(period)} before';+/// One person's week on the board.class SwarmScore {- SwarmScore.fromJson(Map<String, dynamic> json)- : personId = json['personId'] as String? ?? '',+ SwarmScore.fromJson(Map<String, dynamic> json, {String? period})+ : spanName = period == null ? 'this week' : swarmPeriodSpan(period),+ earlierName = period == null+ ? 'last week'+ : 'the ${_periodLength(period)} before',+ personId = json['personId'] as String? ?? '',points = _int(json['points']),rank = _int(json['rank']),medal = SwarmMedal.values.asNameMap()[json['medal']],@@ -85,7 +124,11 @@ class SwarmScore {/// The profile name; null from a server before names.final String? displayName;- /// The same scoring for the week before; null from a server before it.+ /// What the points cover and what [prevWeekPoints] covers, in a sentence.+ final String spanName, earlierName;++ /// The same scoring for the time before; null from a server before it, and+ /// for Last 30d, which has no comparison.final int? prevWeekPoints;}@@ -119,7 +162,7 @@ String? swarmTrend(SwarmScore score) {final before = score.prevWeekPoints;if (before == null || before == score.points) return null;final change = score.points - before;- return '${change > 0 ? 'up' : 'down'} ${change.abs()} from last week';+ return '${change > 0 ? 'up' : 'down'} ${change.abs()} from ${score.earlierName}';}String _plural(int count, String one) =>@@ -175,6 +218,13 @@ class SwarmLeaderboardReader extends ChangeNotifier {/// The Monday of the week shown; null for this week.int? week;+ String _period = swarmDefaultPeriod;+ bool _weeksOnly = false;++ /// The rolling period shown; null while the server only sums weeks (a server+ /// before periods), which keeps the week picker. Told once per reader.+ String? get period => _weeksOnly ? null : _period;+int _read = 0;Timer? _timer;bool _disposed = false;@@ -189,6 +239,17 @@ class SwarmLeaderboardReader extends ChangeNotifier {unawaited(refresh());}+ /// Shows another rolling period.+ Future<void> showPeriod(String period) {+ if (period == _period) return Future.value();+ _period = period;+ // Another period's numbers under this one's name would mislead.+ board = null;+ error = null;+ _notify();+ return refresh();+ }+/// Shows another week, null for this one.Future<void> showWeek(int? week) {if (week == this.week) return Future.value();@@ -203,21 +264,32 @@ class SwarmLeaderboardReader extends ChangeNotifier {Future<void> refresh() async {if (_disposed) return;- final read = ++_read, week = this.week;+ final read = ++_read, week = this.week, period = this.period;try {final answer = await request('GET','/api/super-tabs/${Uri.encodeComponent(tabId)}/leaderboard''?projectId=${Uri.encodeQueryComponent(projectId)}'- '${week == null ? '' : '&week=$week'}',+ '${period != null+ ? '&period=$period'+ : week == null+ ? ''+ : '&week=$week'}',);if (read != _read || _disposed) return;if (answer is! Map) throw const FormatException();board = SwarmLeaderboard.fromJson(answer.cast<String, dynamic>());+ if (board!.period == null) _weeksOnly = true;error = null;unavailable = false;} on SuperTabFailure catch (failure) {if (read != _read || _disposed) return;+ // A server before periods refuses the question, and only that one: any+ // other failure, however early, leaves the periods on for the next read.+ if (failure.statusCode == 400 && period != null) {+ _weeksOnly = true;+ return refresh();+ }if (failure.statusCode == 404) {board = null;error = null;@@ -254,8 +326,8 @@ List<(String, String)> swarmPersonWeek(SwarmScore score) {('Points',score.medal == null- ? '${score.points} this week'- : '${score.points} this week · place ${score.rank}',+ ? '${score.points} ${score.spanName}'+ : '${score.points} ${score.spanName} · place ${score.rank}',),('Shipped',diff --git a/mobile/lib/swarm/swarm_threads.dart b/mobile/lib/swarm/swarm_threads.dartindex 00752d4c6..694d5d95d 100644--- a/mobile/lib/swarm/swarm_threads.dart+++ b/mobile/lib/swarm/swarm_threads.dart@@ -145,14 +145,25 @@ class SwarmThreads extends ChangeNotifier {/// The Threads row's number: tags of the reader inside threads they have/// not read past, in chats this Swarm lists for them. A muted chat's/// threads never count (#2455). None until the phone's marks are back.+ ///+ /// Only threads the Threads page lists count ([unread] and [read]): the+ /// number promises something to open there. A tag in a thread the server+ /// left out (older than its bounds, unfollowed, a root the reader cannot+ /// read) stays in Activity and counts nothing here. None until the list+ /// has been read, and none once it is taken away (access lost).int get threadMentions {final snapshot = reader.snapshot;final marks = reader.readMarks;- if (reader.accessRevoked || snapshot == null || marks == null) return 0;+ if (reader.accessRevoked || snapshot == null || marks == null || !loaded) {+ return 0;+ }+ final listed = {for (final t in unread) t.key, for (final t in read) t.key};var count = 0;for (final m in asks?.mentions ?? const <SuperTabMention>[]) {final root = m.threadId;- if (root == null || snapshot.conversation(m.conversationId) == null) {+ if (root == null ||+ snapshot.conversation(m.conversationId) == null ||+ !listed.contains('${m.conversationId}/$root')) {continue;}if (reader.notifyOf(m.conversationId) == SwarmNotify.muted) continue;diff --git a/mobile/test/swarm/swarm_chat_notify_test.dart b/mobile/test/swarm/swarm_chat_notify_test.dartindex a49167b3f..e9d825b01 100644--- a/mobile/test/swarm/swarm_chat_notify_test.dart+++ b/mobile/test/swarm/swarm_chat_notify_test.dart@@ -337,8 +337,24 @@ void main() {final r = await rig(tags: [tag('t1', threadId: 'm1', messageSequence: 2)],);+ // The Threads page lists the thread the tag is in: only listed threads+ // count.+ r.swarm.routes['/api/super-tabs/$tab/threads'] = (_) => {+ 'unread': [],+ 'read': [+ {+ 'conversationId': 'g1',+ 'rootId': 'm1',+ 'root': {'id': 'm1', 'sequence': 1, 'text': 'Root'},+ 'lastReplyAt': '2026-11-01T01:00:00.000Z',+ 'lastReplySequence': 2,+ },+ ],+ };final threads = SwarmThreads(r.reader, asks: r.asks);addTearDown(threads.dispose);+ threads.addListener(() {});+ await r.reader.refresh();await settle();expect(threads.threadMentions, 1);diff --git a/mobile/test/swarm/swarm_leaderboard_page_test.dart b/mobile/test/swarm/swarm_leaderboard_page_test.dartindex 37a2e85ea..54ffab233 100644--- a/mobile/test/swarm/swarm_leaderboard_page_test.dart+++ b/mobile/test/swarm/swarm_leaderboard_page_test.dart@@ -192,7 +192,95 @@ void main() {const dee = 'swarm-leaderboard-person-dee';expect(inside(dee, find.text('Former member')), findsOneWidget);expect(y(tester, 'swarm-leaderboard-person-ken'), lessThan(y(tester, dee)));- expect(fake.paths.where((p) => p.contains('/leaderboard')), [path]);+ expect(fake.paths.where((p) => p.contains('/leaderboard')), [+ '$path&period=7d',+ ]);+ });++ group('the rolling periods', () {+ Map<String, dynamic> rolling(String name, int shipped) => {+ ...leaderboardData(week: monday, shipped: shipped),+ 'period': {'name': name, 'start': 1, 'end': 2},+ if (name == '30d')+ 'goal': {+ 'openRequests': 4,+ 'thisWeek': {'shipped': shipped},+ 'lastWeek': null,+ },+ };+ FakeSwarm periods() => backend()+ ..routes['$path&period=7d'] = ((_) => rolling('7d', 19))+ ..routes['$path&period=24h'] = ((_) => rolling('24h', 2))+ ..routes['$path&period=30d'] = (_) => rolling('30d', 40);++ testWidgets('opens on Last 7d, picks a period, and says what it covers', (+ tester,+ ) async {+ final fake = periods();+ await pump(tester, fake);+ await tester.pumpAndSettle();+ expect(+ inside('swarm-leaderboard-week', find.text('Last 7d')),+ findsOneWidget,+ );+ expect(+ find.text('19 shipped in the last 7 days · 11 the 7 days before'),+ findsOneWidget,+ );++ await tester.tap(key('swarm-leaderboard-week'));+ await tester.pumpAndSettle();+ expect(find.text('This week'), findsNothing);+ expect(key('swarm-leaderboard-period-24h'), findsOneWidget);+ await tester.tap(key('swarm-leaderboard-period-30d'));+ await tester.pumpAndSettle();+ expect(fake.paths.last, '$path&period=30d');+ expect(+ inside('swarm-leaderboard-week', find.text('Last 30d')),+ findsOneWidget,+ );+ // Only five weeks are kept: Last 30d has nothing to compare with.+ expect(find.text('40 shipped in the last 30 days'), findsOneWidget);+ });++ testWidgets('from a server before periods: the week picker, as before', (+ tester,+ ) async {+ final fake = backend();+ fake.routes['$path&period=7d'] = (_) => throw const SuperTabFailure(+ 'VALIDATION',+ 'Unrecognized key',+ statusCode: 400,+ );+ await pump(tester, fake);+ await tester.pumpAndSettle();+ expect(+ inside('swarm-leaderboard-week', find.text('This week')),+ findsOneWidget,+ );+ await tester.tap(key('swarm-leaderboard-week'));+ await tester.pumpAndSettle();+ expect(find.text('Last week'), findsOneWidget);+ expect(key('swarm-leaderboard-period-30d'), findsNothing);+ });++ testWidgets(+ 'signed out with the picker up: it closes and nothing is read',+ (tester) async {+ final fake = periods();+ final account = ValueNotifier<String?>(me);+ await pump(tester, fake, signedIn: account);+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-leaderboard-week'));+ await tester.pumpAndSettle();+ expect(key('swarm-leaderboard-period-30d'), findsOneWidget);+ final reads = fake.paths.length;+ account.value = null;+ await tester.pumpAndSettle();+ expect(key('swarm-leaderboard-period-30d'), findsNothing);+ expect(fake.paths.length, reads);+ },+ );});testWidgets('a display name from the board wins over the email name', (@@ -756,7 +844,7 @@ void main() {);await tester.pumpAndSettle();- expect(fake.paths.where((p) => p == path), hasLength(2));+ expect(fake.paths.where((p) => p.startsWith(path)), hasLength(2));});group("another account's board never stays", () {diff --git a/mobile/test/swarm/swarm_leaderboard_test.dart b/mobile/test/swarm/swarm_leaderboard_test.dartindex e6f0dbfd5..67b55e41a 100644--- a/mobile/test/swarm/swarm_leaderboard_test.dart+++ b/mobile/test/swarm/swarm_leaderboard_test.dart@@ -171,12 +171,117 @@ void main() {await read.refresh();- expect(fake.paths, [path]);+ expect(fake.paths, ['$path&period=7d']);expect(read.loading, isFalse);expect(read.board!.people.first.personId, 'diego');expect(read.week, isNull);});+ group('the rolling periods', () {+ Map<String, dynamic> period(String name, {int shipped = 19}) => {+ ...leaderboardData(shipped: shipped),+ 'period': {'name': name, 'start': 1, 'end': 2},+ };+ const older = SuperTabFailure(+ 'VALIDATION',+ 'Unrecognized key',+ statusCode: 400,+ );++ test('reads Last 7d first, and another period by name', () async {+ final fake = FakeSwarm()+ ..routes['$path&period=7d'] = ((_) => period('7d'))+ ..routes['$path&period=30d'] = (_) => period('30d', shipped: 40);+ final read = reader(fake);+ await read.refresh();+ expect(read.period, '7d');+ expect(read.board!.period, '7d');++ final told = <SwarmLeaderboard?>[];+ read.addListener(() => told.add(read.board));+ final shown = read.showPeriod('30d');+ expect(read.board, isNull, reason: "another period's numbers");+ await shown;+ expect(told.first, isNull);+ expect(fake.paths.last, '$path&period=30d');+ expect(read.board!.shipped, 40);+ });++ test(+ 'a server before periods keeps the weeks, after one refusal',+ () async {+ final fake = FakeSwarm()+ ..routes['$path&period=7d'] = ((_) => throw older)+ ..routes[path] = (_) => leaderboardData();+ final read = reader(fake);+ await read.refresh();+ expect(read.period, isNull);+ expect(read.error, isNull);+ expect(read.board!.shipped, isNot(0));+ await read.refresh();+ expect(fake.paths, ['$path&period=7d', path, path]);+ },+ );++ test('a failed first read leaves the periods on, and recovers', () async {+ var fail = true;+ final fake = FakeSwarm()+ ..routes[path] = (_) => fail+ ? throw const SuperTabFailure('OFFLINE', 'No computer answered.')+ : period('7d');+ final read = reader(fake);+ await read.refresh();+ expect(read.period, '7d');+ expect(read.error, 'No computer answered.');+ fail = false;+ await read.refresh();+ expect(read.period, '7d');+ expect(read.board!.period, '7d');+ expect(read.error, isNull);+ });++ test('an answer for the period left behind is not shown, a refusal '+ 'included', () async {+ final slow = Completer<Object?>(), refused = Completer<Object?>();+ final fake = FakeSwarm()+ ..routes['$path&period=7d'] = ((_) => slow.future)+ ..routes['$path&period=24h'] = ((_) => refused.future)+ ..routes['$path&period=30d'] = (_) => period('30d', shipped: 40);+ final read = reader(fake);+ final first = read.refresh();+ final second = read.showPeriod('24h');+ await read.showPeriod('30d');+ slow.complete(period('7d', shipped: 1));+ refused.completeError(older);+ await first;+ await second;+ expect(read.board!.shipped, 40);+ expect(read.period, '30d', reason: 'a stale refusal changes nothing');+ });++ test('says the period in words, and no comparison for Last 30d', () {+ final week = SwarmLeaderboard.fromJson(period('7d'));+ final score = week.people.first;+ expect(score.spanName, 'in the last 7 days');+ expect(score.earlierName, 'the 7 days before');+ expect(swarmPersonWeek(score).first.$2, contains('in the last 7 days'));+ expect(swarmPeriodEarlier('24h'), 'the 24 hours before');+ expect(swarmPeriodEarlier('30d'), isNull);+ final old = SwarmLeaderboard.fromJson(leaderboardData()).people.first;+ expect(old.spanName, 'this week');+ });++ test('says a trend against the time before', () {+ final score = SwarmLeaderboard.fromJson({+ ...period('24h'),+ 'people': [+ {'personId': 'a', 'points': 9, 'rank': 1, 'prevWeekPoints': 4},+ ],+ }).people.first;+ expect(swarmTrend(score), 'up 5 from the 24 hours before');+ });+ });+test('another week clears the board until its own read lands', () async {final fake = FakeSwarm()..routes[path] = ((_) => leaderboardData())@@ -199,11 +304,13 @@ void main() {test('an answer for the week left behind is not shown', () async {final slow = Completer<Object?>();+ var reads = 0;final fake = FakeSwarm()- ..routes[path] = ((_) => slow.future)+ ..routes[path] = ((_) => reads++ == 0 ? leaderboardData() : slow.future)..routes['$path&week=$lastWeek'] = (_) =>leaderboardData(week: lastWeek, shipped: 11);final read = reader(fake);+ await read.refresh();final first = read.refresh();await read.showWeek(lastWeek);diff --git a/mobile/test/swarm/swarm_project_c_test.dart b/mobile/test/swarm/swarm_project_c_test.dartindex 39d7c4b0a..05bed4dd4 100644--- a/mobile/test/swarm/swarm_project_c_test.dart+++ b/mobile/test/swarm/swarm_project_c_test.dart@@ -30,6 +30,7 @@ import 'swarm_fixture.dart';/// ☰ opening its Leaderboard and its Team as sheets.void main() {const board = '/api/super-tabs/$tab/leaderboard?projectId=$project';+ bool boardRead(String p) => p.startsWith(board) && !p.contains('&week=');/// One Swarm whose project Mobile has three people (the viewer, diego and/// ken) and four agents: River, the Product Manager; Nova at work on g1;@@ -767,7 +768,7 @@ void main() {tester.getTopRight(points('ken')).dx,reason: 'the points line up',);- expect(fake.paths.where((p) => p == board).length, 1);+ expect(fake.paths.where(boardRead).length, 1);expect(fake.paths.where((p) => p.contains('/leaderboard') && !p.startsWith(board),@@ -1052,13 +1053,13 @@ void main() {expect(key('swarm-leaderboard-loading'), findsNothing);expect(onBoard(tester), contains('diego'));expect(find.textContaining('Loading'), findsNothing);- final reads = fake.paths.where((p) => p == board).length;+ final reads = fake.paths.where(boardRead).length;fake.routes[board] = answer;await tester.tap(key('swarm-leaderboard-retry'));await tester.pumpAndSettle();- expect(fake.paths.where((p) => p == board).length, reads + 1);+ expect(fake.paths.where(boardRead).length, reads + 1);expect(find.text('Board is down.'), findsNothing);expect(onBoard(tester), ['person-me', 'diego', 'ken']);expect(figures('swarm-leaderboard-person-diego'), findsWidgets);@@ -1109,7 +1110,7 @@ void main() {await tester.tap(key('swarm-leaderboard-close'));await tester.pumpAndSettle();expect(find.byType(SwarmLeaderboardPage), findsNothing);- final reads = fake.paths.where((p) => p == board).length;+ final reads = fake.paths.where(boardRead).length;gate.complete();await tester.pumpAndSettle();@@ -1120,7 +1121,7 @@ void main() {await tester.pumpAndSettle();await tester.tap(key('swarm-project-menu-leaderboard'));await tester.pumpAndSettle();- expect(fake.paths.where((p) => p == board).length, reads + 1);+ expect(fake.paths.where(boardRead).length, reads + 1);expect(find.text('1320'), findsOneWidget);});diff --git a/mobile/test/swarm/swarm_threads_test.dart b/mobile/test/swarm/swarm_threads_test.dartindex b7adc622f..92bcc26d4 100644--- a/mobile/test/swarm/swarm_threads_test.dart+++ b/mobile/test/swarm/swarm_threads_test.dart@@ -480,7 +480,16 @@ void main() {mention('t5', chat: 'private', thread: 'p1', sequence: 9),],);- r.swarm.routes[threadsRoute] = (_) => {'unread': [], 'read': []};+ r.swarm.routes[threadsRoute] = (_) => {+ 'unread': [],+ 'read': [+ row('g1', 'm1'),+ row('g1', 'm9'),+ row('g2', 'm3'),+ row('private', 'p1'),+ ],+ };+ await show(r.threads);await r.reader.refresh();await settle();@@ -489,5 +498,84 @@ void main() {r.marks.markThreadRead('g1', 'm1', 4);expect(r.threads.threadMentions, 0);});++ test('counts only tags in threads the page lists: one the server left '+ 'out stays in Activity and counts nothing', () async {+ final r = rig(+ mentions: [+ mention('t1', thread: 'm1', sequence: 4), // listed (unread)+ mention('t2', thread: 'm2', sequence: 5), // listed (read)+ mention('t3', thread: 'm3', sequence: 6), // left out by the server+ mention('t4', chat: 'g1', thread: 'm1', sequence: 7), // same thread+ ],+ );+ r.swarm.routes[threadsRoute] = (_) => {+ 'unread': [row('g1', 'm1', unread: 1)],+ 'read': [row('g1', 'm2')],+ };+ await show(r.threads);+ await r.reader.refresh();+ await settle();++ expect(r.threads.loaded, isTrue);+ expect(r.threads.threadMentions, 3, reason: 't1, t4 and t2; never t3');+ expect(+ r.threads.asks!.mentions,+ hasLength(4),+ reason: 'all still in Activity',+ );+ });++ test('is none until the list has been read, and again once it is taken '+ 'away', () async {+ final r = rig(mentions: [mention('t1', thread: 'm1', sequence: 4)]);+ final list = Completer<Object?>();+ r.swarm.routes[threadsRoute] = (_) => list.future;+ await show(r.threads);+ await r.reader.refresh();+ await settle();++ expect(r.threads.loaded, isFalse);+ expect(r.threads.threadMentions, 0, reason: 'nothing listed yet');++ list.complete({+ 'unread': [],+ 'read': [row('g1', 'm1')],+ });+ await settle();+ expect(r.threads.threadMentions, 1);++ r.reader.revoke();+ expect(r.threads.threadMentions, 0, reason: 'access lost');+ });++ test('a failed first list counts nothing and, once it recovers, counts '+ 'again; the failed read is not repeated on every redraw', () async {+ final r = rig(mentions: [mention('t1', thread: 'm1', sequence: 4)]);+ var failing = true;+ r.swarm.routes[threadsRoute] = (_) {+ if (failing) throw Exception('offline');+ return {+ 'unread': [],+ 'read': [row('g1', 'm1')],+ };+ };+ await show(r.threads);+ await r.reader.refresh();+ await settle();++ expect(r.threads.error, isNotNull);+ expect(r.threads.loaded, isFalse);+ expect(r.threads.threadMentions, 0);+ final reads = threadReads(r.swarm);+ expect(reads, lessThanOrEqualTo(2), reason: 'bounded, no retry loop');++ failing = false;+ r.tick(const Duration(seconds: 30));+ await r.threads.load();+ await settle();+ expect(r.threads.error, isNull);+ expect(r.threads.threadMentions, 1);+ });});}