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
Tasks feed: full history of my agents' tasks, my requests and proposals, paged (#4203) (#3465)
0xken152ef9ee3939e5
diff --git a/backend/integration/superTabNotAvailable.test.ts b/backend/integration/superTabNotAvailable.test.tsindex 4c3e67ad0..566f8df8b 100644--- a/backend/integration/superTabNotAvailable.test.ts+++ b/backend/integration/superTabNotAvailable.test.ts@@ -103,6 +103,7 @@ function calls(tab: string, chat: string, project: string) {json('POST', 'POST /api/super-tabs/:tabId/sharing', `${t}/sharing`, { operationId: op(), revision: 0, access: { mode: 'link', role: 'viewer' } }),json('GET', 'GET /api/super-tabs/:tabId/routing-policy', `${t}/routing-policy`),json('GET', 'GET /api/super-tabs/:tabId/groups', `${t}/groups?dormant=1&projectId=${project}`),+ json('GET', 'GET /api/super-tabs/:tabId/personal-tasks', `${t}/personal-tasks`),json('GET', 'GET /api/super-tabs/:tabId/groups/:conversationId', `${t}/groups/${chat}`),json('POST', 'POST /api/super-tabs/:tabId/join', `${t}/join`, { operationId: op(), token: 'a'.repeat(43) }),json('POST', 'POST /api/super-tabs/:tabId/join/preview', `${t}/join/preview`, { token: 'a'.repeat(43) }),diff --git a/backend/integration/superTabPersonalTasksFeed.test.ts b/backend/integration/superTabPersonalTasksFeed.test.tsnew file mode 100644index 000000000..8c6b2601d--- /dev/null+++ b/backend/integration/superTabPersonalTasksFeed.test.ts@@ -0,0 +1,197 @@+import { randomUUID } from 'node:crypto'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import type { MongoMemoryReplSet } from 'mongodb-memory-server-core'+import type { PrismaClient } from '@prisma/client'+import type { AuthUser } from '../src/lib/ssoAuth.js'+import { SuperTabStore } from '../src/superTabs/store.js'+import { commandSchema } from '../src/superTabs/commands.js'+import type { Conversation } from '../src/superTabs/model.js'+import { SwarmReads } from '../src/superTabs/read/service.js'+import { feedIdsOf, markFeedIds } from '../src/superTabs/read/feedIds.js'+import { listNamedIndexes } from '../src/superTabs/parts/indexed.js'+import { planDatabase, plan, profiled, reads } from './plans.test-support.js'++// Task #4203: the person's Tasks feed is the history of their own agents' tasks, their requests and their proposals,+// dormant and archived ones too, newest first, paged through one index, and only what they may read.+let replica: MongoMemoryReplSet, db: PrismaClient+const owner: AuthUser = { sub: '560000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const peer: AuthUser = { sub: '560000000000000000000002', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const bystander: AuthUser = { sub: '560000000000000000000003', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const outsider: AuthUser = { sub: '560000000000000000000004', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const config = { engine: 'codex', model: 'fixture', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }+const MINUTE = 60_000++beforeAll(async () => {+ ({ replica, db } = await planDatabase('personal_tasks_feed'))+ await listNamedIndexes(db)+ for (const u of [owner, peer, bystander, outsider]) await db.user.create({ data: { id: u.sub, externalId: `fixture-${u.sub}`, email: u.email, autonomousEnv: 'prod' } })+ for (const [machineId, user] of [['feed-owner-mac', owner], ['feed-peer-mac', peer]] as const)+ await db.machine.create({ data: { machineId, userId: user.sub, apiKey: `fixture-${machineId}`, managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })+})+afterAll(async () => { await db?.$disconnect(); await replica?.stop() })++/** A Swarm where peer's own agent works a task the owner asked for (then archived and dormant), peer asked for a task and+ * proposed one, the owner's agent works the owner's own task, and a private project of the owner's holds tasks that name peer. */+async function fixture() {+ let now = Date.now() - 1_000 * MINUTE+ const store = new SuperTabStore(db, () => now, null, { readCache: null })+ const tab = (await store.create(owner, randomUUID(), 'Feed', 'public')).id+ const execute = async (command: unknown, user = owner, asAgentId?: string) => {+ now += MINUTE+ return (await store.execute(user, tab, { operationId: randomUUID(), command: commandSchema.parse(command) }, asAgentId)).result as Record<string, unknown>+ }+ for (const person of [peer, bystander]) {+ const invitation = await execute({ type: 'invite.create', email: person.email, role: 'collaborator', conversationId: 'lead' })+ await execute({ type: 'invite.accept', inviteId: invitation.inviteId }, person)+ }+ const pm = String((await execute({ type: 'agent.add', conversationId: 'lead', machineId: 'feed-owner-mac', harnessId: randomUUID(), name: 'PM', configuration: config, lead: true })).agentId)+ const task = async (title: string, requesterId?: string) => String((await execute({ type: 'conversation.create', title, priority: 'P2',+ ...requesterId ? { requesterId } : { noRequesterReason: 'fixture' },+ task: { goal: title, changes: title, constraints: 'none', owns: ['backend/'] }, checks: [{ description: `${title} works`, independent: false }] }, owner, pm)).conversationId)+ const theirs = await task('Peer agent work', owner.sub)+ const peerAgent = String((await execute({ type: 'agent.add', conversationId: theirs, machineId: 'feed-peer-mac', harnessId: randomUUID(), name: 'Peers', configuration: config, lead: false }, peer)).agentId)+ await execute({ type: 'work.assign', conversationId: theirs, agentId: peerAgent }, owner, pm)+ const asked = await task('Peer asked', peer.sub)+ // The Board switch is #3819's command; the proposal cards read only its stored value.+ const head = await db.swarmHead.findUniqueOrThrow({ where: { id: `${tab}:head` } })+ const data = head.data as unknown as { projects: Array<{ boardMode?: true }> }+ data.projects[0]!.boardMode = true+ await db.swarmHead.update({ where: { id: head.id }, data: { data: data as never, version: head.version + 1 } })+ const proposal = String((await execute({ type: 'proposal.create', projectId: 'lead', title: 'Keep drafts', text: 'Keep offline drafts', goal: 'Preserve work',+ why: 'Reconnect loses drafts', doneWhen: 'Draft returns', evidence: ['Repro'], priority: 'P2' }, peer)).conversationId)+ const ownersOwn = await task('Owner work', owner.sub)+ const ownerAgent = String((await execute({ type: 'agent.add', conversationId: ownersOwn, machineId: 'feed-owner-mac', harnessId: randomUUID(), name: 'Builder', configuration: config, lead: false })).agentId)+ await execute({ type: 'work.assign', conversationId: ownersOwn, agentId: ownerAgent }, owner, pm)+ const secret = String((await execute({ type: 'project.create', name: 'Secret', visibility: 'private', brief: '' })).projectId)+ // Archived and quiet, as the archive pass leaves a finished task: still in its people's history.+ const row = await db.swarmGroup.findUniqueOrThrow({ where: { tabId_key: { tabId: tab, key: theirs } } })+ await db.swarmGroup.update({ where: { id: row.id }, data: { archived: true, dormant: true,+ data: { ...row.data as object, archived: true, dormant: true } as never } })+ return { store, tab, execute, now: () => now, theirs, asked, proposal, ownersOwn, secret, peerAgent, ownerAgent }+}++type Fixture = Awaited<ReturnType<typeof fixture>>++/** `n` copies of `key`'s row under new keys, each a minute older than the one before from `newest`, in `projectId`. */+async function copies(f: Fixture, key: string, n: number, newest: number, projectId?: string, tie = 0): Promise<string[]> {+ const { id: _id, ...row } = await db.swarmGroup.findUniqueOrThrow({ where: { tabId_key: { tabId: f.tab, key } } })+ const keys = Array.from({ length: n }, (_, i) => `${projectId ? 'hidden' : 'copy'}-${String(i).padStart(3, '0')}`)+ await db.swarmGroup.createMany({ data: keys.map((k, i) => {+ // `tie` rows share one moment: the cursor goes on by key within it.+ const at = new Date(newest - Math.max(0, i - tie) * MINUTE)+ return { ...row, id: `${f.tab}:${k}`, key: k, ordinal: row.ordinal + i + 1, lastActivityAt: at, ...projectId ? { projectId } : {},+ data: { ...row.data as object, id: k, title: k, lastActivityAt: at.toISOString(), ...projectId ? { projectId } : {} } as never }+ }) })+ return keys+}++const ids = (rows: Array<{ id: string }>) => rows.map(r => r.id)++describe('the person\'s Tasks feed (task #4203)', () => {+ it('lists my agents\' tasks, archived ones too, my requests and my proposals, never another\'s own work', async () => {+ const f = await fixture()+ const feed = (await new SwarmReads(f.store).firstLoad(peer, f.tab)).personalTasks!+ expect(feed).toMatchObject({ reset: true, removed: [], olderCursor: null })+ expect(ids(feed.upserts)).toEqual([f.proposal, f.asked, f.theirs])+ expect(feed.upserts.find(r => r.id === f.theirs)).toMatchObject({ status: 'working', agent: { id: f.peerAgent },+ requester: { id: owner.sub } })+ })++ it('pages older tasks newest first through a cursor, with no repeat or gap across rows of the same moment', async () => {+ const f = await fixture()+ const older = await copies(f, f.asked, 60, f.now() - 10 * MINUTE, undefined, 5)+ const reads = new SwarmReads(f.store)+ const first = (await reads.firstLoad(peer, f.tab)).personalTasks!+ expect(first.upserts).toHaveLength(50)+ expect(first.olderCursor).toEqual(expect.any(String))+ const second = await reads.personalTasks(peer, f.tab, first.olderCursor!)+ expect(second).toMatchObject({ reset: false, removed: [], olderCursor: null })+ const all = [...ids(first.upserts), ...ids(second.upserts)]+ expect(new Set(all).size).toBe(all.length)+ expect(new Set(all)).toEqual(new Set([f.proposal, f.asked, f.theirs, ...older]))+ const at = [...first.upserts, ...second.upserts].map(r => r.at)+ expect(at).toEqual([...at].sort((a, b) => b - a))+ })++ it('never lists, nor hands out as a cursor, a task the reader may not read, and lists nothing for a bystander', async () => {+ const f = await fixture()+ // Newer than everything, naming peer, in a project only the owner reads.+ const hidden = await copies(f, f.asked, 55, f.now() + 100 * MINUTE, f.secret)+ await copies(f, f.asked, 49, f.now() - 10 * MINUTE)+ const reads = new SwarmReads(f.store)+ const first = (await reads.firstLoad(peer, f.tab)).personalTasks!+ expect(first.upserts).toHaveLength(50)+ expect(ids(first.upserts).some(id => hidden.includes(id))).toBe(false)+ const cursor = JSON.parse(Buffer.from(first.olderCursor!, 'base64url').toString()) as { k: string }+ expect(ids(first.upserts)).toContain(cursor.k)+ const second = await reads.personalTasks(peer, f.tab, first.olderCursor!)+ expect(ids(second.upserts).some(id => hidden.includes(id))).toBe(false)+ expect((await reads.firstLoad(bystander, f.tab)).personalTasks!.upserts).toEqual([])+ await expect(reads.personalTasks(outsider, f.tab)).rejects.toThrow()+ await expect(reads.personalTasks(peer, f.tab, 'not-a-cursor')).rejects.toMatchObject({ code: 'INVALID_CURSOR' })+ })++ it('reads a page through the feed index, examining about what it returns', async () => {+ const f = await fixture()+ await copies(f, f.asked, 120, f.now() - 10 * MINUTE)+ const reads = new SwarmReads(f.store)+ const first = (await reads.firstLoad(peer, f.tab)).personalTasks!+ const entries = await profiled(db, () => reads.personalTasks(peer, f.tab, first.olderCursor!))+ const feed = plan(readsOf(entries))+ expect(feed.length).toBeGreaterThan(0)+ for (const read of feed) {+ expect(read.plan).toContain('IXSCAN { tabId: 1, feedIds: 1, lastActivityAt: 1, key: 1 }')+ expect(read.docsExamined).toBeLessThanOrEqual(read.returned + 1)+ }+ })++ it('keeps a task of my agent after that agent is closed, by the login it ran under', async () => {+ const f = await fixture()+ await f.execute({ type: 'agent.remove', agentId: f.peerAgent }, peer)+ const feed = (await new SwarmReads(f.store).firstLoad(peer, f.tab)).personalTasks!+ expect(ids(feed.upserts)).toContain(f.theirs)+ expect(feed.upserts.find(r => r.id === f.theirs)!.agent).toBeNull()+ })++ it('skips tasks I can no longer read inside the database: a page is one or two reads however many there are', async () => {+ const f = await fixture()+ await copies(f, f.asked, 300, f.now() + 100 * MINUTE, f.secret)+ const reads = new SwarmReads(f.store)+ let page: Awaited<ReturnType<typeof reads.personalTasks>> | undefined+ const entries = await profiled(db, async () => { page = await reads.personalTasks(peer, f.tab) })+ expect(ids(page!.upserts)).toEqual([f.proposal, f.asked, f.theirs])+ const feed = plan(readsOf(entries))+ expect(feed.length).toBeLessThanOrEqual(2)+ for (const read of feed) expect(read.returned).toBeLessThanOrEqual(50)+ })++ it('sets the column at startup on rows written before it, with the login of an assignment\'s agent from before it was stored', async () => {+ const f = await fixture()+ await db.$runCommandRaw({ update: 'SwarmGroup', updates: [{ q: { tabId: f.tab }, u: { $unset: { feedIds: '', 'data.assignment.execution.contributorId': '' } }, multi: true }] })+ expect(await markFeedIds(db)).toBeGreaterThan(0)+ const rows = await db.swarmGroup.findMany({ where: { tabId: f.tab } })+ const column = (key: string) => [...rows.find(r => r.key === key)!.feedIds].sort()+ expect(column(f.theirs)).toEqual([owner.sub, f.peerAgent, peer.sub].sort())+ expect(column(f.ownersOwn)).toEqual([owner.sub, f.ownerAgent].sort())+ for (const row of rows.filter(r => !(r.data as unknown as Conversation).assignment))+ expect([...row.feedIds].sort(), row.key).toEqual(feedIdsOf(row.data as unknown as Conversation).sort())+ expect(await markFeedIds(db)).toBe(0)+ })+})++describe('the Tasks feed backfill when the database refuses its writes (review of #3465)', () => {+ it('stops and says so, never reading the same rows again forever', async () => {+ const f = await fixture()+ await db.$runCommandRaw({ update: 'SwarmGroup', updates: [{ q: { tabId: f.tab }, u: { $unset: { feedIds: '' } }, multi: true }] })+ // Any row that would get a non-empty column is refused.+ await db.$runCommandRaw({ collMod: 'SwarmGroup', validator: { $or: [{ feedIds: { $exists: false } }, { feedIds: { $size: 0 } }] }, validationAction: 'error' })+ try {+ await expect(markFeedIds(db)).rejects.toThrow(/refused/)+ } finally {+ await db.$runCommandRaw({ collMod: 'SwarmGroup', validator: {} })+ }+ expect(await markFeedIds(db)).toBeGreaterThan(0)+ }, 20_000)+})++const readsOf = (entries: Awaited<ReturnType<typeof profiled>>) => reads(entries, 'SwarmGroup', ['feedIds'])diff --git a/backend/integration/superTabRead.test.ts b/backend/integration/superTabRead.test.tsindex cc0608e8d..01cb6e17b 100644--- a/backend/integration/superTabRead.test.ts+++ b/backend/integration/superTabRead.test.ts@@ -189,6 +189,16 @@ describe('first load (design 4.3)', () => {}})+ it('pages the person\'s Tasks feed by its cursor, and refuses a cursor it never gave (task #4203)', async () => {+ const s = await scene()+ const page = await get(`/api/super-tabs/${s.tabId}/personal-tasks`, peer)+ expect(page.status).toBe(200)+ expect(page.body.data).toEqual({ approvalMode: 'autoApprove', reset: true, upserts: [], removed: [], olderCursor: null })+ const bad = await get(`/api/super-tabs/${s.tabId}/personal-tasks?before=bm90LWEtY3Vyc29y`, peer)+ expect(bad.status).toBe(400)+ expect(bad.body.error.code).toBe('INVALID_CURSOR')+ })+it('answers the design\'s shape: cursor 30 s before the read, epoch, newest change, the reader\'s parts and derived values', async () => {const s = await scene()clock = NOW@@ -196,7 +206,7 @@ describe('first load (design 4.3)', () => {expect(status).toBe(200)expect(Object.keys(body.data).sort()).toEqual(['agents', 'cursor', 'derived', 'derivedEtag', 'epoch', 'format', 'groups', 'head', 'lastChangedAt','machines', 'members', 'personalTasks', 'progress', 'serverTime', 'starts', 'steps', 'tabId'].sort())- expect(body.data.personalTasks).toEqual({ approvalMode: 'autoApprove', reset: true, upserts: [], removed: [] })+ expect(body.data.personalTasks).toEqual({ approvalMode: 'autoApprove', reset: true, upserts: [], removed: [], olderCursor: null })expect(body.data).toMatchObject({ format: 2, tabId: s.tabId, serverTime: NOW, epoch: 1, lastChangedAt: MIGRATED, steps: true,head: { key: 'head', version: R, changedAt: MIGRATED, data: { id: s.tabId, name: 'Pilot' } } })expect(JSON.parse(Buffer.from(body.data.cursor, 'base64url').toString())).toEqual({ v: 2, t: NOW - 30_000, e: 1 })diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex 84f6ee975..f0f40b062 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1972,6 +1972,9 @@ model SwarmGroup {/// Out of first loads and changes: work done or cancelled and quiet for a day, or archived by hand. A message wakes it.dormant Boolean @default(false)agentIds String[]+ /// The people and agents whose Tasks feed lists it (read/feedIds.ts); [] for a conversation that is no task. Set on every+ /// write; parts written before it are set at worker startup (markFeedIds).+ feedIds String[] @default([])/// The machine running its active assignment, for the host's change read.executionMachineId String?messageSeq Int @default(0)@@ -1995,6 +1998,8 @@ model SwarmGroup {@@index([tabId, changedAt])@@index([tabId, dormant, changedAt])@@index([tabId, agentIds])+ /// A person's Tasks feed, newest activity first, then by key (read/personalTasks.ts): the person and their own agents.+ @@index([tabId, feedIds, lastActivityAt, key])/// A project's quiet conversations by activity (leaderboard, digest), and their pages newest first, then by key (parts/load.ts loadDormant).@@index([tabId, projectId, dormant, lastActivityAt, key])@@index([tabId, projectId, dormant, reportSeq])diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex 9e23cb028..28883f904 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -97,6 +97,8 @@ const scorecardQuery = z.object({ projectId: id, scope: z.literal('all').optionaconst 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.')const dormantQuery = agentQuery.extend({ dormant: z.literal('1'), projectId: id.optional(), before: cursor.optional() })+/** An older page of the person's Tasks feed (task #4203): the `olderCursor` a first load or an earlier page gave. */+const personalTasksQuery = z.object({ before: cursor.optional() }).strict()const groupParams = tabParams.extend({ conversationId: id })const hostChangesQuery = z.object({ cursor: cursor.optional(), full: z.literal('1').optional() }).strict()const etag = z.string().regex(/^[A-Za-z0-9_-]{1,64}$/)@@ -696,6 +698,9 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Suapp.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.query.period, req.query.scope === 'all')))+ app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof personalTasksQuery> }>('/api/super-tabs/:tabId/personal-tasks',+ { preHandler: [validateParams(tabParams), validateQuery(personalTasksQuery)] },+ (req, reply) => respond(reply, () => reads.personalTasks(req.user!, req.params.tabId, req.query.before)))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/buddies.test.ts b/backend/src/superTabs/buddies.test.tsindex 2d38b3a70..232cfe02f 100644--- a/backend/src/superTabs/buddies.test.ts+++ b/backend/src/superTabs/buddies.test.ts@@ -141,12 +141,14 @@ describe('what a Buddy reads', () => {expect(JSON.stringify(seen)).not.toContain('/Users/owner/app')// No machines means none: agents and a task's assignment keep no machine or terminal id (review 1 of #2115, item 3).f.state.conversations.find(c => c.id === f.group)!.assignment = { id: 'a1', agentId: f.pm, status: 'working', result: null,- execution: { machineId: 'machine', harnessId: 'app-pm', machineOwnerId: 'host' } } as never+ execution: { machineId: 'machine', harnessId: 'app-pm', machineOwnerId: 'host', contributorId: 'runner-login' } } as neverf.state.conversations.find(c => c.id === f.group)!.lostAttempt = { id: 'a0', agentId: f.pm, machineId: 'machine', engine: 'claude' }const strict = visibleState(f.state, agentActor('buddy'))expect(strict.agents.map(a => [a.machineId, a.harnessId])).toEqual(strict.agents.map(() => ['', '']))const task = strict.conversations.find(c => c.id === f.group)!- expect(task.assignment!.execution).toEqual({ machineId: '', harnessId: '', machineOwnerId: '' })+ // Nor whose login its agent runs under (the Tasks feed's, #4203), as an agent's own contributor is blanked.+ expect(task.assignment!.execution).toEqual({ machineId: '', harnessId: '', machineOwnerId: '', contributorId: '' })+ expect(JSON.stringify(strict)).not.toContain('runner-login')expect(task.lostAttempt).toEqual({ id: 'a0', agentId: f.pm })expect(visibleState(f.state, agentActor(f.pm)).agents.find(a => a.id === f.pm)!.machineId).toBe('machine')// A lost task's reason without its machine, on the task and on the agent; a reason naming none stays (re-check 2).diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex b1f135c46..d0700059d 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -1952,7 +1952,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,// Whoever it was pinned to (dispatch.ts), it is in someone's hands now.delete group.pingroup.assignment = { id: assignmentId, agentId: worker.id, status: 'working', configuration: structuredClone(worker.configuration),- execution: { machineId: worker.machineId, harnessId: worker.harnessId, machineOwnerId: worker.machineOwnerId }, result: null }+ execution: { machineId: worker.machineId, harnessId: worker.harnessId, machineOwnerId: worker.machineOwnerId, contributorId: worker.contributorId }, result: null }renewLease(group.assignment, context.now)leadActed(group.id, 'assign')recordRun(state, group, group.assignment, worker, context.now)diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex e0bb0e454..53b3cbd35 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -308,7 +308,9 @@ export interface Assignment {agentId: stringstatus: WorkStatusconfiguration: AgentConfiguration- execution: { machineId: string; harnessId: string; machineOwnerId: string }+ /** `contributorId`: whose login its agent runs under (Agent.contributorId), so the person's Tasks feed keeps it after the agent+ * is closed (read/feedIds.ts). Absent on assignments made before 2026-11-07. */+ execution: { machineId: string; harnessId: string; machineOwnerId: string; contributorId?: string }result: string | null/** Explicit progress fences delayed recording gaps; absent on older backends. */recordingProgress?: { at: number; revision: number }@@ -919,7 +921,8 @@ export const groupForBuddy = <T extends Pick<Conversation, 'assignment' | 'lostA}export const groupWithoutMachines = <T extends Pick<Conversation, 'assignment' | 'lostAttempt'>>(group: T): T => {const assignment = group.assignment && { ...group.assignment,- ...(group.assignment.execution ? { execution: { ...group.assignment.execution, machineId: '', harnessId: '', machineOwnerId: '' } } : {}),+ ...(group.assignment.execution ? { execution: { ...group.assignment.execution, machineId: '', harnessId: '', machineOwnerId: '',+ ...group.assignment.execution.contributorId !== undefined ? { contributorId: '' } : {} } } : {}),...(group.assignment.lost ? { lost: { ...group.assignment.lost, reason: lostReasonWithoutMachine(group.assignment.lost.reason) } } : {}) }return { ...group, ...(assignment ? { assignment } : {}),...(group.lostAttempt ? { lostAttempt: { id: group.lostAttempt.id, agentId: group.lostAttempt.agentId } } : {}) }diff --git a/backend/src/superTabs/parts/index.ts b/backend/src/superTabs/parts/index.tsindex bac7f463a..3a89a67b2 100644--- a/backend/src/superTabs/parts/index.ts+++ b/backend/src/superTabs/parts/index.ts@@ -7,7 +7,7 @@ export * from './types.js'export { clock, createClock } from './clock.js'export { knownKind, reassemble, split, toLegacyState } from './shape.js'-export { DORMANT_PAGE, insertParts, lastChangedAt, loadAccess, loadActive, loadAll, loadChanged, loadDelta, loadDormant, loadFinishedStarts, loadGroups, loadGroupUnless, loadMachineParts, loadMachines, loadMachineAccounts, loadNamed, loadObserved, loadReadBase, loadStartsOfAgents } from './load.js'+export { DORMANT_PAGE, FEED_IDS, FEED_PAGE, FEED_READS, insertParts, lastChangedAt, loadAccess, loadActive, loadAll, loadChanged, loadDelta, loadDormant, loadFeed, loadFinishedStarts, loadGroups, loadGroupUnless, loadMachineParts, loadMachines, loadMachineAccounts, loadNamed, loadObserved, loadReadBase, loadStartsOfAgents } from './load.js'export type { SwarmDelta } from './load.js'export { loadLight, loadLightGroups } from './light.js'export { guardedWrite, PartConflict, type PartWrite } from './write.js'diff --git a/backend/src/superTabs/parts/indexed.ts b/backend/src/superTabs/parts/indexed.tsindex 49326507b..a7277c3d4 100644--- a/backend/src/superTabs/parts/indexed.ts+++ b/backend/src/superTabs/parts/indexed.ts@@ -17,6 +17,8 @@ export const GROUP_INDEX = {key: { tabId: 1, key: 1 },running: { tabId: 1, executionMachineId: 1 },agents: { tabId: 1, agentIds: 1 },+ /** A person's Tasks feed pages, newest activity first (read/personalTasks.ts, task #4203). */+ feed: { tabId: 1, feedIds: 1, lastActivityAt: 1, key: 1 },project: { tabId: 1, projectId: 1, dormant: 1, lastActivityAt: 1, key: 1 },dormancy: { tabId: 1, dormant: 1, changedAt: 1 },/** Groups active since a time, in every Swarm: the scorecard's projects with a day to count (scorecard/job.ts). */diff --git a/backend/src/superTabs/parts/load.ts b/backend/src/superTabs/parts/load.tsindex f0a5448bb..47cd6a4d5 100644--- a/backend/src/superTabs/parts/load.ts+++ b/backend/src/superTabs/parts/load.ts@@ -353,6 +353,30 @@ export async function loadDormant(tx: Transaction, tabId: string,return [...same, ...older].map(row => toPart<GroupData>('group', rawGroupRow(row)))}+export const FEED_PAGE = 50+/** Most reads one feed page makes: rows its reads return that the feed then refuses are rare (the reads leave out other+ * memberships and lost projects), so a page that would need more ends there, and says so (read/personalTasks.ts). */+export const FEED_READS = 3+/** Most ids one feed read names: the person and their newest own agents. The index serves an `$in` of up to 200 as points. */+export const FEED_IDS = 200++/** The conversations naming any of `ids` in their feed column (read/feedIds.ts) in `projectIds` (null: stored with no project),+ * newest activity first, then by key, at most FEED_PAGE, each with its stored activity time for the next cursor. The projects+ * are the reader's readable ones: a task in a project they lost is left behind in the database, never read out to be skipped.+ * A later page reads as loadDormant's do: the rest of its cursor's moment by key, then what is older, each bounded by the+ * `feed` index. */+export async function loadFeed(tx: Transaction, tabId: string, ids: string[], projectIds: Array<string | null>,+ before?: { lastActivityAt: number; key: string }): Promise<Array<{ part: Part<GroupData>; activityAt: number }>> {+ if (!ids.length || !projectIds.length) return []+ const read = async (match: Where, limit: number) => limit <= 0 ? [] : groupsBy(tx, 'feed', [+ { $match: { tabId, deleted: false, feedIds: { $in: ids.slice(0, FEED_IDS) }, projectId: { $in: projectIds }, ...match } as Prisma.InputJsonValue },+ { $sort: { lastActivityAt: -1, key: -1 } }, { $limit: limit }])+ const at = before && { $date: new Date(before.lastActivityAt).toISOString() }+ const same = before ? await read({ lastActivityAt: at, key: { $lt: before.key } }, FEED_PAGE) : []+ const older = await read(at ? { lastActivityAt: { $lt: at } } : {}, FEED_PAGE - same.length)+ return [...same, ...older].map(row => ({ part: toPart<GroupData>('group', rawGroupRow(row)), activityAt: ms(row.lastActivityAt) }))+}+/** The newest data change of each Swarm, over all its parts (design section 3.7). A touch does not count.* One `$group` with `$max` per part kind, run by Mongo itself: Prisma's groupBy here can panic its engine on Mongo, which* then fails every later query of the process (as groupBy on SuperTabDecision did, 2026-10-27). */diff --git a/backend/src/superTabs/parts/write.test.ts b/backend/src/superTabs/parts/write.test.tsindex e3e116dc6..d00b3f13f 100644--- a/backend/src/superTabs/parts/write.test.ts+++ b/backend/src/superTabs/parts/write.test.ts@@ -78,3 +78,35 @@ describe('which hosts a write concerns', () => {expect(update('progress', {})).toEqual([])})})++describe('the feed ids a conversation write stores (read/feedIds.ts, task #4203)', () => {+ const work = { id: 'w', agentId: 'worker', status: 'done' as const, configuration: { engine: 'codex', model: null, effort: null, contextWindow: null, engineVersion: null },+ execution: { machineId: 'm', harnessId: 'h', machineOwnerId: 'machine-owner', contributorId: 'runner' }, result: null }+ const proposal = { version: 1, text: 'Keep drafts', goal: 'Drafts', why: 'Loss', doneWhen: 'Returns', evidence: ['Repro'], priority: 'P2', createdAt: 1, questions: [],+ senders: [{ personId: 'proposer', generation: 'g1' }, { personId: 'asker', generation: 'g2' }] } as NonNullable<GroupData['proposal']>+ const task = (change: Partial<GroupData> = {}): GroupData => ({ id: 'g', projectId: 'p', title: 'Work', leadId: 'lead', agentIds: ['lead', 'worker'],+ archived: true, dormant: true, brief: '', checks: [], lastMessageSequence: 0, requesterId: 'asker', assignment: work, ...change })+ const ids = (data: GroupData) => (extracted('group', data, 1).feedIds as string[]).sort()++ it('names who asked as the feed checks it: the approver or the proposal senders at their membership, else the requester', () => {+ expect(ids(task())).toEqual(['asker', 'runner', 'worker'])+ expect(ids(task({ taskApproval: { personId: 'asker', generation: 'g1', state: 'approved', createdAt: 1, suggestedAgentId: 'suggested' }, proposal })))+ .toEqual(['asker:g1', 'runner', 'worker'])+ expect(ids(task({ proposal }))).toEqual(['asker:g2', 'proposer:g1', 'runner', 'worker'])+ })++ it('names the agent about to do it, and the login its agent ran under, which outlives the agent', () => {+ expect(ids(task({ requesterId: undefined, assignment: null, taskApproval: { personId: 'approver', generation: 'g1', state: 'proposal', createdAt: 1,+ suggestedAgentId: 'suggested' } }))).toEqual(['approver:g1', 'suggested'])+ })++ it('names nobody for a conversation that is no task, or a proposal merged into another', () => {+ for (const change of [{ kind: 'buddy' as const }, { kind: 'agent-chat' as const }, { audience: { people: [{ id: 'asker', generation: 'g1' }] } }, { reviewOf: 'task' },+ { proposal: { ...proposal, mergedInto: 'other' } }])+ expect(ids(task(change as Partial<GroupData>))).toEqual([])+ })++ it('never names the machine owner, whose login the agent may not run under', () => {+ expect(ids(task())).not.toContain('machine-owner')+ })+})diff --git a/backend/src/superTabs/parts/write.ts b/backend/src/superTabs/parts/write.tsindex 5ab3ff99e..ca8ac1b16 100644--- a/backend/src/superTabs/parts/write.ts+++ b/backend/src/superTabs/parts/write.ts@@ -5,6 +5,7 @@ import { activeWork, stableId, type AgentStart, type Agent } from '../model.js'import type { GroupData, MachineData, PartKind } from './types.js'import { RETENTION_MS } from './types.js'import { ALL_HOSTS, noteChange } from '../cache.js'+import { feedIdsOf } from '../read/feedIds.js'type Transaction = Prisma.TransactionClientconst json = (value: unknown): Prisma.InputJsonValue => JSON.parse(JSON.stringify(value)) as Prisma.InputJsonValue@@ -109,7 +110,7 @@ export function extracted(kind: PartKind, data: unknown, stamp: number): Record<const group = data as GroupData, dueAt = proposalDueAt(group.proposal)return { projectId: group.projectId ?? null, kind: group.kind ?? null, archived: group.archived, dormant: !!group.dormant,proposalDueAt: dueAt == null ? null : new Date(dueAt),- agentIds: group.agentIds, executionMachineId: activeWork(group) ? group.assignment!.execution.machineId : null,+ agentIds: group.agentIds, feedIds: feedIdsOf(group), executionMachineId: activeWork(group) ? group.assignment!.execution.machineId : null,messageSeq: group.messageSeq ?? 0, reportSeq: group.reportSeq ?? 0,lastActivityAt: group.lastActivityAt ? new Date(group.lastActivityAt) : new Date(stamp), hostDigest: hostDigest(group),// A step is never marked by a write: it archives with its task (task steps design; steps.ts endSteps), not on its own clock.diff --git a/backend/src/superTabs/read/feedIds.ts b/backend/src/superTabs/read/feedIds.tsnew file mode 100644index 000000000..6e5f1abd7--- /dev/null+++ b/backend/src/superTabs/read/feedIds.ts@@ -0,0 +1,55 @@+import type { PrismaClient } from '@prisma/client'+import type { Conversation } from '../model.js'++type FeedFields = Pick<Conversation, 'kind' | 'audience' | 'reviewOf' | 'requesterId' | 'taskApproval' | 'proposal' | 'assignment'>++/** A person at one membership, as an approval or a proposal names them: a later membership of the same account matches none. */+export const askedKey = (personId: string, generation: string): string => `${personId}:${generation}`++/**+ * The keys whose Tasks feed lists a task (read/personalTasks.ts, task #4203), exactly as the feed counts a task as the+ * reader's: who asked (the approver or proposal senders at their membership, else the requester), the login its agent runs+ * under, which outlives the agent, and the agent doing it or suggested for it. Stored as the conversation's indexed `feedIds`+ * on every write (parts/write.ts extracted), so a page is one read of the reader's keys and own agents. A conversation that+ * is no task, and a proposal merged into another, names nobody.+ */+export function feedIdsOf(group: FeedFields): string[] {+ if (group.kind || group.audience || group.reviewOf || group.proposal?.mergedInto) return []+ const approval = group.taskApproval+ const asked = approval ? [askedKey(approval.personId, approval.generation)]+ : group.proposal ? group.proposal.senders.map(s => askedKey(s.personId, s.generation)) : [group.requesterId]+ const ids = [...asked, group.assignment?.execution?.contributorId, group.assignment?.agentId ?? approval?.suggestedAgentId]+ return [...new Set(ids.filter((id): id is string => typeof id === 'string' && !!id))]+}++const BATCH = 500+type Stored = { _id: string; tabId: string; data?: FeedFields }++/** Run once by the worker at startup, as markFinishedGroups is: sets `feedIds` on every part written before it, 500 at a time.+ * Remove it, and its call in worker.ts, after 2026-12-07: by then every Swarm's rows carry the column (its unindexed match reads+ * the whole collection on each start).+ * An assignment from before its agent's login was stored takes it from the agent's row while that row (or its tombstone) is+ * there. Every later write sets the column itself. Returns how many it set; throws when the database refuses any write. */+export async function markFeedIds(db: PrismaClient): Promise<number> {+ let set = 0+ for (;;) {+ const rows = await db.swarmGroup.aggregateRaw({ pipeline: [{ $match: { feedIds: { $exists: false } } }, { $limit: BATCH },+ { $project: { tabId: 1, 'data.kind': 1, 'data.audience': 1, 'data.reviewOf': 1, 'data.requesterId': 1, 'data.taskApproval': 1, 'data.proposal.senders': 1,+ 'data.proposal.mergedInto': 1, 'data.assignment.agentId': 1, 'data.assignment.execution.contributorId': 1 } }] }) as unknown as Stored[]+ if (!rows.length) return set+ const agentOf = (row: Stored) => row.data?.assignment && !row.data.assignment.execution?.contributorId ? `${row.tabId}:${row.data.assignment.agentId}` : null+ const named = [...new Set(rows.map(agentOf).filter((id): id is string => !!id))]+ const agents = named.length ? await db.swarmAgent.aggregateRaw({ pipeline: [{ $match: { _id: { $in: named } } }, { $project: { contributorId: 1 } }] }) as+ unknown as Array<{ _id: string; contributorId?: string }> : []+ const contributors = new Map(agents.map(a => [a._id, a.contributorId]))+ const reply = await db.$runCommandRaw({ update: 'SwarmGroup', updates: rows.map(row => {+ const data = row.data ?? {} as FeedFields, contributorId = contributors.get(agentOf(row) ?? '')+ const filled = contributorId ? { ...data, assignment: { ...data.assignment!, execution: { ...data.assignment!.execution, contributorId } } } : data+ return { q: { _id: row._id }, u: { $set: { feedIds: feedIdsOf(filled) } } }+ }) }) as { writeErrors?: unknown[] }+ // A refused row would come back in the next batch, and that batch again, for ever.+ if (reply.writeErrors?.length) throw new Error(`The database refused ${reply.writeErrors.length} of ${rows.length} Tasks feed id writes`)+ set += rows.length+ if (rows.length < BATCH) return set+ }+}diff --git a/backend/src/superTabs/read/personalTasks.test.ts b/backend/src/superTabs/read/personalTasks.test.tsindex dbb6bee33..0ee145229 100644--- a/backend/src/superTabs/read/personalTasks.test.ts+++ b/backend/src/superTabs/read/personalTasks.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest'-import { personalTasksFor } from './personalTasks.js'+import { personalTasksFor, personalTasksPage } from './personalTasks.js'import { readerView } from './views.js'import { fullSwarm, NOW, owner, peer, outsider } from './fixture.test-support.js'import * as parts from '../parts/index.js'@@ -40,27 +40,25 @@ describe('personal Tasks summaries', () => {if (proposal) data.proposal = { version: 1, text: 'Keep drafts', goal: 'Drafts', why: 'Loss', doneWhen: 'Returns', evidence: ['Repro'], priority: 'P2',createdAt: NOW, questions: [], senders: [{ personId: peer.userId, generation: s.f.state.people.find(p => p.id === peer.userId)!.generation }],...proposal === 'undecided' ? {} : { decision: { kind: proposal, reason: 'PM', at: NOW, by: 'lead' } } }- for (const reset of [true, false])- expect(personalTasksFor([row], s.view(), peer, reset)!.upserts).toEqual([expect.objectContaining({ id: row.key, canApprove })])+ expect(personalTasksFor([row], s.view(), peer)!.upserts).toEqual([expect.objectContaining({ id: row.key, canApprove })])})it.each(['foreign', 'stale'])('never exposes an actionable pending approval for a %s membership', kind => {const s = scene(), row = s.stored.groups.find(g => g.key === s.f.web)!, data = row.data!data.assignment = nulldata.taskApproval = { ...data.taskApproval!, state: 'proposal',...kind === 'foreign' ? { personId: owner.userId } : { generation: 'previous-membership' } }- expect(personalTasksFor([row], s.view(), peer, true)!.upserts).toEqual([])- expect(personalTasksFor([row], s.view(), peer, false)).toMatchObject({ upserts: [], removed: [row.key] })+ expect(personalTasksFor([row], s.view(), peer)).toMatchObject({ upserts: [], removed: [row.key] })})it('includes only my visible requested tasks and proposals, with project, assigned identity and execution status', () => {- const s = scene(), feed = personalTasksFor(s.stored.groups, s.view(), peer, true)!- expect(feed).toMatchObject({ approvalMode: 'review', reset: true, removed: [] })+ const s = scene(), feed = personalTasksFor(s.stored.groups, s.view(), peer)!+ expect(feed).toMatchObject({ approvalMode: 'review', reset: false })expect(feed.upserts.map(r => r.id)).toEqual(expect.arrayContaining([s.f.web, s.f.secretGroup]))expect(feed.upserts.find(r => r.id === s.f.web)).toMatchObject({ version: 7, at: NOW, projectId: 'lead', projectName: 'Pilot',title: 'Web', status: 'working', suggested: false, agent: { id: s.f.worker, name: expect.any(String) } })expect(feed.upserts.some(r => r.id === s.f.done || r.id === s.f.buddyChat)).toBe(false)- expect(personalTasksFor(s.stored.groups, s.view(outsider), outsider, true)!.upserts).toEqual([])+ expect(personalTasksFor(s.stored.groups, s.view(outsider), outsider)!.upserts).toEqual([])const agent: Actor = { kind: 'agent', agentId: s.f.lead, machineOwnerId: `${owner.userId}-machine` }- expect(personalTasksFor(s.stored.groups, s.view(agent), agent, true)).toBeUndefined()+ expect(personalTasksFor(s.stored.groups, s.view(agent), agent)).toBeUndefined()})it('shows proposal/rejected, suggested identity and reason, newest first with stable id ties', () => {const s = scene(), group = s.stored.groups.find(g => g.key === s.f.web)!@@ -68,33 +66,79 @@ describe('personal Tasks summaries', () => {data.assignment = nulldata.taskApproval = { ...data.taskApproval!, state: 'proposal', suggestedAgentId: s.f.worker }const proposal = { ...structuredClone(group), key: 'proposal', changedAt: NOW + 1,- data: { ...structuredClone(data), id: 'proposal', taskApproval: { ...data.taskApproval!, state: 'rejected' as const, reason: 'Too much scope' } } }- const feed = personalTasksFor([group, proposal], s.view(), peer, true)!+ data: { ...structuredClone(data), id: 'proposal', lastActivityAt: new Date(NOW + 1).toISOString(), taskApproval: { ...data.taskApproval!, state: 'rejected' as const, reason: 'Too much scope' } } }+ const feed = personalTasksFor([group, proposal], s.view(), peer)!expect(feed.upserts.map(r => [r.id, r.status])).toEqual([['proposal', 'rejected'], [s.f.web, 'proposal']])expect(feed.upserts[0]).toMatchObject({ reason: 'Too much scope', suggested: true, agent: { id: s.f.worker } })})- it('returns one changed summary or idle empty output; removes archived, reassigned, merged and deleted cards', () => {+ it('returns one changed summary or idle empty output; keeps archived and dormant history; removes reassigned, merged and deleted cards', () => {const s = scene(), row = s.stored.groups.find(g => g.key === s.f.web)!- expect(personalTasksFor([], s.view(), peer, false)!.upserts).toEqual([])- expect(personalTasksFor([row], s.view(), peer, false)!.upserts.map(r => r.id)).toEqual([row.key])- for (const change of [{ archived: true }, { requesterId: owner.userId, taskApproval: undefined }, { dormant: true }]) {- const changed = { ...row, data: { ...row.data!, ...change } }- expect(personalTasksFor([changed], s.view(), peer, false)).toMatchObject({ upserts: [], removed: [row.key] })- }- expect(personalTasksFor([{ ...row, deleted: true }], s.view(), peer, false)).toMatchObject({ upserts: [], removed: [row.key] })- expect(personalTasksFor([{ ...row, data: { ...row.data!, proposal: { mergedInto: 'other' } as never } }], s.view(), peer, false))+ expect(personalTasksFor([], s.view(), peer)!.upserts).toEqual([])+ expect(personalTasksFor([row], s.view(), peer)!.upserts.map(r => r.id)).toEqual([row.key])+ for (const change of [{ archived: true }, { dormant: true }, { archived: true, dormant: true }])+ expect(personalTasksFor([{ ...row, dormant: true as const, data: { ...row.data!, ...change } }], s.view(), peer))+ .toMatchObject({ upserts: [{ id: row.key, status: 'working' }], removed: [] })+ expect(personalTasksFor([{ ...row, data: { ...row.data!, requesterId: owner.userId, taskApproval: undefined } }], s.view(), peer)).toMatchObject({ upserts: [], removed: [row.key] })+ expect(personalTasksFor([{ ...row, deleted: true }], s.view(), peer)).toMatchObject({ upserts: [], removed: [row.key] })+ expect(personalTasksFor([{ ...row, data: { ...row.data!, proposal: { mergedInto: 'other' } as never } }], s.view(), peer))+ .toMatchObject({ upserts: [], removed: [row.key] })+ })++ it('lists what my own agents did, do or are about to do for anyone, by the login they run under, never by machine owner', () => {+ const s = scene(), row = s.stored.groups.find(g => g.key === s.f.done)!+ const mine = { ...s.f.state.agents.find(a => a.id === s.f.worker)!, id: 'peer-agent', harnessId: 'peer-harness', contributorId: peer.userId }+ const lent = { ...mine, id: 'lent-agent', harnessId: 'lent-harness', contributorId: owner.userId, machineOwnerId: peer.userId }+ const stored = parts.split({ ...s.f.state, agents: [...s.f.state.agents, mine, lent] }, { tabId: 'tab', version: 7, now: NOW })+ const view = readerView(stored, peer, NOW, { teamMachines: [] })+ const work = (agentId: string) => ({ ...s.f.state.conversations.find(c => c.id === s.f.web)!.assignment!, agentId, status: 'done' as const })+ const did = { ...row, dormant: true as const, data: { ...row.data!, requesterId: owner.userId, archived: true, dormant: true, assignment: work(mine.id) } }+ expect(personalTasksFor([did], view, peer)!.upserts).toEqual([expect.objectContaining({ id: row.key, status: 'done', agent: expect.objectContaining({ id: mine.id }) })])+ expect(personalTasksFor([did], view, owner)!.upserts.map(r => r.id)).toEqual([row.key])+ const soon = { ...did, data: { ...did.data, assignment: null, taskApproval: { personId: owner.userId, generation: 'any', state: 'proposal' as const, createdAt: NOW, suggestedAgentId: mine.id } } }+ // Another person's pending approval that suggests my agent is listed, never as mine to approve (security review 2 of #3465).+ expect(personalTasksFor([soon], view, peer)!.upserts).toEqual([expect.objectContaining({ id: row.key, suggested: true, canApprove: false })])+ const generation = s.f.state.people.find(p => p.id === peer.userId)!.generation+ const mineToApprove = { ...soon, data: { ...soon.data, taskApproval: { ...soon.data.taskApproval, personId: peer.userId, generation } } }+ expect(personalTasksFor([mineToApprove], view, peer)!.upserts).toEqual([expect.objectContaining({ id: row.key, canApprove: true })])+ expect(personalTasksFor([{ ...did, data: { ...did.data, assignment: work(lent.id) } }], view, peer)).toMatchObject({ upserts: [], removed: [row.key] })+ // Its agent closed since: the task stays, by the login the agent ran under (code review of #3465).+ const closed = { ...did, data: { ...did.data, assignment: { ...work('closed-agent'), execution: { ...work('closed-agent').execution, contributorId: peer.userId } } } }+ expect(personalTasksFor([closed], view, peer)!.upserts).toEqual([expect.objectContaining({ id: row.key, status: 'done', agent: null })])+ expect(personalTasksFor([closed], view, owner)!.upserts.map(r => r.id)).toEqual([row.key])+ })++ it('reads by at most 200 keys: the person\'s two and their newest 198 agents (review of #3465)', async () => {+ const s = scene(), template = s.f.state.agents.find(a => a.id === s.f.worker)!+ const agents = Array.from({ length: 250 }, (_, i) => ({ ...template, id: `agent-${String(i).padStart(3, '0')}`, harnessId: `h-${i}`, contributorId: peer.userId }))+ const stored = parts.split({ ...s.f.state, agents: [...s.f.state.agents, ...agents] }, { tabId: 'tab', version: 7, now: NOW })+ let read: string[] = []+ await personalTasksPage(async ids => { read = ids; return [] }, readerView(stored, peer, NOW, { teamMachines: [] }), peer)+ expect(read).toHaveLength(200)+ expect(read).toEqual(expect.arrayContaining([peer.userId, 'agent-249', 'agent-052']))+ expect(read).not.toContain('agent-051')+ })++ it('carries who asked and the newest linked pull request', () => {+ const s = scene(), row = s.stored.groups.find(g => g.key === s.f.web)!+ row.data!.pullRequestUrls = ['https://github.com/o/r/pull/1', 'https://github.com/o/r/pull/2']+ const [task] = personalTasksFor([row], s.view(), peer)!.upserts+ expect(task).toMatchObject({ requester: { id: peer.userId }, pullRequestUrl: 'https://github.com/o/r/pull/2' })+ s.stored.members.find(m => m.key === peer.userId)!.data!.name = 'Peer Person'+ expect(personalTasksFor([row], s.view(), peer)!.upserts[0]!.requester).toEqual({ id: peer.userId, name: 'Peer Person' })+ delete row.data!.pullRequestUrls+ expect(personalTasksFor([row], s.view(), peer)!.upserts[0]).not.toHaveProperty('pullRequestUrl')})it('never leaks a hidden project, private chat, hidden agent or stale membership proposal', () => {const s = scene(), row = s.stored.groups.find(g => g.key === s.f.secretGroup)!const hidden = s.f.state.agents.find(a => a.projectId === s.f.secret)s.stored.head.data!.projects!.find(p => p.id === s.f.secret)!.members = []- expect(personalTasksFor([row], s.view(), peer, false)).toMatchObject({ upserts: [], removed: [] })+ expect(personalTasksFor([row], s.view(), peer)).toMatchObject({ upserts: [], removed: [] })const web = s.stored.groups.find(g => g.key === s.f.web)!web.data!.assignment!.agentId = hidden?.id ?? 'hidden-agent'- expect(personalTasksFor([web], s.view(), peer, true)!.upserts[0]!.agent).toBeNull()+ expect(personalTasksFor([web], s.view(), peer)!.upserts[0]!.agent).toBeNull()web.data!.taskApproval!.generation = 'old-membership'- expect(personalTasksFor([web], s.view(), peer, true)!.upserts).toEqual([])+ expect(personalTasksFor([web], s.view(), peer)!.upserts).toEqual([])})it('shows legacy or Board proposals before a task exists, without duplicate merged mirrors', () => {const s = scene(), row = s.stored.groups.find(g => g.key === s.f.web)!@@ -102,8 +146,8 @@ describe('personal Tasks summaries', () => {row.data!.assignment = nullrow.data!.proposal = { version: 1, text: 'Keep drafts', goal: 'Drafts', why: 'Loss', doneWhen: 'Returns', evidence: ['Repro'], priority: 'P2',createdAt: NOW, questions: [], senders: [{ personId: peer.userId, generation: s.f.state.people.find(p => p.id === peer.userId)!.generation }] }- expect(personalTasksFor([row], s.view(), peer, true)!.upserts[0]!.status).toBe('proposal')+ expect(personalTasksFor([row], s.view(), peer)!.upserts[0]!.status).toBe('proposal')row.data!.proposal.mergedInto = 'prepared-task'- expect(personalTasksFor([row], s.view(), peer, false)!.removed).toEqual([row.key])+ expect(personalTasksFor([row], s.view(), peer)!.removed).toEqual([row.key])})})diff --git a/backend/src/superTabs/read/personalTasks.ts b/backend/src/superTabs/read/personalTasks.tsindex 91d3d6524..149b96b49 100644--- a/backend/src/superTabs/read/personalTasks.ts+++ b/backend/src/superTabs/read/personalTasks.ts@@ -1,18 +1,27 @@-import type { Actor, Conversation } from '../model.js'-import type { Part } from '../parts/types.js'-import { canReadGroup, groupProject } from '../projects.js'+import type { Actor, Conversation, Person } from '../model.js'+import type { GroupData, Part } from '../parts/types.js'+import { FEED_IDS, FEED_PAGE, FEED_READS } from '../parts/load.js'+import { canReadGroup, canReadProject, groupProject } from '../projects.js'+import { logger } from '../../utils/logger.js'+import { askedKey } from './feedIds.js'import { undecidedProposal, type ApprovalMode } from '../taskApproval.js'import type { AgentView } from './contract.js'+import { decodeDormantPage } from './dormantPage.js'import type { ReaderView } from './views.js'export interface PersonalTask {id: stringversion: number+ /** Its last activity (ms): the feed's order, newest first, and its pages'. */at: numberprojectId: stringprojectName: stringtitle: stringagent: { id: string; name: string; avatar?: AgentView['avatar'] } | null+ /** The person who asked for it, when the Swarm still lists them: the name they show or chose, absent when neither is set. */+ requester: { id: string; name?: string; avatar?: Person['avatar'] } | null+ /** Its newest linked pull request. */+ pullRequestUrl?: stringstatus: import('../model.js').WorkStatus | 'proposal' | 'rejected'suggested: booleancanApprove: boolean@@ -23,39 +32,112 @@ export interface PersonalTasks {reset: booleanupserts: PersonalTask[]removed: string[]+ /** A first load's or a page's cursor for the next older page (SwarmReads.personalTasks); null when there is none. A change+ * poll sends none: it carries only what changed. */+ olderCursor?: string | null}-/** First load supplies its active groups; a poll supplies only its changed parts. No history read or second cursor. */-export function personalTasksFor(changed: readonly Part[], view: ReaderView, actor: Actor, reset: boolean): PersonalTasks | undefined {+/** Who reads a feed: the person and their own agents, those running under their login (Desktop's My agents), never by+ * machine owner and never another person's Buddy; the newest FEED_IDS − 2 of them, after the person's own two keys. */+interface Reader { actor: Actor; member: Person; agents: Set<string>; view: ReaderView }++function readerOf(view: ReaderView, actor: Actor): Reader | undefined {if (actor.kind !== 'person') return undefinedconst member = view.state.people.find(p => p.id === actor.userId)if (!member) return undefined- const agents = new Map(view.parts.agents.map(a => [a.key, a.data]))- const out: PersonalTasks = { approvalMode: member.approvalMode ?? 'autoApprove', reset, upserts: [], removed: [] }+ const own = view.state.agents.filter(a => a.contributorId === member.id && (!a.buddyOf || a.buddyOf.personId === member.id))+ return { actor, member, view, agents: new Set(own.slice(-(FEED_IDS - 2)).map(a => a.id)) }+}++/** The keys a page of the reader's feed reads by (read/feedIds.ts): theirs at this membership, their id and their own agents. */+const feedReadIds = (reader: Reader): string[] => [askedKey(reader.member.id, reader.member.generation), reader.member.id, ...reader.agents]++/** The projects whose tasks the reader may read; null too for conversations stored with no project, which are the default one's. */+function readableProjects(reader: Reader): Array<string | null> {+ const ids = (reader.view.state.projects ?? []).filter(p => canReadProject(reader.view.state, reader.actor, p)).map(p => p.id)+ return ids.includes('lead') ? [...ids, null] : ids+}++const activityAt = (part: Part<GroupData>): number => Date.parse(part.data?.lastActivityAt ?? '') || part.changedAt++/** One changed part as the reader's feed takes it: a row, gone from the feed, or none of the reader's business (never said). */+function summary(part: Part, reader: Reader): PersonalTask | 'gone' | null {+ if (part.kind !== 'group' || !part.data) return null+ const group = part.data as Conversation, { actor, member, view } = reader+ // Every id, including a removal's, passes today's read rules; revocation uses the existing visibility epoch reload.+ try { if (!canReadGroup(view.state, actor, group)) return null } catch { return null }+ if (group.kind || group.audience || group.reviewOf) return null+ const project = groupProject(view.state, group)+ if (group.id === project.leadConversationId) return null+ const approval = group.taskApproval+ const asked = approval ? approval.personId === member.id && approval.generation === member.generation+ : group.proposal ? group.proposal.senders.some(s => s.personId === member.id && s.generation === member.generation)+ : group.requesterId === member.id+ // Did, doing or about to do: its assignee, or the agent suggested before anyone is assigned; or an agent that ran under the+ // reader's login, closed since (read/feedIds.ts).+ const worker = group.assignment?.agentId ?? approval?.suggestedAgentId+ const own = asked || (!!worker && reader.agents.has(worker)) || group.assignment?.execution?.contributorId === member.id+ if (part.deleted || group.proposal?.mergedInto || !own) return 'gone'+ const agent = view.parts.agents.find(a => a.key === worker)?.data+ const asker = group.requesterId ? view.state.people.find(p => p.id === group.requesterId) : undefined+ const askerName = asker && (asker.name ?? asker.username)+ const status = approval?.state === 'proposal' || approval?.state === 'rejected' ? approval.state+ : group.assignment?.status ?? (group.proposal && !['accept', 'reshape'].includes(group.proposal.decision?.kind ?? '') ? 'proposal' : 'planned')+ const pullRequestUrl = group.pullRequestUrls?.at(-1)+ return { id: group.id, version: part.version, at: activityAt(part as Part<GroupData>), projectId: project.id, projectName: project.name,+ title: group.title, status, suggested: !group.assignment && !!approval?.suggestedAgentId, canApprove: approval?.state === 'proposal' && asked && !undecidedProposal(group),+ agent: agent ? { id: agent.id, name: agent.displayName ?? agent.name, ...agent.avatar ? { avatar: agent.avatar } : {} } : null,+ requester: asker ? { id: asker.id, ...askerName ? { name: askerName } : {}, ...asker.avatar ? { avatar: asker.avatar } : {} } : null,+ ...pullRequestUrl ? { pullRequestUrl } : {}, ...approval?.reason ? { reason: approval.reason } : {} }+}++const newestFirst = (a: PersonalTask, b: PersonalTask) => b.at - a.at || a.id.localeCompare(b.id)++/** A change poll's feed: a summary of each changed part of the reader's, and the ids that left it. Dormant and archived+ * tasks stay: the feed is their history. */+export function personalTasksFor(changed: readonly Part[], view: ReaderView, actor: Actor): PersonalTasks | undefined {+ const reader = readerOf(view, actor)+ if (!reader) return undefined+ const out: PersonalTasks = { approvalMode: reader.member.approvalMode ?? 'autoApprove', reset: false, upserts: [], removed: [] }for (const part of changed) {- if (part.kind !== 'group' || !part.data) continue- const group = part.data as Conversation- // Every id, including a removal's, passes today's read rules; revocation uses the existing visibility epoch reload.- try { if (!canReadGroup(view.state, actor, group)) continue } catch { continue }- if (group.kind || group.audience || group.reviewOf) continue- const project = groupProject(view.state, group)- if (group.id === project.leadConversationId) continue- const approval = group.taskApproval- const own = approval ? approval.personId === member.id && approval.generation === member.generation- : group.proposal ? group.proposal.senders.some(s => s.personId === member.id && s.generation === member.generation)- : group.requesterId === member.id- if (part.deleted || part.dormant || group.archived || group.dormant || group.proposal?.mergedInto || !own) {- if (!reset) out.removed.push(part.key)- continue- }- const worker = agents.get(group.assignment?.agentId ?? approval?.suggestedAgentId ?? '')- const status = approval?.state === 'proposal' || approval?.state === 'rejected' ? approval.state- : group.assignment?.status ?? (group.proposal && !['accept', 'reshape'].includes(group.proposal.decision?.kind ?? '') ? 'proposal' : 'planned')- out.upserts.push({ id: group.id, version: part.version, at: part.changedAt, projectId: project.id, projectName: project.name,- title: group.title, status, suggested: !group.assignment && !!approval?.suggestedAgentId, canApprove: approval?.state === 'proposal' && !undecidedProposal(group),- agent: worker ? { id: worker.id, name: worker.displayName ?? worker.name, ...worker.avatar ? { avatar: worker.avatar } : {} } : null,- ...approval?.reason ? { reason: approval.reason } : {} })+ const row = summary(part, reader)+ if (row === 'gone') out.removed.push(part.key)+ else if (row) out.upserts.push(row)}- out.upserts.sort((a, b) => b.at - a.at || a.id.localeCompare(b.id))+ out.upserts.sort(newestFirst)return out}++type FeedRead = (ids: string[], projectIds: Array<string | null>, before?: { lastActivityAt: number; key: string }) =>+ Promise<Array<{ part: Part<GroupData>; activityAt: number }>>++/** A page of the reader's feed, newest first: the first (a first load's, `reset`) or the one older than `cursor`. Rows the+ * reader may not read never shorten a page, and the cursor names the last row it returns, never a hidden one (as the+ * dormant pager, security review 2 of #2115). Each batch reads on from the last row of the one before. */+export async function personalTasksPage(read: FeedRead, view: ReaderView, actor: Actor, cursor?: string): Promise<PersonalTasks | undefined> {+ let before = cursor ? decodeDormantPage(cursor) : undefined+ const reader = readerOf(view, actor)+ if (!reader) return undefined+ const ids = feedReadIds(reader), projects = readableProjects(reader), upserts: PersonalTask[] = []+ let last: { lastActivityAt: number; key: string } | undefined, more = false+ for (let reads = 1; ; reads++) {+ const rows = await read(ids, projects, before)+ for (const { part, activityAt } of rows) {+ const row = summary(part, reader)+ if (!row || row === 'gone') continue+ if (upserts.length === FEED_PAGE) { more = true; break }+ upserts.push(row)+ last = { lastActivityAt: activityAt, key: part.key }+ }+ if (more || rows.length < FEED_PAGE) break+ if (reads === FEED_READS) {+ // Ends the feed here rather than hand out a cursor at a row it never sent: the next page would read the same rows again.+ logger.warn('[swarm-reads] a Tasks feed page ended early: its reads returned rows the feed refused', { reads, kept: upserts.length })+ break+ }+ const end = rows.at(-1)!+ before = { lastActivityAt: end.activityAt, key: end.part.key }+ }+ return { approvalMode: reader.member.approvalMode ?? 'autoApprove', reset: !cursor, upserts, removed: [],+ olderCursor: more && last ? Buffer.from(JSON.stringify({ la: last.lastActivityAt, k: last.key })).toString('base64url') : null }+}diff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.tsindex 12dfe32f1..6a92d1820 100644--- a/backend/src/superTabs/read/service.ts+++ b/backend/src/superTabs/read/service.ts@@ -1,4 +1,4 @@-import { personalTasksFor } from './personalTasks.js'+import { personalTasksFor, personalTasksPage, type PersonalTasks } from './personalTasks.js'/*** The read API by parts (design section 4; shapes in contract.ts). Every read takes its time `T0` before any query and* makes the next cursor from it, so a write that commits late, inside the overlap, is still seen by the next poll.@@ -91,6 +91,11 @@ function stamped(derived: Derived, held?: string) {return held === etag ? { derived: marksOf(derived), derivedEtag: etag, derivedUnchanged: true as const } : { derived, derivedEtag: etag }}+/** Tasks feed reads (parts/load.ts loadFeed) held at the Swarm's main stamp, which every conversation write moves: a first load of a+ * Swarm that did not change asks Mongo for nothing. The rows are shared; each reader's own checks run on every read. */+const feedRead = (tx: PrismaClient, cached: CacheView, tabId: string): Parameters<typeof personalTasksPage>[0] => (ids, projects, before) =>+ cached.get(tabId, `feed:${JSON.stringify([ids, projects, before ?? null])}`, 'main', () => parts.loadFeed(tx, tabId, ids, projects, before))+/** A change poll's light base (parts/light.ts): the same for every reader of a Swarm, so one load per stamp serves them all. */const LIGHT = { groups: 'working' } as const@@ -134,7 +139,8 @@ export class SwarmReads {return { format: READ_FORMAT, tabId, cursor: cursorFor(t0, loaded.visibilityEpoch), serverTime: t0, lastChangedAt, epoch: loaded.visibilityEpoch,// This backend opens steps (task steps design): a newer CLI sends `step` only to a backend that says so....(this.options.githubApp ? { githubApp: true as const } : {}), steps: true as const, ...view.parts,- ...read.actor.kind === 'person' ? { personalTasks: personalTasksFor(loaded.groups, view, read.actor, true) } : {},+ // The feed's newest page (task #4203): its history is read by its own index, not from the loaded working set.+ ...read.actor.kind === 'person' ? { personalTasks: await personalTasksPage(feedRead(tx, cached, tabId), view, read.actor) } : {},...stamped({ ...await this.withAvatars(view, t0), ...readableMarks(read, await this.marksOf(tx, tabId, read.actor),await this.threadMarksOf(tx, tabId, read.actor), await this.settingsOf(tx, tabId, read.actor)) }) }})@@ -221,11 +227,27 @@ export class SwarmReads {if (!asAgentId) sent.groups = await this.servedTops.served(tabId, read.view.state, sent.groups)return { format: READ_FORMAT, reload: false, cursor: cursorFor(t0, read.parts.visibilityEpoch), serverTime: t0, lastChangedAt: read.lastChangedAt,epoch: read.parts.visibilityEpoch, ...sent,- ...read.actor.kind === 'person' ? { personalTasks: personalTasksFor(changed, read.view, read.actor, false) } : {},+ ...read.actor.kind === 'person' ? { personalTasks: personalTasksFor(changed, read.view, read.actor) } : {},...stamped({ ...await this.withAvatars(read.view, t0), ...readableMarks(read, marks, threadMarks, settings) }, options.derivedEtag) }})}+ /** The person's Tasks feed page older than `before`, a first load's or an earlier page's `olderCursor` (task #4203). A person's+ * read only: an agent has no feed. */+ async personalTasks(user: AuthUser, tabId: string, before?: string): Promise<PersonalTasks> {+ const t0 = this.now()+ return this.read(user, tabId, async (tx, cached) => {+ const loaded = await readParts(tx, cached, tabId)+ const state = parts.reassemble(loaded, { share: true })+ const actor = await this.store.actor(tx, user, state)+ author(state, actor)+ const [teamMachines, otherWorkspaceMachines, machineVersions, joiningTeams] = await this.machineLookups(state)+ const view = readerView(loaded, actor, t0, { teamMachines, otherWorkspaceMachines, machineVersions, joiningTeams, teamAccountsIdle: this.store.teamAccountsIdle })+ return await personalTasksPage(feedRead(tx, cached, tabId), view, actor, before)+ ?? fail('NOT_FOUND', 'Only a member has a Tasks feed.', 404)+ })+ }+async dormant(user: AuthUser, tabId: string, page: { projectId?: string; before?: string }, asAgentId?: string): Promise<DormantGroups> {return this.read(user, tabId, async (tx, cached) => {const state = parts.reassemble(await readParts(tx, cached, tabId), { share: true })diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 26e895a83..4b81dbb24 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -5891,7 +5891,8 @@ export class SuperTabStore {await recordAttempts(tx, tabId, { ...state, conversations: before.conversations }, state, this.now())await recordEvidence(tx, tabId, { ...state, conversations: before.conversations }, state, this.now())await this.writeMessages(tx, tabId, state, notices, sequences)- if (!prior) await tx.superTabStopReceipt.create({ data: { id, tabId, assignmentId, ...execution, receipt } })+ if (!prior) await tx.superTabStopReceipt.create({ data: { id, tabId, assignmentId, machineId: execution.machineId, harnessId: execution.harnessId,+ machineOwnerId: execution.machineOwnerId, receipt } })ended = endedHolds(before, state)return { confirmed: true }})diff --git a/backend/src/worker.ts b/backend/src/worker.tsindex c76d9f4f3..f116fc2f6 100644--- a/backend/src/worker.ts+++ b/backend/src/worker.ts@@ -27,6 +27,7 @@ import { startDeliverySettle } from './superTabs/deliverySettle.js'import { startDeliveryRepush } from './superTabs/deliveryRepush.js'import { startDeliveryCompaction } from './superTabs/deliveryCompaction.js'import { startThreadBackfill } from './superTabs/threadBackfill.js'+import { markFeedIds } from './superTabs/read/feedIds.js'import { appPullRequests, markFinishedGroups, startSwarmArchive, unknownPullRequests } from './superTabs/archive.js'import { appPullRequestWatch, startPullRequestWatch } from './superTabs/pullRequestEvents.js'import { startTimeChecks } from './superTabs/timeChecks.js'@@ -70,6 +71,10 @@ async function start(): Promise<void> {const schema = await releaseSchema()// After the push, which adds the finished mark: parts written before it are marked once, so the archive pass finds them.await markFinishedGroups(prisma)+ // Likewise the Tasks feed's column (read/feedIds.ts): a person's older tasks show once it is set.+ await markFeedIds(prisma).then(count => logger.info('[swarm] Tasks feed ids set on older conversations', { count }), error =>+ logger.error('[swarm] Tasks feed ids not set on older conversations: their tasks stay out of people\'s Tasks feeds until the next worker start sets them',+ { error: error instanceof Error ? error.message : String(error) }))// AFTER the push: it creates the new collections + their unique indexes, and the copy uses $merge// so those indexes survive. Copying first would leave the unique index build to fail silently.await migrateMachineRename()diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.tsindex b1e3344c6..bc87547d9 100644--- a/backend/vitest.super-tabs.config.ts+++ b/backend/vitest.super-tabs.config.ts@@ -1,7 +1,7 @@import { defineConfig } from 'vitest/config'export default defineConfig({ test: { include: ['integration/superTabProposalCards.test.ts', 'integration/superTabs.test.ts', 'integration/superTabSharing.test.ts', 'integration/superTabAutoJoin.test.ts', 'integration/superTabGithub.test.ts', 'integration/superTabTeam.test.ts', 'integration/superTabWorkspaces.test.ts',- 'integration/superTabRead.test.ts', 'integration/superTabOneGroup.test.ts', 'integration/superTabReadMarks.test.ts', 'integration/superTabInbox.test.ts', 'integration/superTabFollowedThreads.test.ts', 'integration/superTabActivity.test.ts', 'integration/superTabMessageEdits.test.ts', 'integration/superTabReminders.test.ts', 'integration/superTabLeaderboard.test.ts', 'integration/superTabMigration.test.ts', 'integration/superTabLiveness.test.ts',+ 'integration/superTabRead.test.ts', 'integration/superTabPersonalTasksFeed.test.ts', 'integration/superTabOneGroup.test.ts', 'integration/superTabReadMarks.test.ts', 'integration/superTabInbox.test.ts', 'integration/superTabFollowedThreads.test.ts', 'integration/superTabActivity.test.ts', 'integration/superTabMessageEdits.test.ts', 'integration/superTabReminders.test.ts', 'integration/superTabLeaderboard.test.ts', 'integration/superTabMigration.test.ts', 'integration/superTabLiveness.test.ts','integration/superTabTidy.test.ts', 'integration/superTabProfile.test.ts', 'integration/superTabLegacyDrop.test.ts', 'integration/shareRaces.test.ts', 'integration/superTabIndexes.test.ts', 'integration/superTabRouteDecisions.test.ts','integration/superTabHotReads.test.ts', 'integration/swarmSweepStarts.test.ts', 'integration/superTabGroupPlans.test.ts', 'integration/superTabInvitationPlans.test.ts', 'integration/superTabCache.test.ts', 'integration/superTabCacheDelta.test.ts', 'integration/superTabHostGroups.test.ts', 'integration/superTabMachineReports.test.ts', 'integration/superTabMachineLiveness.test.ts', 'integration/superTabHeldParts.test.ts','integration/superTabObserver.test.ts', 'integration/productUsageConflicts.test.ts', 'integration/productUsageReceipts.test.ts', 'integration/schemaRelease.test.ts', 'integration/superTabBuddies.test.ts', 'integration/superTabNotAvailable.test.ts',diff --git a/docs/plans/2026-11-07-tasks-feed-history-plan.md b/docs/plans/2026-11-07-tasks-feed-history-plan.mdnew file mode 100644index 000000000..acee33d37--- /dev/null+++ b/docs/plans/2026-11-07-tasks-feed-history-plan.md@@ -0,0 +1,101 @@+# Tasks feed history implementation plan++> Implemented natively by the task's Engineer, plan task by plan task, each failing test committed before its code; one+> independent review of the pull request.++**Goal:** The person's Tasks feed lists every task their own agents did, are doing or are about to do, the tasks they asked+for and their proposals, dormant and archived ones included, newest first, with a cursor for older pages (task #4203).++**Architecture:** Each stored conversation gets one indexed column, `feedIds`: the people and agents whose feed lists it,+computed from its data on every write (parts/write.ts `extracted`) and backfilled once at worker startup. A feed page is one+read of the `(tabId, feedIds, lastActivityAt, key)` index for the person and their own agents, newest activity first, 50+readable rows a page. First load sends the first page with an `olderCursor`; a new `GET /api/super-tabs/:tabId/personal-tasks`+pages older ones; change polls keep summarising only the parts that changed since the cursor, now without dropping dormant+or archived tasks.++**Tech Stack:** TypeScript backend, Prisma on MongoDB 7, vitest with mongodb-memory-server for real-store and plan tests.++**Spec:** task #4203's brief (anh Dee, 2026-11-07 06:20 VN), extending docs/plans/2026-11-07-v3-personal-tasks-plan.md.++## Global Constraints++- Backend only; ships as a backend hotfix with Desktop 1.3.88. Old clients keep working: `personalTasks` is only extended.+- Server-enforced audience: every row passes `canReadGroup` for the reader; a cursor names only a row the reader was sent.+- Own agents are the reader's by `contributorId` (as Desktop's My agents), never by machine owner; another person's Buddy is not.+- One index per query, read with explain in an integration test: IXSCAN on `feed`, documents examined close to returned.+- Bounded: 50 rows a page; at most 200 ids in the index's `$in` (the person and their 199 newest own agents).++## Review Focus++- A task of the person's agent in a project the person lost access to never reaches them, nor its id through a cursor.+- A stale membership's approval or proposal stays out, as today, even though its person id is in `feedIds`.+- A row written before this release (no `feedIds`) shows after the startup backfill, same ids as `extracted` would write.+- Paging across rows with the same `lastActivityAt` neither repeats nor skips a row.+- A dormant or archived task that changes stays in the feed on a poll; a deleted or merged one leaves it.++## Design++- Growth: one string array per conversation (≤ requester, approver, proposal senders, assignee, suggested agent: a few ids)+ and one index entry per id; deleted with the conversation (part tombstone purge). Prod 2026-11-07: 4,612 SwarmGroup rows,+ 26.4 MB data, 3.8 MB in 15 indexes; this index adds about 2 entries a row (~0.3 MB).+- Concurrency: no new lock; the column is written in the same guarded part write as the data.+- Read cost: first load adds one indexed read of ≤ 50 rows; a page is the same; polls read only changed parts, as today.+- Scale: 10x is ~46k rows; a page still reads the 50 it returns. The first warning is the feed read's p95 in the read timing.+- Compatibility: `olderCursor` and the new row fields are additions; `at` becomes the last activity time (clients only sort by it).+ Clients from the last 30 days ignore what they don't read. Older backends never send `olderCursor`. Shape agreed with Desktop's Taskcards (#4204); Desktop picks project colours.+- Migration and rollback: `db push` adds the index; the worker's startup backfill sets `feedIds` on rows without it. A+ rollback leaves an unused column and index; nothing reads them.+- Audience: `canReadGroup` on every row before it counts toward a page; cursor from the last row sent.+- Identity: own agents by `contributorId`; the machine owner's login is never read.+- Failure: a bad cursor is `INVALID_CURSOR` (400, "Ask for the first page again."); the backfill logs how many it set.+- Platforms: backend (Linux); clients unchanged on every platform.++### Task 1: The feed column, its index and backfill++**Files:** Modify `backend/src/superTabs/read/personalTasks.ts` (add `feedIdsOf`), `backend/src/superTabs/parts/write.ts`+(`extracted`), `backend/prisma/schema.prisma`, `backend/src/superTabs/parts/indexed.ts` (`GROUP_INDEX.feed`),+`backend/src/superTabs/archive.ts` or a new `backend/src/superTabs/read/feedBackfill.ts`, `backend/src/worker.ts`.+Test: `backend/src/superTabs/read/personalTasks.test.ts`, `backend/integration/superTabPersonalTasksFeed.test.ts`.++**Interfaces:** Produces `feedIdsOf(group: Conversation): string[]` (unique ids; `[]` for a kind, audience or step);+`markFeedIds(db: PrismaClient): Promise<number>`; `GROUP_INDEX.feed = { tabId: 1, feedIds: 1, lastActivityAt: 1, key: 1 }`.++- [x] Failing tests: `feedIdsOf` lists requester, approval person, suggested agent, proposal senders and assignee once each,+ and nothing for a buddy chat, private chat or step; the backfill gives an old row the same ids `extracted` writes.+- [x] Run them; record red.+- [x] Implement; run them green; commit.++### Task 2: Feed pages, first load and the older-page read++**Files:** Modify `backend/src/superTabs/parts/load.ts` (`loadFeed`), `backend/src/superTabs/read/personalTasks.ts`,+`backend/src/superTabs/read/service.ts`, `backend/src/superTabs/read/contract.ts`, `backend/src/routes/superTabs.ts`.+Test: `backend/integration/superTabPersonalTasksFeed.test.ts`, `backend/integration/superTabRead.test.ts`.++**Interfaces:** `loadFeed(tx, tabId, ids: string[], before?: { lastActivityAt: number; key: string }): Promise<Part<GroupData>[]>`;+`PersonalTasks.olderCursor?: string | null`; `SwarmReads.personalTasks(user, tabId, before?): Promise<PersonalTasks>`;+`GET /api/super-tabs/:tabId/personal-tasks?before=`.++- [x] Failing tests: first load lists a dormant archived task of the person's own agent and their own proposal, newest first,+ with `olderCursor`; the next page continues with no repeat; another member's view and an outsider's never list it; a hidden+ project's task never shortens a page nor names the cursor; the read plan is IXSCAN `feed` with examined ≈ returned.+- [x] Run them; record red.+- [x] Implement; run them and the read tests green; commit.++### Task 3: Row fields and live updates++**Files:** Modify `backend/src/superTabs/read/personalTasks.ts`. Test: `backend/src/superTabs/read/personalTasks.test.ts`.++**Interfaces:** `PersonalTask` gains `requester: { id, name, avatar? } | null` and optional `pullRequestUrl` (newest linked);+`at` is `lastActivityAt` in ms.++- [x] Failing tests: a poll keeps a dormant or archived own task and a task of the person's agent requested by someone else;+ removes deleted, merged and no-longer-own ones; rows carry requester, newest pull request and canApprove.+- [x] Run them; record red.+- [x] Implement; run them green; commit; mark the pull request ready.++## Validation receipt++- Feed column: red at f93cab251 (3 of the new write tests fail, no `feedIds`), green at 43c517602.+- Feed summaries: the new unit tests fail 4 of 15 against the old feed code, pass 15 of 15 at the feature commit.+- Feed paging, audience, plan and backfill (integration): red at f93cab251 (no module), 5 of 5 green at the feature commit.+- Older-page route: red at c8ab3d181 (404), green at the feature commit.