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
Backend: a project's purpose, the project list, and a main project on every agent (#4540) (#3552)
0xken15c5e633681c8e
diff --git a/backend/integration/superTabNotAvailable.test.ts b/backend/integration/superTabNotAvailable.test.tsindex 566f8df8b..223536d93 100644--- a/backend/integration/superTabNotAvailable.test.ts+++ b/backend/integration/superTabNotAvailable.test.ts@@ -99,6 +99,7 @@ function calls(tab: string, chat: string, project: string) {json('GET', 'GET /api/super-tabs/:tabId/scorecard', `${t}/scorecard?projectId=${project}`),json('GET', 'GET /api/super-tabs/:tabId/machine-readings', `${t}/machine-readings`),json('GET', 'GET /api/super-tabs/:tabId/proposals', `${t}/proposals?projectId=${project}`),+ json('GET', 'GET /api/super-tabs/:tabId/project-list', `${t}/project-list?invitedTo=${project}`),json('GET', 'GET /api/super-tabs/:tabId/sharing', `${t}/sharing`),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`),@@ -222,6 +223,12 @@ describe('a Swarm the caller cannot reach, on every person route', () => {const got = await answer(call, member), absent = await answer(missing[hidden.indexOf(call)]!, member)expect(got, call.url).toEqual(absent)if (before.includes(call.route)) continue+ // The project to pick first is only a hint (task #4540): the member's own list, alike for a private project and a missing one.+ if (call.route === 'GET /api/super-tabs/:tabId/project-list') {+ expect(got.status, call.url).toBe(200)+ expect(got.body, call.url).not.toContain(f.privateProject)+ continue+ }expect(got.status, call.url).toBe(404)expect(got.body, call.url).toBe(NOT_AVAILABLE_BODY)expect(JSON.parse(got.body).error.message).not.toMatch(about)@@ -249,3 +256,20 @@ describe('a Swarm the caller cannot reach, on every person route', () => {expect(JSON.parse(refused.body).error.code).toBe('OWNER_REQUIRED')})})++// Task #4540: the Cmd-N and join project list shows only the projects its reader can read, decided by the server.+describe('the project list', () => {+ it('lists a private project only to the people who read it', async () => {+ const f = await swarm()+ const list = async (as: AuthUser) => {+ const res = await app.inject({ method: 'GET', url: `/api/super-tabs/${f.tab}/project-list?invitedTo=${f.privateProject}`, headers: { 'x-user': as.sub } })+ expect(res.statusCode).toBe(200)+ return JSON.parse(res.body).data as { projects: Array<{ id: string }>; pick: string | null }+ }+ const mine = await list(owner), theirs = await list(member)+ expect(mine.pick).toBe(f.privateProject)+ expect(theirs.projects.map(p => p.id)).toEqual(['lead'])+ expect(theirs.pick).toBe('lead')+ expect(JSON.stringify(theirs)).not.toContain(f.privateProject)+ })+})diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex 28883f904..db3639086 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -126,6 +126,8 @@ const threadsQuery = z.object({ read: z.string().regex(/^[1-9][0-9]{0,2}$/).tran.refine(n => n <= READ_THREADS_ASKED_MAX, `At most ${READ_THREADS_ASKED_MAX}.`).optional() }).strict()// The project whose open Buddy proposals a person reads (superTabs/proposals.ts).const proposalsQuery = z.object({ projectId: id }).strict()+/** The Cmd-N and join project list's query (superTabs/projectList.ts): the project the person was invited to, if any. */+const projectListQuery = z.object({ invitedTo: id.optional() }).strict()// The reader's own catch-up (superTabs/catchUp.ts): no asAgentId, since agents read every message as it comes.const catchUpQuery = z.object({ after: z.coerce.number().int().nonnegative().safe() }).strict()// Pages by (sequence, id) (design 4.6): `afterId`/`beforeId` go with `after`/`before`, from the previous page's `next`.@@ -674,6 +676,10 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Suapp.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof proposalsQuery> }>('/api/super-tabs/:tabId/proposals',{ preHandler: [validateParams(tabParams), validateQuery(proposalsQuery)] },(req, reply) => respond(reply, () => store.proposals(req.user!, req.params.tabId, req.query.projectId)))+ // The projects a person may pick a main project from (superTabs/projectList.ts, task #4540), read when Cmd-N or Join opens.+ app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof projectListQuery> }>('/api/super-tabs/:tabId/project-list',+ { preHandler: [validateParams(tabParams), validateQuery(projectListQuery)] },+ (req, reply) => respond(reply, () => store.projectList(req.user!, req.params.tabId, req.query.invitedTo)))// A person's Activity (superTabs/activity.ts): replies to their messages and reactions to them, read when its digest moves.app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof noQuery> }>('/api/super-tabs/:tabId/activity',{ preHandler: [validateParams(tabParams), validateQuery(noQuery)] }, async (req, reply) => {diff --git a/backend/src/superTabs/agentKind.ts b/backend/src/superTabs/agentKind.tsindex 3dee07d26..ae7e84398 100644--- a/backend/src/superTabs/agentKind.ts+++ b/backend/src/superTabs/agentKind.ts@@ -5,9 +5,24 @@*/import { isBuddy, isBuddyChat } from './buddies.js'import type { Actor, Agent, SuperTabState } from './model.js'-import { isAgentChat, ledProject, onTeamAccount } from './projects.js'+import { isAgentChat, ledProject, onTeamAccount, projectsOf } from './projects.js'export type AgentKind = 'buddy' | 'pm' | 'regular'+/** Members and Leads (task #4540; spec 2026-11-07-members-and-leads): a Lead leads a project, every other agent is a Member.+ * Derived, never stored; `kind` stays beside it for clients until 2026-12-07. */+export type AgentRole = 'lead' | 'member'++/** The project each Lead leads, by its agent id, from one pass (projects.ts ledProject scans every conversation per call): a+ * read derives every agent's role and main project from it. The first project in order, as ledProject picks. */+export function ledProjects(state: SuperTabState): Map<string, string> {+ const chats = new Map(state.conversations.map(c => [c.id, c]))+ const led = new Map<string, string>()+ for (const project of projectsOf(state)) {+ const leadId = chats.get(project.leadConversationId)?.leadId+ if (leadId && !led.has(leadId)) led.set(leadId, project.id)+ }+ return led+}export function agentKind(state: SuperTabState, target: Agent): AgentKind {if (isBuddy(target)) return 'buddy'diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 688585140..1ed3ebfe9 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -294,6 +294,8 @@ export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('note.remove'), projectId: id, noteId: id }).strict(),// What the project calls its coordinator, as its instructions say (instructions.ts coordinatorNameOf).z.object({ type: z.literal('project.coordinatorName'), projectId: id, name: roleNameSchema }).strict(),+ // What the project is, in one line, for the Cmd-N and join project list (task #4540): empty clears it.+ z.object({ type: z.literal('project.about'), projectId: id, about: z.string().trim().max(80).regex(/^[^\r\n]*$/, 'One line.') }).strict(),// Whether its agents answer each person's message in that message's thread (projects.ts answersInThread, task #3747).z.object({ type: z.literal('project.answers'), projectId: id, inThread: z.boolean() }).strict(),z.object({ type: z.literal('lead.start'), projectId: id, machineId: id.nullable(), engine: swarmEngine,@@ -403,12 +405,16 @@ export const commandSchema = z.discriminatedUnion('type', [// `conversationId` starts that one of the person's Buddies again; neither, the default, as before.z.object({ type: z.literal('buddy.create'), projectId: id.optional(), machineId: id, engine: swarmEngine, model: z.string().trim().min(1).max(200).optional(),setup: z.object({ name: title, cwd: path, engines: z.array(swarmEngine).min(1).max(2) }).strict().optional(),- name: z.string().max(200).optional(), conversationId: id.optional() }).strict(),+ name: z.string().max(200).optional(), conversationId: id.optional(),+ // The project the person picked to join as a Member of (task #4540): kept on the agent as its main project.+ mainProjectId: id.optional() }).strict(),// + New agent (Swarm v3, task #4116): a Regular agent in a chat of its own, or a PM that names and starts a project, on the// person's own listed computer and account.z.object({ type: z.literal('agent.new'), kind: z.enum(['regular', 'pm']), machineId: id, engine: swarmEngine,model: z.string().trim().min(1).max(200).optional(), name: z.string().trim().min(1).max(80).optional(), projectName: title.optional(),repositoryUrl: repositoryUrl.optional(),+ // The Member's main project (task #4540): only on the Swarm's start of a Member; New project makes the Lead of its own.+ mainProjectId: id.optional(),// A Member its person's Desktop starts itself through Cmd-N (task #4196): only its chat opens here; agent.add brings in the session.local: z.literal(true).optional() }).strict(),z.object({ type: z.literal('agent.startDispatch'), startId: id }).strict(),@@ -586,6 +592,7 @@ export const WORDS: Partial<Record<Command['type'], readonly string[]>> = {'instructions.save': ['text', 'summary', 'repeatReason', 'dropped[].text'],'note.add': ['text'],'project.coordinatorName': ['name'],+ 'project.about': ['about'],'rule.set': ['text'],'rules.set': ['summary', 'rules.instructionApprovals.people[].name', 'rules.reviews.rows[].area', 'rules.reviews.rows[].paths[]','rules.reviews.test[].where', 'rules.reviews.test[].paths[]', 'rules.reviews.untested[]', 'rules.caps[].name', 'rules.paths[].name',@@ -1756,7 +1763,10 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,// Its sessions still starting in people's one Buddy chats go with it (their chats belong to no project).for (const start of state.starts ?? []) {if (start.request.buddySession?.projectId === project.id && !start.harnessId && !start.error) start.error = 'Its project was deleted.'+ if (start.request.mainProjectId === project.id) delete start.request.mainProjectId}+ // Members elsewhere whose main project it was have none now (spec: they ask their person again, build task 9).+ for (const target of state.agents) if (target.mainProjectId === project.id) delete target.mainProjectIddeleteProject(state, actor, project.id, orphaned, context.now)// No machine keeps it any more; one kept only for it now serves none (machines.ts machineProjectRefusal).for (const pool of state.machines ?? []) if (pool.projects) pool.projects = pool.projects.filter(id => id !== project.id)@@ -2552,6 +2562,17 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,projectOf(state, project.id).coordinatorName = command.namebreak}+ case 'project.about': {+ // As its coordinator's name: the coordinator sets it, or a person who manages the project.+ const project = readProject(state, actor, command.projectId)+ if (actor.kind === 'agent') coordinatorOf(project)+ else manageProject(state, actor, project.id)+ mutableProjects(state)+ const stored = projectOf(state, project.id)+ if (command.about) stored.about = command.about+ else delete stored.about+ break+ }case 'process.confirm': {const project = readProject(state, actor, command.projectId)if (actor.kind !== 'agent' || ledProject(state, actor.agentId)?.id !== project.id) fail('FORBIDDEN', 'Only the project\'s PM confirms a note for PMs.', 403)@@ -3718,6 +3739,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,if (state.paused) fail('PAUSED', 'New work is paused in this Super Tab.')// One Buddy per person per Swarm (Dee, 10-31). An older app's Start names a project it reads: it adds that same one Buddy.if (command.projectId) readProject(state, actor, command.projectId)+ if (command.mainProjectId) readProject(state, actor, command.mainProjectId)const me = person(state, actor.userId)// Which Buddy (task #3818): one of the person's own, by its chat; a new one, named, in the main chat while no Buddy is there,// else in a chat of its own, within the Swarm's cap; neither, the default, as before several.@@ -3778,7 +3800,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,const request: AgentStartRequest = { conversationId: chatId, machineId: pool.machineId, engine: command.engine,...(command.model ? { model: command.model } : {}), name: named.name, cwd: buddyHomeFolder(pool, me), worktree: false,requirements: BUDDY_REQUIREMENTS, buddyOf: { personId: me.id, generation: me.generation }, buddyScope: 'swarm',- buddyProjects: buddyProjectsOn(state, pool, me) }+ buddyProjects: buddyProjectsOn(state, pool, me), ...(command.mainProjectId ? { mainProjectId: command.mainProjectId } : {}) }const admitted = admitMachineStart(state, request, context.now, undefined, context.teamMachines, context.otherWorkspaceMachines)!state.starts ??= []if (state.starts.filter(s => !s.harnessId && !s.error).length >= 32) fail('STARTS_PENDING', 'Reconcile pending agent starts before adding more.')@@ -3802,6 +3824,11 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,if (grant.machineOwnerId !== me.id || grant.contributorId !== me.id || grant.hostGrant || grant.hostMachineId || grant.teamSession) {fail('AGENT_OWN_MACHINE', 'A new agent runs only on your own computer, in your own account.', 403)}+ // Cmd-N starts a Member through the Swarm, as Join does (task #4540): a local start or a Lead, which leads its own, takes none.+ if (command.mainProjectId) {+ if (command.local || command.kind !== 'regular') fail('MAIN_PROJECT_MEMBER_ONLY', 'Only a Member the Swarm starts takes a main project; New project makes its own Lead.', 400)+ readProject(state, actor, command.mainProjectId)+ }// A Member started through Cmd-N (task #4196, anh Dee 11-07): a server start waited on its host (p50 18 s, p95 4 min), so// its person's Desktop starts it on their own computer at once. Only its chat opens here, with no start, so neither a listed// computer nor a host that runs Regular starts is needed; agent.add then brings the running session into the chat.@@ -3833,7 +3860,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,const request: AgentStartRequest = { conversationId: chatId, machineId: pool.machineId, engine: command.engine,...(command.model ? { model: command.model } : {}), name, cwd: buddyHomeFolder(pool, me), worktree: false,// A Buddy's smaller memory is for a session that only reads and talks (#3738); a Regular agent takes tasks.- requirements: { ...BUDDY_REQUIREMENTS, memoryBytes: AGENT_MEMORY_BYTES }, regular: true }+ requirements: { ...BUDDY_REQUIREMENTS, memoryBytes: AGENT_MEMORY_BYTES }, regular: true,+ ...(command.mainProjectId ? { mainProjectId: command.mainProjectId } : {}) }const admitted = admitMachineStart(state, request, context.now, undefined, context.teamMachines, context.otherWorkspaceMachines)!state.starts ??= []if (state.starts.filter(s => !s.harnessId && !s.error).length >= 32) fail('STARTS_PENDING', 'Reconcile pending agent starts before adding more.')@@ -4010,6 +4038,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,: state.projects ? { projectId: groupProject(state, group).id } : {}),...(start.request.buddyScope ? { buddyScope: start.request.buddyScope } : {}),...(start.request.regular ? { regular: true as const } : {}),+ ...(start.request.mainProjectId ? { mainProjectId: start.request.mainProjectId } : {}),...(start.request.buddyNarrow ? { buddyNarrow: true as const } : {}),machineOwnerId: start.machineOwnerId, contributorId: start.contributorId, membershipGeneration: start.membershipGeneration,hostGrant: start.hostGrant, name: start.request.name, configuration: command.configuration, configurationVersion: operationId,diff --git a/backend/src/superTabs/mainProject.test.ts b/backend/src/superTabs/mainProject.test.tsnew file mode 100644index 000000000..05d7e2629--- /dev/null+++ b/backend/src/superTabs/mainProject.test.ts@@ -0,0 +1,140 @@+import { describe, expect, it } from 'vitest'+import { applyCommand, type Command, type CommandContext } from './commands.js'+import type { ContributedMachine } from './machines.js'+import { createSuperTab, SuperTabError, type Actor, type SuperTabState } from './model.js'+import { agentKind } from './agentKind.js'+import * as store from './parts/index.js'+import { readerView } from './read/views.js'++// Task #4540 (spec 2026-11-07-members-and-leads, build task 4): every agent has a main project and is a Lead or a Member.+// + New agent and Bring agent take a main project; New project makes its Lead. `kind` keeps its values for older clients.+const NOW = 50_000_000+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }+const mate: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'mate', email: '[email protected]' }+const outsider: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'other', email: '[email protected]' }+const resources = { cpuPercent: 1, memoryTotalBytes: 8, memoryUsedBytes: 1, diskFreeBytes: 8, diskTotalBytes: 8, projectDiskFreeBytes: 8,+ deviceType: null, chip: null, os: null, gpuPercent: null }+const reading = { generation: 'g1', receivedAt: NOW, sessionKind: 'computer' as const, resources, tools: {}, quotas: [], runningHarnessIds: [],+ stoppedHarnessIds: [], capabilities: ['leadStart', 'regularAgent', 'swarmBuddy'] }+const configuration = { engine: 'claude' as const, model: 'opus', effort: 'high', contextWindow: null, engineVersion: null }+const own = (userId: string) => ({ contribution: { machineOwnerId: userId, contributorId: userId } })+const code = (body: () => unknown): string | null => {+ try { body(); return null } catch (error) { return error instanceof SuperTabError ? error.code : 'INVALID' }+}++function swarm() {+ let state: SuperTabState = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')+ let sequence = 0+ const run = (command: Command, actor: Actor = mate, context: Partial<CommandContext> = {}) => {+ const effects = applyCommand(state, actor, command, { now: NOW, operationId: `op-${++sequence}`, ...context })+ state = effects.state+ return effects+ }+ for (const person of [mate, outsider]) {+ const invited = run({ type: 'invite.create', email: person.email, role: 'collaborator', conversationId: 'lead' }, owner)+ run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, person)+ }+ const generation = (userId: string) => state.people.find(p => p.id === userId)!.generation+ const pool = (machineId: string, contributorId: string): ContributedMachine => ({+ machineId, name: machineId, contributorId, membershipGeneration: generation(contributorId), generation: 'g1', cwd: '/swarm', scope: 'swarm',+ engines: ['claude', 'codex'], maxAgents: 4, paused: false, observation: reading })+ state.machines = [pool('mate-mac', 'mate')]+ const project = (name: string, visibility: 'public' | 'private' = 'public', by: Actor = owner) =>+ run({ type: 'project.create', name, visibility, brief: '' }, by).result.projectId as string+ /** Mate's start [made], dispatched and running: its agent's id. */+ const started = (startId: string, harnessId: string) => {+ run({ type: 'agent.startDispatch', startId }, mate, own('mate'))+ return run({ type: 'agent.started', startId, harnessId, configuration }, mate, own('mate')).result.agentId as string+ }+ const newAgent = (extra: Record<string, unknown>) =>+ run({ type: 'agent.new', engine: 'claude', machineId: 'mate-mac', ...extra } as Command, mate, own('mate'))+ const derived = (reader: Actor, agentId: string) =>+ readerView(store.split(state, { tabId: 'tab', version: 9_000, now: NOW }), reader, NOW, { teamMachines: [] }).derived.agents[agentId]+ return { run, project, started, newAgent, derived, get state() { return state } }+}++describe('+ New agent with a main project', () => {+ it('starts a Member whose main project is the one picked; kind stays regular for older clients', () => {+ const f = swarm()+ const harness = f.project('harness')+ const made = f.newAgent({ kind: 'regular', name: 'Ada', mainProjectId: harness })+ expect(f.state.starts!.find(s => s.id === made.result.startId)!.request.mainProjectId).toBe(harness)+ const agentId = f.started(made.result.startId as string, 'h-ada')+ const agent = f.state.agents.find(a => a.id === agentId)!+ expect(agent.mainProjectId).toBe(harness)+ expect(agentKind(f.state, agent)).toBe('regular')+ expect(f.derived(mate, agentId)).toMatchObject({ kind: 'regular', role: 'member', mainProjectId: harness })+ })++ it('refuses a main project the person cannot read, as one that is not there', () => {+ const f = swarm()+ const secret = f.project('secret', 'private')+ expect(code(() => f.newAgent({ kind: 'regular', name: 'Ada', mainProjectId: secret }))).toBe('NOT_FOUND')+ expect(code(() => f.newAgent({ kind: 'regular', name: 'Ada', mainProjectId: 'gone' }))).toBe('NOT_FOUND')+ expect(f.state.starts ?? []).toHaveLength(0)+ })++ it('takes a main project only on the Swarm\'s start of a Member: a local start or a Lead says so', () => {+ const f = swarm()+ const harness = f.project('harness')+ expect(code(() => f.newAgent({ kind: 'regular', name: 'Ada', local: true, mainProjectId: harness }))).toBe('MAIN_PROJECT_MEMBER_ONLY')+ expect(code(() => f.newAgent({ kind: 'pm', projectName: 'Docs', mainProjectId: harness }))).toBe('MAIN_PROJECT_MEMBER_ONLY')+ })++ it('without one, starts as before, with no main project', () => {+ const f = swarm()+ const made = f.newAgent({ kind: 'regular', name: 'Ada' })+ const agentId = f.started(made.result.startId as string, 'h-ada')+ expect(f.state.agents.find(a => a.id === agentId)).not.toHaveProperty('mainProjectId')+ expect(f.derived(mate, agentId)).toMatchObject({ kind: 'regular', role: 'member', mainProjectId: null })+ })+})++describe('New project', () => {+ it('makes its Lead, whose main project is the one it leads', () => {+ const f = swarm()+ const made = f.newAgent({ kind: 'pm', projectName: 'Docs site' })+ const agentId = f.started(made.result.startId as string, 'h-lead')+ expect(f.derived(mate, agentId)).toMatchObject({ kind: 'pm', role: 'lead', mainProjectId: made.result.projectId })+ })+})++describe('Bring agent with a main project', () => {+ it('makes the new person\'s agent a Member of the project they picked', () => {+ const f = swarm()+ const harness = f.project('harness')+ const made = f.run({ type: 'buddy.create', machineId: 'mate-mac', engine: 'claude', mainProjectId: harness } as Command, mate, own('mate'))+ expect(f.state.starts!.find(s => s.id === made.result.startId)!.request.mainProjectId).toBe(harness)+ const agentId = f.started(made.result.startId as string, 'h-buddy')+ expect(f.derived(mate, agentId)).toMatchObject({ kind: 'buddy', role: 'member', mainProjectId: harness })+ })++ it('refuses a project the person cannot read', () => {+ const f = swarm()+ const secret = f.project('secret', 'private')+ expect(code(() => f.run({ type: 'buddy.create', machineId: 'mate-mac', engine: 'claude', mainProjectId: secret } as Command, mate, own('mate')))).toBe('NOT_FOUND')+ })+})++describe('a main project\'s readers', () => {+ it('shows a private main project only to readers of that project, and keeps it out of the agent\'s own part', () => {+ const f = swarm()+ const secret = f.project('secret', 'private', mate)+ const made = f.newAgent({ kind: 'regular', name: 'Ada', mainProjectId: secret })+ const agentId = f.started(made.result.startId as string, 'h-ada')+ expect(f.derived(mate, agentId)).toMatchObject({ mainProjectId: secret })+ expect(f.derived(outsider, agentId)?.mainProjectId ?? null).toBeNull()+ const parts = readerView(store.split(f.state, { tabId: 'tab', version: 9_000, now: NOW }), outsider, NOW, { teamMachines: [] }).parts+ expect(JSON.stringify(parts.agents)).not.toContain(secret)+ })++ it('is cleared when the project is deleted, on agents and on starts still waiting', () => {+ const f = swarm()+ const harness = f.project('harness')+ const agentId = f.started(f.newAgent({ kind: 'regular', name: 'Ada', mainProjectId: harness }).result.startId as string, 'h-ada')+ const waiting = f.newAgent({ kind: 'regular', name: 'Bo', mainProjectId: harness }).result.startId as string+ f.run({ type: 'project.delete', projectId: harness }, owner)+ expect(f.state.agents.find(a => a.id === agentId)).not.toHaveProperty('mainProjectId')+ expect(f.state.starts!.find(s => s.id === waiting)!.request).not.toHaveProperty('mainProjectId')+ })+})diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex 7e88cf363..6fedcfe20 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -159,6 +159,10 @@ export interface Agent {buddyScope?: 'swarm'/** A Regular agent (agent.new, task #4116): in no project but its active task's (projects.ts agentProjectId). */regular?: true+ /** The one project this Member belongs to (task #4540; spec 2026-11-07-members-and-leads): picked in Cmd-N or when its person+ * joined. Readers get it in the derived row, never in this part (read/views.ts), and only when they read that project. A+ * Lead's is the project it leads, derived (agentKind.ts ledProjects). Cleared when the project is deleted. */+ mainProjectId?: string/** The private project a Regular agent first worked in: its one conversation holds that project's content, so it takes tasks* only there from then on (projects.ts regularMayWorkIn; security review 2 of #4116). Set at its assignment, never cleared. */privateProjectId?: string@@ -216,6 +220,8 @@ export interface AgentStartRequest {buddyScope?: 'swarm'/** A Regular agent's start (agent.new, task #4116): in its person's own chat, in no project's folder. Written by the server alone. */regular?: true+ /** The main project its person picked (agent.new, buddy.create; task #4540), kept on the agent when it starts. */+ mainProjectId?: string/** A one-project Buddy's start (Agent.buddyNarrow), written by message.send alone. */buddyNarrow?: true/** The person's messages in an older project chat its start waits on, delivered when it joins (ids only). */diff --git a/backend/src/superTabs/parts/touches.test.ts b/backend/src/superTabs/parts/touches.test.tsindex 00fcc6e6b..32d5b980d 100644--- a/backend/src/superTabs/parts/touches.test.ts+++ b/backend/src/superTabs/parts/touches.test.ts@@ -57,6 +57,7 @@ describe('the parts a command touches (design section 1.2, column T)', () => {[{ type: 'note.remove', projectId: 'lead', noteId: 'n1' }, { notes }],[{ type: 'project.coordinatorName', projectId: 'lead', name: 'Lead engineer' }, {}],[{ type: 'project.answers', projectId: 'lead', inThread: true }, {}],+ [{ type: 'project.about', projectId: 'lead', about: 'The Harness app' }, {}],// An older CLI's rule, a save to the instructions after the one above (project instructions, phase 4).[{ type: 'rule.set', rule: { kind: 'preferIdle' }, text: 'Idle first.', askedIn: { conversationId: 'lead', messageId: 'm1' } },{ askedIn: { author: { kind: 'person', id: 'owner', name: 'owner', membershipGeneration: 'g' }, source: false, createdAt: 0 },diff --git a/backend/src/superTabs/parts/touches.ts b/backend/src/superTabs/parts/touches.tsindex a4e0e2b88..d4432bc01 100644--- a/backend/src/superTabs/parts/touches.ts+++ b/backend/src/superTabs/parts/touches.ts@@ -124,7 +124,7 @@ export function touchesFor(command: Command, actor: Actor, before: SuperTabStatebreakcase 'project.report': case 'project.repository':// The coordinator's own writes check it leads the project, which a concurrent Lead change ends (review of phase 2).- case 'instructions.save': case 'note.add': case 'note.remove': case 'project.coordinatorName': case 'project.answers':+ case 'instructions.save': case 'note.add': case 'note.remove': case 'project.coordinatorName': case 'project.answers': case 'project.about':leadCheck(command.projectId)break// A rules save writes its own collection, no part of the project: by anyone, it guards on the project's Lead chat, which adiff --git a/backend/src/superTabs/projectAbout.test.ts b/backend/src/superTabs/projectAbout.test.tsnew file mode 100644index 000000000..c8711ad0d--- /dev/null+++ b/backend/src/superTabs/projectAbout.test.ts@@ -0,0 +1,62 @@+import { describe, expect, it } from 'vitest'+import { applyCommand, type Command, type CommandContext } from './commands.js'+import { CREDENTIAL_MARKER } from './credentials.js'+import { createSuperTab, type Actor, type AgentConfiguration } from './model.js'++// Task #4540 (spec 2026-11-07-members-and-leads, build task 2): a project says what it is in one line, which the Cmd-N and+// join project list shows. Its owner or its Lead sets it, as they set the coordinator's name.+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }+const peer: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'peer', email: '[email protected]' }+const config: AgentConfiguration = { engine: 'codex', model: 'test-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }++function fixture() {+ let state = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')+ let sequence = 0+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {+ const effects = applyCommand(state, actor, command, { now: 1000, operationId: `op-${++sequence}`, ...context })+ state = effects.state+ return effects+ }+ const invited = run({ type: 'invite.create', email: peer.email, role: 'collaborator', conversationId: 'lead' })+ run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, peer)+ const lead = run({ type: 'agent.add', conversationId: 'lead', machineId: 'host', harnessId: 'lead', name: 'lead', configuration: config, lead: true },+ owner, { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }).result.agentId as string+ const asLead: Actor = { kind: 'agent', agentId: lead, machineOwnerId: 'host-owner' }+ return { run, asLead, get state() { return state } }+}++const about = (text: string): Command => ({ type: 'project.about', projectId: 'lead', about: text })++describe('project.about', () => {+ it('is set by the project owner and by its Lead, trimmed, and cleared by an empty line', () => {+ const f = fixture()+ f.run(about(' The Harness app and Swarm '))+ expect(f.state.projects![0]!.about).toBe('The Harness app and Swarm')+ f.run(about('Ships the Swarm'), f.asLead)+ expect(f.state.projects![0]!.about).toBe('Ships the Swarm')+ f.run(about(' '))+ expect(f.state.projects![0]).not.toHaveProperty('about')+ })++ it('refuses anyone else', () => {+ const f = fixture()+ expect(() => f.run(about('Mine now'), peer)).toThrow(expect.objectContaining({ code: 'PROJECT_OWNER_REQUIRED' }))+ })++ it('is one line of at most 80 characters', () => {+ const f = fixture()+ f.run(about('x'.repeat(80)))+ expect(() => f.run(about('x'.repeat(81)))).toThrow()+ expect(() => f.run(about('Two\nlines'))).toThrow()+ expect(f.state.projects![0]!.about).toBe('x'.repeat(80))+ })++ it('never stores a credential pasted into it', () => {+ const f = fixture()+ // Assembled at run time from obviously fake parts, never a credential-shaped literal.+ const token = ['ghp', 'Fixture0Token1Not2Real3Value4abcdefgh'].join('_')+ f.run(about(`Deploys with ${token}`))+ expect(f.state.projects![0]!.about).toBe(`Deploys with ${CREDENTIAL_MARKER}`)+ expect(JSON.stringify(f.state)).not.toContain(token)+ })+})diff --git a/backend/src/superTabs/projectList.test.ts b/backend/src/superTabs/projectList.test.tsnew file mode 100644index 000000000..bea9b238a--- /dev/null+++ b/backend/src/superTabs/projectList.test.ts@@ -0,0 +1,144 @@+import { describe, expect, it } from 'vitest'+import { applyCommand, type Command } from './commands.js'+import { createSuperTab, type Actor, type SuperTabState } from './model.js'+import { projectList } from './projectList.js'+import type { Pulse } from './pulse.js'++// Task #4540 (spec 2026-11-07-members-and-leads, section 1 and build task 3): the Cmd-N and join forms list the projects the+// person can read, each with what it is, its Lead and how many tasks wait, and say which row starts picked.+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }+const peer: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'peer', email: '[email protected]' }++function swarm() {+ let state: SuperTabState = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')+ let sequence = 0+ const run = (command: Command, actor: Actor = owner) => {+ const effects = applyCommand(state, actor, command, { now: 1000, operationId: `op-${++sequence}` })+ state = effects.state+ return effects+ }+ const invited = run({ type: 'invite.create', email: peer.email, role: 'collaborator', conversationId: 'lead' })+ run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, peer)+ // Every command records each project's pulse again (pulse.ts recordPulse), so the pulses wanted here are put on last.+ const wanted = new Map<string, Pulse | undefined>()+ const chatOf = (projectId: string) => state.conversations.find(c => c.id === state.projects!.find(p => p.id === projectId)!.leadConversationId)!+ const project = (name: string, extra: { visibility?: 'public' | 'private'; waiting?: number; members?: number } = {}) => {+ const id = run({ type: 'project.create', name, visibility: extra.visibility ?? 'public', brief: '' }).result.projectId as string+ wanted.set(id, pulse(extra.waiting ?? 0, extra.members ?? 0))+ return id+ }+ const noPulse = (projectId: string) => wanted.set(projectId, undefined)+ const read = () => {+ for (const [id, recorded] of wanted) { const chat = chatOf(id); if (recorded) chat.pulse = recorded; else delete chat.pulse }+ return state+ }+ const lead = (projectId: string, name: string, displayName?: string) => {+ const chat = chatOf(projectId)+ const id = `agent-${name}`+ state.agents.push({ id, machineId: 'mac', harnessId: name, machineOwnerId: 'owner', contributorId: 'owner',+ membershipGeneration: state.people[0]!.generation, hostGrant: null, name, ...(displayName ? { displayName } : {}), configuration: null, configurationVersion: 'v' } as unknown as SuperTabState['agents'][number])+ chat.leadId = id+ chat.agentIds.push(id)+ }+ return { run, project, noPulse, lead, read, get state() { return state } }+}++/** A stored pulse with [waiting] tasks in Next up and [members] agents working in the project beside its Lead. */+const pulse = (waiting: number, members: number): Pulse => ({ pmId: null,+ asks: { count: 0, oldestAt: null, personId: null, list: [] }, working: { count: 0, crew: members, agentIds: [] },+ nextUp: { count: waiting, conversationIds: [] }, lost: { count: 0, since: null, conversationIds: [] },+ held: { count: 0, withoutReason: 0, list: [] }, idleSince: null, process: null,+ redAt: { asks: null, idle: null, lost: null, held: null }, limits: { askMinutes: 5, idleMinutes: 10, lostMinutes: 10 } })++const names = (list: ReturnType<typeof projectList>) => list.projects.map(p => p.name)++describe('the project list', () => {+ it('lists only the projects the reader can read', () => {+ const f = swarm()+ f.project('harness')+ f.project('secret', { visibility: 'private' })+ expect(names(projectList(f.read(), peer))).not.toContain('secret')+ expect(names(projectList(f.read(), owner))).toContain('secret')+ })++ it('shows what each project is, else its repository\'s name, its Lead and how many tasks wait', () => {+ const f = swarm()+ const harness = f.project('harness', { waiting: 12 })+ f.run({ type: 'project.about', projectId: harness, about: 'The Harness app and Swarm' })+ f.lead(harness, 'River')+ const lamp = f.project('lamp')+ f.state.projects!.find(p => p.id === lamp)!.repository = { machineId: 'mac', cwd: '/Users/someone/lamp', repositoryUrl: 'https://github.com/autonomous-ai/lamp-os' }+ const rows = projectList(f.read(), peer).projects+ expect(rows.find(r => r.id === harness)).toEqual({ id: harness, name: 'harness', about: 'The Harness app and Swarm', repositoryName: null,+ lead: { agentId: 'agent-River', name: 'River' }, waiting: 12 })+ // A repository's name, never a folder on someone's computer.+ expect(rows.find(r => r.id === lamp)).toEqual({ id: lamp, name: 'lamp', about: null, repositoryName: 'lamp-os', lead: null, waiting: 0 })+ })++ // Review of #3552: a Lead goes by the name people see (River), not its internal one (Lead).+ it('names each Lead as people see it', () => {+ const f = swarm()+ const harness = f.project('harness')+ f.lead(harness, 'Lead', 'River')+ expect(projectList(f.read(), peer).projects.find(r => r.id === harness)!.lead).toEqual({ agentId: 'agent-Lead', name: 'River' })+ })++ it('starts on the project the person was invited to', () => {+ const f = swarm()+ f.project('busy', { waiting: 9 })+ const quiet = f.project('quiet')+ const list = projectList(f.read(), peer, quiet)+ expect(list.pick).toBe(quiet)+ expect(list.projects[0]!.id).toBe(quiet)+ })++ it('ignores an invitation to a project the reader cannot read, or that is gone', () => {+ const f = swarm()+ const busy = f.project('busy', { waiting: 9 })+ const secret = f.project('secret', { visibility: 'private', waiting: 50 })+ expect(projectList(f.read(), peer, secret).pick).toBe(busy)+ expect(projectList(f.read(), peer, 'gone').pick).toBe(busy)+ })++ it('otherwise starts on the one that needs help most: waiting per Member there, then waiting, then A to Z', () => {+ const f = swarm()+ f.project('crowded', { waiting: 10, members: 5 })+ f.project('short', { waiting: 6, members: 1 })+ f.project('empty', { waiting: 1, members: 0 })+ f.project('beta', { waiting: 4, members: 2 })+ f.project('alpha', { waiting: 2, members: 1 })+ const list = projectList(f.read(), peer)+ // Nobody working where a task waits needs help first; 6 per Member; 2 per Member, the one with more waiting first, then A+ // to Z; nothing waiting comes last.+ expect(names(list)).toEqual(['empty', 'short', 'crowded', 'beta', 'alpha', 'Pilot'])+ expect(list.pick).toBe(list.projects[0]!.id)+ })++ it('lists a project whose pulse is not recorded yet with nothing waiting', () => {+ const f = swarm()+ const fresh = f.project('fresh')+ f.noPulse(fresh)+ expect(projectList(f.read(), peer).projects.find(r => r.id === fresh)).toMatchObject({ waiting: 0, lead: null })+ })++ it('gives a person who reads no project an empty list and no pick', () => {+ const f = swarm()+ f.run({ type: 'project.create', name: 'mine', visibility: 'private', brief: '' })+ const state = f.read()+ // Only private projects of another person: the implicit first project is made private too.+ state.projects!.forEach(p => { p.visibility = 'private' })+ expect(projectList(state, peer)).toEqual({ projects: [], pick: null })+ })++ it('stays within its byte bound for 100 projects with every field at its longest', () => {+ const f = swarm()+ for (let i = f.state.projects?.length ?? 0; i < 100; i++) {+ const id = f.project(`${i}`.padStart(3, '0') + 'x'.repeat(157), { waiting: 999 })+ f.state.projects!.find(p => p.id === id)!.repository = { machineId: 'mac', cwd: '/repo', repositoryUrl: `https://github.com/${'o'.repeat(39)}/${'r'.repeat(100)}` }+ f.lead(id, `${i}`.padStart(3, '0') + 'n'.repeat(77))+ }+ const list = projectList(f.read(), peer)+ expect(list.projects).toHaveLength(100)+ expect(Buffer.byteLength(JSON.stringify(list))).toBeLessThan(64 * 1024)+ })+})diff --git a/backend/src/superTabs/projectList.ts b/backend/src/superTabs/projectList.tsnew file mode 100644index 000000000..1b68b4e14--- /dev/null+++ b/backend/src/superTabs/projectList.ts@@ -0,0 +1,44 @@+/**+ * The projects a person may pick a main project from, in Cmd-N and when joining (task #4540; spec+ * 2026-11-07-members-and-leads, section 1): each readable project with what it is, its Lead and how many tasks wait, and the+ * row that starts picked. Worked out from the projects and the pulse stored on each project's chat (pulse.ts), so the read+ * loads nothing beyond the Swarm's first load and its project chats.+ */+import { githubRepository } from '../github/repository.js'+import type { Actor, SuperTabState } from './model.js'+import { canReadProject, projectsOf } from './projects.js'+import { pmOf, storedPulse } from './pulse.js'++export interface ProjectRow {+ id: string+ name: string+ /** Its own one line (project.about), or null: the form then shows `repositoryName`, sent only then. */+ about: string | null+ repositoryName: string | null+ lead: { agentId: string; name: string } | null+ /** Tasks in Next up: approved, and nobody on them yet. */+ waiting: number+}+export interface ProjectList { projects: ProjectRow[]; pick: string | null }++/** [actor]'s readable projects, the one to pick first at the top: [invitedTo] when they read it, else the one that needs help+ * most (the most waiting tasks for each Member working there, then the most waiting, then A to Z). */+export function projectList(state: SuperTabState, actor: Actor, invitedTo?: string): ProjectList {+ const rows = projectsOf(state).filter(project => canReadProject(state, actor, project)).map(project => {+ const pulse = storedPulse(state, project)+ const leadId = pmOf(state, project)+ const lead = leadId ? state.agents.find(a => a.id === leadId) : undefined+ const row: ProjectRow = { id: project.id, name: project.name, about: project.about ?? null,+ repositoryName: project.about ? null : githubRepository(project.repository?.repositoryUrl)?.name ?? null,+ lead: lead ? { agentId: lead.id, name: lead.displayName ?? lead.name } : null, waiting: pulse?.nextUp.count ?? 0 }+ return { row, perMember: perMember(row.waiting, pulse?.working.crew ?? 0) }+ })+ rows.sort((a, b) => b.perMember - a.perMember || b.row.waiting - a.row.waiting || a.row.name.localeCompare(b.row.name))+ const invited = rows.findIndex(r => r.row.id === invitedTo)+ if (invited > 0) rows.unshift(...rows.splice(invited, 1))+ const projects = rows.map(r => r.row)+ return { projects, pick: projects[0]?.id ?? null }+}++/** Waiting tasks for each Member working there; a project where tasks wait and nobody works needs help before any other. */+const perMember = (waiting: number, members: number): number => members ? waiting / members : waiting ? Infinity : 0diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.tsindex c8cc220c6..970059cb4 100644--- a/backend/src/superTabs/projects.ts+++ b/backend/src/superTabs/projects.ts@@ -33,6 +33,9 @@ export const roleVersion = (text: string): string => createHash('sha256').updateexport interface SwarmProject {id: stringname: string+ /** What the project is, in one line (at most 80 characters), set by its owner or Lead (project.about, task #4540): the Cmd-N+ * and join project list shows it. Absent shows the repository's name. */+ about?: string/** The owner's id; '' for a private project whose owner left with no member left to take it (settleOwners): nobody's. */ownerId: string/** The owner's membership generation when they became its owner (task #3073): the same account at a later membershipdiff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.tsindex d3ab9a2f4..71371db03 100644--- a/backend/src/superTabs/read/contract.ts+++ b/backend/src/superTabs/read/contract.ts@@ -87,7 +87,9 @@ export interface Derived {* (agentKind.ts, task #4116). Absent from an older backend. *//** `myAgent`: whether it is in the reader's My agents (agentKind.ts inMyAgents, task #4192). Absent from an older backend. */agents: Record<string, { downSince: string | null; limitedUntil: string | null; workDecision: 'awaiting' | null; roleId: string | null; roleName: string;- kind: import('../agentKind.js').AgentKind; chatId: string | null; myAgent: boolean }>+ kind: import('../agentKind.js').AgentKind; chatId: string | null; myAgent: boolean+ /** Lead or Member, and its main project when the reader reads that project (agentKind.ts, task #4540). Absent from an older backend. */+ role: import('../agentKind.js').AgentRole; mainProjectId: string | null }>/** Every contributed machine the reader can see. *//** `clientVersion`: the CLI version its daemon last connected with (routing reads a machine updated since its failed starts). */machines: Record<string, { availableSlots: number; teamWork: { allowed: true } | { allowed: false; reason: string; [key: string]: unknown }; clientVersion?: stringdiff --git a/backend/src/superTabs/read/derivedEtag.test.ts b/backend/src/superTabs/read/derivedEtag.test.tsindex d3c30d207..517d9f304 100644--- a/backend/src/superTabs/read/derivedEtag.test.ts+++ b/backend/src/superTabs/read/derivedEtag.test.ts@@ -3,7 +3,7 @@ import type { Derived } from './contract.js'import { derivedEtag, MARK_FIELDS } from './derivedEtag.js'const summary = (): Derived => ({- agents: { a1: { downSince: null, limitedUntil: null, workDecision: null, roleId: null, roleName: 'Engineer', kind: 'regular', chatId: null, myAgent: false } },+ agents: { a1: { downSince: null, limitedUntil: null, workDecision: null, roleId: null, roleName: 'Engineer', kind: 'regular', chatId: null, myAgent: false, role: 'member' as const, mainProjectId: null } },machines: { m1: { availableSlots: 2, teamWork: { allowed: true } } },mentionsWaiting: 1, mentionsDigest: 'd1', avatars: { 'person:p1': 'https://example.test/a?sig=1' },})diff --git a/backend/src/superTabs/read/views.test.ts b/backend/src/superTabs/read/views.test.tsindex 58e08a08f..52fc1e2ed 100644--- a/backend/src/superTabs/read/views.test.ts+++ b/backend/src/superTabs/read/views.test.ts@@ -126,7 +126,7 @@ describe('reader view of the parts (design 4.1, 4.3)', () => {const view = readerView(parts, peer, NOW, { teamMachines: [] })const worker = view.parts.agents.find(a => a.key === s.worker)!for (const hidden of ['downNamed', 'downSince', 'limitedUntil', 'roleId']) expect(worker.data).not.toHaveProperty(hidden)- expect(view.derived.agents[s.worker]).toEqual({ downSince: new Date(NOW - 5 * MINUTE).toISOString(), limitedUntil: null, workDecision: null, roleId: null, roleName: 'Engineer', kind: 'regular', chatId: null, myAgent: false })+ expect(view.derived.agents[s.worker]).toEqual({ downSince: new Date(NOW - 5 * MINUTE).toISOString(), limitedUntil: null, workDecision: null, roleId: null, roleName: 'Engineer', kind: 'regular', chatId: null, myAgent: false, role: 'member', mainProjectId: null })expect(Object.keys(view.derived.agents).sort()).toEqual([s.lead, s.worker].sort())})diff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.tsindex 46824f411..c50883b0a 100644--- a/backend/src/superTabs/read/views.ts+++ b/backend/src/superTabs/read/views.ts@@ -12,11 +12,11 @@ import { agentForBuddy, agentWithoutMachine, groupForBuddy, machineHiddenFrom, simport { availableSlots, slotCounter, machineTeamWork, type ContributedMachine } from '../machines.js'import * as store from '../parts/index.js'import type { Part, SwarmParts } from '../parts/index.js'-import { canReadGroup } from '../projects.js'+import { canReadGroup, canReadProject, projectsOf } from '../projects.js'import { promptWaits } from '../promptWaits.js'import { storedPulse, type Pulse } from '../pulse.js'import { coordinatorNameOf, roleNameOf } from '../instructions.js'-import { agentChatId, agentKind, inMyAgents } from '../agentKind.js'+import { agentChatId, agentKind, inMyAgents, ledProjects } from '../agentKind.js'import { withAvatarView } from '../profile.js'import { swarmUsernames } from '../usernames.js'import type { AgentView, Derived, GroupView, HeadView, LivePart, MachineView, MemberView, ProgressView, StartView } from './contract.js'@@ -93,7 +93,8 @@ export const seenIn = (parts: ReaderView['parts']): Set<string> =>new Set([...parts.machines.map(m => m.key), ...parts.agents.map(a => a.data.machineId)])export function agentView(agent: Agent): AgentView {- const { downNamed: _named, downSince: _since, limitedUntil: _limit, roleId: _role, ...rest } = agent+ // A main project goes in the derived row, to its project's readers only: a private one's id says the project exists.+ const { downNamed: _named, downSince: _since, limitedUntil: _limit, roleId: _role, mainProjectId: _main, ...rest } = agentreturn withAvatarView(rest) as AgentView}@@ -196,6 +197,19 @@ function derive(state: SuperTabState, visible: SuperTabState, actor: Actor, now:const pulse = pulses(state, visible, actor, isBuddyReader(state, actor))// Each visible agent's stored row, looked up once rather than once per derived field.const storedAgents = new Map(state.agents.map(a => [a.id, a]))+ // Whether the reader reads each project, worked out once for every agent naming it as its main project.+ const projectReads = new Map<string, boolean>()+ const readsProject = (id: string) => {+ let reads = projectReads.get(id)+ if (reads === undefined) {+ const project = projectsOf(state).find(p => p.id === id)+ projectReads.set(id, reads = !!project && canReadProject(state, actor, project))+ }+ return reads+ }+ // A Lead's main project is the one it leads; a Member's, the one its person picked (task #4540).+ const led = ledProjects(state)+ const shownMain = (agent: Agent) => { const main = led.get(agent.id) ?? agent.mainProjectId; return main && readsProject(main) ? main : null }// The next release times the settle recorded (releases.ts), for the projects this reader sees: the release list itself stays// the server's (task #3827).const releaseTimes = Object.fromEntries(visible.projects?.flatMap(seen => {@@ -215,7 +229,9 @@ function derive(state: SuperTabState, visible: SuperTabState, actor: Actor, now:// What it is and where its person talks to it, for the left pane's "My agents" (agentKind.ts, task #4116).kind: agentKind(state, stored), chatId: agentChatId(state, stored),// Whether it is in this reader's My agents, decided here so every client lists the same (task #4192).- myAgent: inMyAgents(state, actor, stored) }]+ myAgent: inMyAgents(state, actor, stored),+ // Lead or Member, and its main project (agentKind.ts, task #4540).+ role: led.has(stored.id) ? 'lead' as const : 'member' as const, mainProjectId: shownMain(stored) }]})),machines: Object.fromEntries((visible.machines ?? []).map(machine)),...(visible.otherProjectsWork ? { otherProjectsWork: visible.otherProjectsWork } : {}),diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex bdee956f4..be508022e 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -41,6 +41,7 @@ import { deliveriesByMessage } from './read/pageDeliveries.js'import { restoreDelivery } from './deliveryCompaction.js'import { threadSummaries } from './threads.js'import { closeProposal, databaseProposalReads, openProposalRows, openProposals, proposalChat, type OpenProposal } from './proposals.js'+import { projectList, type ProjectList } from './projectList.js'import { attachmentMime, attachmentName, AttachmentTooLarge, AVATAR_PURPOSE, AVATAR_TYPES, checkedType, directUploads, errorCode, EXPIRED_UPLOAD, HOURLY_UPLOAD_BYTES, HOURLY_UPLOADS, MAX_ATTACHMENT_BYTES, MAX_AVATAR_BYTES, MAX_FORM_ATTACHMENT_BYTES, objectKeyFor, peekType, PENDING_UPLOAD_PURPOSE, publicUrl, TOO_LARGE_MESSAGE, trimPrefix, typeFromHead, UPLOAD_LINK_MS,type Attachment, type Attachments, type AttachmentStore, type AvatarStore } from './attachments.js'import { makeThumbnail, MAX_READ_BACK_BYTES, pictureFields, THUMBNAILED_TYPES, thumbKeyOf, thumbnailsReserve, type StoredImage } from './thumbnails.js'@@ -3944,6 +3945,21 @@ export class SuperTabStore {return { proposals: await openProposals(state, chat, databaseProposalReads(this.db, tabId, chat.id)) }}+ /** The projects a person may pick a main project from, in Cmd-N and when joining (projectList.ts, task #4540): only those they+ * read. A project's chat holds its pulse; a quiet one is not in the first load, so the readable ones missing are loaded by id+ * (at most the Swarm's 100 projects). */+ async projectList(user: AuthUser, tabId: string, invitedTo?: string): Promise<ProjectList> {+ this.personOnly(user)+ let { state } = await this.readLoad(user, tabId)+ const actor = await this.actor(this.db, user, state)+ // Only a member: someone who left reads no list, as for a Swarm that is not there.+ author(state, actor)+ const missing = projectsOf(state).filter(p => canReadProject(state, actor, p) && !state.conversations.some(c => c.id === p.leadConversationId))+ .map(p => p.leadConversationId)+ if (missing.length) ({ state } = await this.readLoad(user, tabId, { groupIds: missing }))+ return projectList(state, actor, invitedTo)+ }+/** The main-chat excerpt a Buddy thread session starts from: main-stream rows at or before `from` it may read (never a session* thread's, never a reply only in its thread), by the conversation's sequence index, at most 50 rows read for 10 kept. */private async sessionExcerpt(tx: Transaction, state: SuperTabState, tabId: string, conversationId: string, from: number,diff --git a/docs/plans/2026-11-07-main-project-backend-plan.md b/docs/plans/2026-11-07-main-project-backend-plan.mdnew file mode 100644index 000000000..e9acee9ce--- /dev/null+++ b/docs/plans/2026-11-07-main-project-backend-plan.md@@ -0,0 +1,128 @@+# A project's purpose, the project list and a main project on every agent: implementation plan++> This plan is carried out by the project's Engineer way of working (test first, task by task, one pull request), not+> subagent-driven-development. There is no execution handoff.++**Goal:** The backend half of anh Dee's Members and Leads flow (task #4540, part of #4539): a project says what it is in+one line, Cmd-N and joining can read the list of projects to pick a main project from, and every agent carries its main+project and its role (Lead or Member) beside its kind.++**Architecture:** `about` is a project field set by `project.about`, which follows `project.coordinatorName` (the Lead or+the project's owner). The list is a new person-only GET read, `/api/super-tabs/:tabId/project-list`, computed by+`projectList.ts` from what the Swarm's first load already holds: each project and the pulse stored on its chat (waiting+count, Members working there, its Lead). `mainProjectId` is stored on the agent: `agent.new` and `buddy.create` take it,+and their server starts copy it from the start request when the agent starts. Desktop's new Cmd-N starts a Member through+the server, as Join does (#4541), so a local `agent.new` that names a main project is refused. Clients read `role` and `mainProjectId` in each agent's derived row, beside `kind`, which keeps its values.++**Tech Stack:** TypeScript backend (Fastify, zod), vitest.++**Spec:** `docs/specs/2026-11-07-members-and-leads.md` (PR #3542): build tasks 2, 3 and 4, sections 1 and 7, and the+Design section's lines for `about`, `mainProjectId`, the list's read cost, compatibility and audience.++## Global Constraints++- Backend only; ships in the next backend release once green and reviewed.+- `about`: plain text, one line, at most 80 characters, set by the project's owner or its Lead, through the same credential+ check as other agent text (`WORDS`, `withoutCredentials`).+- The list shows only projects the reader can read (`canReadProject`), enforced by the server; at most 100 projects of+ about 150 bytes each, so at most 15 KB; never on a timer; nothing loaded beyond the Swarm's first load.+- Which row starts picked: the invitation's project, else the one that needs help most (the most waiting tasks for each+ Member working there, then the most waiting tasks, then A to Z).+- `kind` keeps `buddy | pm | regular` for clients of the last 30 days (until 2026-12-07). `role` is `lead | member`,+ derived, never stored: a Lead when a project's chat names it as `leadId`, else a Member.+- A Lead's main project is the one it leads. A deleted project clears `mainProjectId` on every agent that named it.+- No production write, no backfill: every new field is optional.++## Review Focus++- A private project the reader can't read is absent from the list, and an agent whose main project is that private+ project shows no main project to that reader (an id alone says the project exists).+- An `invitedTo` naming a project the reader can't read, or no project, picks as if none was given.+- A project with no stored pulse yet (just created) lists with 0 waiting and no Lead, never fails the read.+- `about` with a newline, or only spaces, is refused or cleared: an empty one clears the field, a line break is refused.+- An older Desktop sending `agent.new` or `buddy.create` without `mainProjectId` works exactly as today.++---++### Task 1: A project's purpose (`project.about`)++**Files:**+- Modify: `backend/src/superTabs/projects.ts` (`SwarmProject.about?: string`)+- Modify: `backend/src/superTabs/commands.ts` (schema, `WORDS`, handler beside `project.coordinatorName`)+- Test: `backend/src/superTabs/projectAbout.test.ts`++**Interfaces:**+- Produces: command `{ type: 'project.about', projectId, about: string }` (trimmed, at most 80, no line break; `''`+ clears). `SwarmProject.about` reaches readers in the head's `projects`, absent when unset.++- [ ] **Step 1: Write the failing tests.** The owner sets it and the head shows it; the Lead (agent) sets it; a member who+ is neither is refused `PROJECT_OWNER_REQUIRED`; 81 characters and a line break are refused; `''` clears it; a key pasted+ in is removed before it is stored.+- [ ] **Step 2: Run** `npx vitest run src/superTabs/projectAbout.test.ts`. Expected: FAIL (unknown command).+- [ ] **Step 3: Commit** the failing test.+- [ ] **Step 4: Implement** the field, schema, `WORDS` entry and handler.+- [ ] **Step 5: Run** the test file and `commands.test.ts` (its schema walk checks `WORDS`). Expected: PASS.+- [ ] **Step 6: Commit.**++### Task 2: The project list read++**Files:**+- Create: `backend/src/superTabs/projectList.ts`+- Modify: `backend/src/superTabs/store.ts` (`projectList(user, tabId, invitedTo?)`)+- Modify: `backend/src/routes/superTabs.ts` (GET `/api/super-tabs/:tabId/project-list?invitedTo=`)+- Test: `backend/src/superTabs/projectList.test.ts`++**Interfaces:**+- Consumes: `SwarmProject.about` (task 1), `storedPulse` (`pulse.ts`), `canReadProject`, `githubRepository`.+- Produces: `projectList(state, actor, invitedTo?: string): ProjectList`, where+ `ProjectList = { projects: ProjectRow[]; pick: string | null }` and+ `ProjectRow = { id; name; about: string | null; repositoryName: string | null; lead: { agentId; name } | null; waiting: number }`.+ Rows come in pick order: the picked one first, then the one that needs help most, then A to Z.++- [ ] **Step 1: Write the failing tests.** Only readable projects (a private one of another person is absent); the+ invitation's project is picked and first; an unreadable or unknown `invitedTo` falls back to the needs-help order; that+ order is waiting per Member working there, then waiting, then A to Z; a project without a pulse lists 0 waiting and no+ Lead; `repositoryName` is the GitHub repository's name, never a folder; a person with no readable project gets an empty+ list and `pick: null`; 100 projects with 80-character purposes stay under 15 KB.+- [ ] **Step 2: Run** `npx vitest run src/superTabs/projectList.test.ts`. Expected: FAIL (no module).+- [ ] **Step 3: Commit** the failing test.+- [ ] **Step 4: Implement** `projectList.ts`, the store method (person only, `readLoad` as `proposals` does) and the route.+- [ ] **Step 5: Run** the test file. Expected: PASS.+- [ ] **Step 6: Commit.**++### Task 3: A main project and a role on every agent++**Files:**+- Modify: `backend/src/superTabs/model.ts` (`Agent.mainProjectId?`, `AgentStartRequest.mainProjectId?`)+- Modify: `backend/src/superTabs/agentKind.ts` (`AgentRole`, `ledProjects`)+- Modify: `backend/src/superTabs/read/views.ts` (`agentView` keeps `mainProjectId` out of the part; derived `role`,+ `mainProjectId`), `backend/src/superTabs/read/contract.ts`+- Modify: `backend/src/superTabs/commands.ts` (`agent.new`, `buddy.create`, `agent.started`, `project.delete`)+- Test: `backend/src/superTabs/mainProject.test.ts`, `backend/src/superTabs/agentKind.test.ts`++**Interfaces:**+- Produces: `ledProjects(state): Map<agentId, projectId>`, one pass per read (`ledProject` scans every conversation per+ call). A Lead's main project is the one it leads, else the stored one. Derived agent row gains `role` and `mainProjectId` (null when none, or when the reader+ can't read it). `agent.new` and `buddy.create` take an optional `mainProjectId`.++- [ ] **Step 1: Write the failing tests.** A Regular agent started by the server with a main project carries it; a local+ start or a Lead that names one is refused `MAIN_PROJECT_MEMBER_ONLY`; Bring agent (`buddy.create`) with a main+ project makes a Buddy whose role is member and main project is that one; a project the person can't read is refused+ `NOT_FOUND`; a PM made by `agent.new` is a Lead whose main project is its project; the derived rows carry `role` and+ `mainProjectId` while `kind` is unchanged; a reader who can't read the main project gets null; deleting the project+ clears it; a command without `mainProjectId` behaves as today.+- [ ] **Step 2: Run** `npx vitest run src/superTabs/mainProject.test.ts src/superTabs/agentKind.test.ts`. Expected: FAIL.+- [ ] **Step 3: Commit** the failing tests.+- [ ] **Step 4: Implement.**+- [ ] **Step 5: Run** these tests and the tests of what imports the changed code (`agentNew.test.ts`, `buddies.test.ts`,+ `read/views.test.ts`, `deletion.test.ts`). Expected: PASS.+- [ ] **Step 6: Commit.**++### Task 4: The read's cost at prod scale++- [ ] **Step 1:** On a synthetic Swarm (100 projects, 600 agents, 2,000 tasks), time `readerView` on main and on this+ branch, the added derive work alone, and `projectList` (p50 and p95), and record their bytes. Put the numbers in the+ pull request; no timing is asserted in a test (no flaky timing gates). The byte bound is asserted in+ `projectList.test.ts`: 100 projects with every field at its longest stay under 64 KB (the spec's 15 KB assumed 150-byte+ rows; a 100-project list with one-line purposes measures 16.5 KB). The read touches no collection beyond the first load+ and its project chats, so no index changes.