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
Routing gaps for Regular agents after v3 (#4218) (#3472)
0xken15417263157fda
diff --git a/backend/integration/superTabComputerMoves.test.ts b/backend/integration/superTabComputerMoves.test.tsindex b7e8c2e20..de3f82bb9 100644--- a/backend/integration/superTabComputerMoves.test.ts+++ b/backend/integration/superTabComputerMoves.test.ts@@ -262,9 +262,8 @@ describe('the cleanup script', () => {describe("a Mac whose owner's Team account is about to join", () => {const run = (tab: string, command: Command, as: AuthUser = owner) => store.execute(as, tab, { operationId: randomUUID(), command })- // Swarm v3 has no Team accounts (#4248, finding 8 of #4212): the Mac takes teammates' projects through its person's own agents- // meanwhile, and the read of the owners' Team machines it still makes stays indexed.- it('reads as taking teammates\' projects, from an indexed read of the owners\' Team machines', async () => {+ // Swarm v3 (task #4218): the Mac reads as itself, which takes its person's agents' work, so it never reads "not set up".+ it('reads as taking its person\'s agents\' work while its Team account is not listed', async () => {const tab = (await store.create(owner, randomUUID(), 'Joining')).idconst invitation = await run(tab, { type: 'invite.create', email: kelvinUser.email, role: 'collaborator', conversationId: 'lead' })await run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, kelvinUser)@@ -280,11 +279,6 @@ describe("a Mac whose owner's Team account is about to join", () => {const teamWork = async () => ((await store.read(kelvinUser, tab)).state.machines!.find(m => m.machineId === 'kelvin-joining') as { teamWork?: { code?: string } }).teamWork?.codeexpect(await teamWork()).toBeUndefined()- const { state } = await store.readLoad(kelvinUser, tab)- const entries = await profiled(db, () => store.joiningTeams(db, state))- const rows = reads(entries, 'machines', ['hostMachineId'])- expect(rows, JSON.stringify(plan(rows))).toHaveLength(1)- expect(rows[0]!.planSummary, JSON.stringify(plan(rows))).toMatch(/IXSCAN \{ userId: 1/)})})diff --git a/backend/integration/superTabTeam.test.ts b/backend/integration/superTabTeam.test.tsindex 2c7eb8304..a4879250e 100644--- a/backend/integration/superTabTeam.test.ts+++ b/backend/integration/superTabTeam.test.ts@@ -683,7 +683,6 @@ describe('a teammate\'s work and the machines that take it', () => {const start = (tab: string, conversationId: string, machineId: string, user: AuthUser = owner, cwd = machineId === 'team-mac' ? '/team' : '/work/lead', at: SuperTabStore = store) =>at.execute(user, tab, { operationId: randomUUID(), command: { type: 'agent.start', request: { conversationId, machineId, engine: 'codex', name: 'Builder',cwd, worktree: false, requirements } } })- const NO_TEAM_ACCOUNT = 'MacBook Pro has no Harness Team account yet, so it runs only its owner\'s projects.'it('keeps privacy only from the team account\'s own reading, and the read says which machines take teammates\' projects', async () => {const f = await fixture()@@ -691,8 +690,9 @@ describe('a teammate\'s work and the machines that take it', () => {expect((await pool(f.tab, 'team-mac')).observation!.privacy).toEqual({ ...PASSED, seenAt: expect.any(Number) })expect((await pool(f.tab, 'team-mac')).teamWork).toEqual({ allowed: true })// The person's own sign-in claimed the same check for its MacBook: an ordinary computer proves nothing about a team account.+ // It runs its own person's agents, so it reads no Team-account rule (Swarm v3, task #4218).expect((await pool(f.tab, 'personal-mac')).observation).not.toHaveProperty('privacy')- expect((await pool(f.tab, 'personal-mac')).teamWork).toEqual({ allowed: false, code: 'TEAM_ACCOUNT_REQUIRED', reason: NO_TEAM_ACCOUNT })+ expect((await pool(f.tab, 'personal-mac')).teamWork).toEqual({ allowed: true })// The same check sent again keeps the date it first arrived, so a check that stops running goes stale.const first = (await pool(f.tab, 'team-mac')).observation!.privacy!.seenAtawait new Promise(resolve => setTimeout(resolve, 5))diff --git a/backend/src/superTabs/closedAgents.ts b/backend/src/superTabs/closedAgents.tsindex 45d928d2e..b814b4b36 100644--- a/backend/src/superTabs/closedAgents.ts+++ b/backend/src/superTabs/closedAgents.ts@@ -18,10 +18,11 @@ export const REMOVED_KEEP_MS = 30 * 24 * 60 * 60_000* one stopped for a moment before it is back (security reviews of #2569). */export const STOPPED_REMOVE_MS = 30_000-/** Whether [target] could ever leave this way: not a coordinator, a Buddy, crew (its host reopens it in place, crew.ts), one- * kept or being stopped. */+/** Whether [target] could ever leave this way: not a coordinator, a Buddy, a Regular agent, crew (its host reopens it in place,+ * crew.ts), one kept or being stopped. A Regular agent is its person's, as a Buddy is: removed, it never came back, since its own+ * chat made it confidential and it has no project to restore into (task #4218). Its person stops it. */const removable = (state: SuperTabState, target: Agent): boolean =>- !isBuddy(target) && !isCrew(target) && target.workDecision !== 'keep' && target.workDecision !== 'stop' && !ledProject(state, target.id)+ !isBuddy(target) && !target.regular && !isCrew(target) && target.workDecision !== 'keep' && target.workDecision !== 'stop' && !ledProject(state, target.id)/** Whether [report] proves [target]'s session stopped: listed stopped and, for a reservation a resume renewed, stopped in that* very generation, since an older host lists the earlier run stopped and cannot say which. */@@ -47,7 +48,7 @@ export function sessionClosed(state: SuperTabState, target: Agent, now: number):* not listed for DOWN_REMOVE_MS while the machine's other sessions still run. The last reading must be fresh and not list* them running either, so one report after a silence never removes anyone, and a report whose running list is empty never* removes by time (a fault in the host's listing would empty a whole machine). Never a coordinator (a project's end is the- * only removal that takes one), a Buddy (its owner stops it), an agent someone chose to keep: it stays, shown as closed, or+ * only removal that takes one), a Buddy or a Regular agent (its person stops it), an agent someone chose to keep: it stays, shown as closed, or* one being stopped: its host closes it and takes it out (commands.ts agent.remove). Whether a task is still held is judged by* removeClosedAgents, after the loss of tasks.*/diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex e476b0fe4..88fa7b110 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -1,4 +1,4 @@-import { authorizeTaskApproval, pendingTaskApproval, personalApprovalCommand, reopenTaskApproval, requireTaskApproval, stageTaskApproval, undecidedProposal } from './taskApproval.js'+import { authorizeTaskApproval, pendingTaskApproval, personalApprovalCommand, rejectTaskApproval, reopenTaskApproval, REQUESTER_LEFT, requireTaskApproval, stageTaskApproval, undecidedProposal } from './taskApproval.js'import type { PullRequestFilesRead } from './pullRequestFiles.js'import { legacyProposalId, migrateLegacyProposals, type LegacyProposalAsk, pmAcceptsMessage, applyProposalAction, authorizeProposalAction, authorizePersonProposal, cardPriority, createPersonProposal, createProposalCard, proposalCreateSchema, proposalFields, proposalRoot } from './proposalCards.js'import { pulseProjectOf, recordPulse, owe, settleDeleted, settleReaction, settleReply, settleRequest } from './pulse.js'@@ -72,7 +72,7 @@ import { bindPullRequestCards, bindTaskCard, pullRequestCard, recordCardMerged }import { avatarChoice, setAgentAvatar, setMemberAvatar, setStatus, setTimeZone, statusSchema, type AvatarUpload } from './profile.js'import { cancelledTags, cancelReason, switchExpired, unfinishedWork } from './tidy.js'import { namedDefault } from './catalog.js'-import { BUILT_IN_ROLE_DEFAULTS, NO_PROJECT, isAgentChat, agentProjectId, audienceOf, groupRepositoryUrl, canReadAgent, canReadProject, deletableProject, deleteProject, markConfidential, onTeamAccount, ownsProject, admitPerson, dismissPeople, requireSingleRegistration, groupProject, inviteLanding, ledProject, manageProject, MAX_ROLES, mutableProjects, placeRules, projectAgent, projectMembers, projectOf, projectsOf, readAgent, readConversation, readProject, requestedByLine, sameProject, sharedWithLeads, withRoleDefaults, type SwarmProject, PROJECT_STATUS_MAX } from './projects.js'+import { BUILT_IN_ROLE_DEFAULTS, NO_PROJECT, isAgentChat, agentProjectId, audienceOf, groupRepositoryUrl, canReadAgent, canReadProject, deletableProject, deleteProject, markConfidential, onTeamAccount, ownsProject, admitPerson, dismissPeople, requireSingleRegistration, groupProject, inviteLanding, ledProject, manageProject, MAX_ROLES, mutableProjects, placeRules, projectAgent, projectMembers, projectOf, projectsOf, readAgent, readConversation, readProject, regularCodeLine, requestedByLine, sameProject, sharedWithLeads, withRoleDefaults, type SwarmProject, PROJECT_STATUS_MAX } from './projects.js'import { recordClosing, sessionClosed } from './closedAgents.js'import { declinedWith, declinedWithout } from './sharing.js'import { actorLabel, memberChanges, memberRowText, quotedName } from './memberRows.js'@@ -2003,8 +2003,10 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,// The brief (a task with none: its title), and its acceptance checks when it has some: checks are information. Then// whom this task's pull requests are for, from its own requester (projects.ts requestedByLine).const requestedBy = requestedByLine(state, groupProject(state, group), group, worker)+ const code = worker.regular ? regularCodeLine(groupProject(state, group), worker) : nullmessage(group.id, [group.brief || group.title,...recovery ? [recovery] : [],+ ...code ? [code] : [],...group.checks.length ? [`Acceptance checks:\n${group.checks.map(c => `- ${c.description}`).join('\n')}`] : [],...requestedBy ? [requestedBy] : []].join('\n\n'), [worker.id], null, SYSTEM_ROW, undefined, undefined, undefined, assignmentId)const news = firstAssignment && assignedNotice(state, group, sender, assignmentId)@@ -4377,6 +4379,14 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,for (const target of state.agents.filter(a => a.contributorId === member.id || a.buddyOf?.personId === member.id)) {if (state.agents.some(a => a.id === target.id)) removeAgent(target)}+ // Their approvals still pending are rejected: approval is the membership's, which nobody holds once it leaves, so the task+ // stayed open for good (task #4218). Its PM is told, as a rejection tells it.+ for (const group of state.conversations.filter(c => c.taskApproval?.state === 'proposal' && c.taskApproval.personId === member.id+ && c.taskApproval.generation === member.generation)) {+ rejectTaskApproval(group, REQUESTER_LEFT, sender.id, context.now)+ effects.messages.push({ id: stableId(operationId, 'approval-left', group.id), conversationId: group.id, author: sender, replyTo: null,+ recipients: group.leadId ? [group.leadId] : [], source: { kind: 'task-approval', state: 'rejected' }, text: `Rejected: ${REQUESTER_LEFT}` })+ }// Their projects pass to a remaining member, or are nobody's: rejoining gives none of them back (task #3073).dismissPeople(state, new Set([member.id]))state.invitations = state.invitations.filter(i => i.email !== member.email)@@ -4739,9 +4749,11 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,if (command.type === 'task.approve' && command.suggestedAgentId !== undefined && command.suggestedAgentId !== (approval.suggestedAgentId ?? null)) {fail('TASK_SUGGESTION_CHANGED', 'The suggested agent changed since you looked. Read the task again and approve the agent it names now.', 409)}- approval.state = command.type === 'task.approve' ? 'approved' : 'rejected'- approval.decidedAt = context.now- if (command.type === 'task.reject') approval.reason = command.reason+ if (command.type === 'task.reject') rejectTaskApproval(group, command.reason, sender.id, context.now)+ else {+ approval.state = 'approved'+ approval.decidedAt = context.now+ }// This decision releases the gate; the ordinary work.assign path alone launches work, with all of the// store's global session, repository, machine and account checks. Never introduce a second assignment path here.if (command.type === 'task.approve' && approval.suggestedAgentId)diff --git a/backend/src/superTabs/computerMoves.test.ts b/backend/src/superTabs/computerMoves.test.tsindex fdeae8de1..90cab5888 100644--- a/backend/src/superTabs/computerMoves.test.ts+++ b/backend/src/superTabs/computerMoves.test.ts@@ -5,7 +5,7 @@ import { describe, expect, it } from 'vitest'import { applyCommand, type Command, type CommandContext } from './commands.js'import { createSuperTab, type Actor } from './model.js'import { swarmBuddyChatId } from './buddies.js'-import { joiningTeamMacs, machineTeamWork, type ContributedMachine } from './machines.js'+import { machineTeamWork, type ContributedMachine } from './machines.js'const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }const kelvin: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'kelvin', email: '[email protected]' }@@ -145,39 +145,15 @@ describe("another account's sign-in on a computer", () => {})})-// Scholes, 11-05: kelvin added his Mac, Set up showed for a couple of seconds and went away. His Harness Team account was on-// that Mac already, and joined the Swarm moments after the Mac did; until then the Mac read "not set up".+// Scholes, 11-05: kelvin added his Mac, Set up showed for a couple of seconds and went away, while his Harness Team account on+// it joined. Swarm v3 (task #4218): the Mac reads as itself, which takes its person's agents' work, so it never reads "not set up".describe('a Mac whose own Harness Team account has not joined the Swarm yet', () => {- const mac = (f: ReturnType<typeof setup>) => {+ it('reads as taking its person\'s agents\' work', () => {+ const f = setup()f.state.machines = f.state.machines!.filter(m => m.machineId === 'kelvin-mac')const pool = f.state.machines[0]!pool.observation = reading(NOW - 1000)- // Teammates' work only through its Team account, as Add machine leaves it.delete pool.ownAccountChoice- return pool- }- const row = (userId: string, hostMachineId: string, machineId = 'kelvin-team') => ({ machineId, userId, hostMachineId })-- it('is joining while its owner has a Team account on it that the Swarm does not list', () => {- const f = setup()- const pool = mac(f)- expect(joiningTeamMacs(f.state, [row('kelvin', 'kelvin-mac')])).toEqual(['kelvin-mac'])- // Swarm v3 has no Team accounts (#4248): the Mac takes teammates' projects as itself meanwhile, through its person's own agents.- expect(machineTeamWork(f.state, pool, NOW, [], [], ['kelvin-mac'])).toBeNull()- expect(machineTeamWork(f.state, pool, NOW, [], [])).toBeNull()- })-- it("is not joining with another account's Team account on it, one listed already, or no room for it", () => {- const f = setup()- mac(f)- // The Team account of the computer's previous account names that account's machine, never this one.- expect(joiningTeamMacs(f.state, [row('tt', 'kelvin-mac')])).toEqual([])- expect(joiningTeamMacs(f.state, [row('kelvin', 'another-mac')])).toEqual([])- const listed = setup()- expect(joiningTeamMacs(listed.state, [row('kelvin', 'kelvin-mac')])).toEqual([])- const cleaning = setup()- mac(cleaning)- cleaning.state.machineCleanups = [{ machineId: 'kelvin-team', removalId: 'r', machineOwnerId: 'kelvin' }]- expect(joiningTeamMacs(cleaning.state, [row('kelvin', 'kelvin-mac')])).toEqual([])+ expect(machineTeamWork(pool, NOW, [], [])).toBeNull()})})diff --git a/backend/src/superTabs/dispatch.ts b/backend/src/superTabs/dispatch.tsindex 96af3c459..b4c68a472 100644--- a/backend/src/superTabs/dispatch.ts+++ b/backend/src/superTabs/dispatch.ts@@ -9,7 +9,7 @@ import { firstMachines, isReview, machineRuleRefusal } from './machineRules.js'import { isBuddy } from './buddies.js'import { sessionClosed } from './closedAgents.js'import { activeWork, handed, occupiesAgent, reviewsWanted, type Agent, type Assignment, type Conversation, type SuperTabState } from './model.js'-import { agentProjectId, onTeamAccount, projectOf, projectsOf } from './projects.js'+import { agentProjectId, NO_PROJECT, onTeamAccount, projectOf, projectsOf, regularMayWorkIn } from './projects.js'import { barredFromTeamWritten } from './teamWritten.js'import { digestOf, localNow } from './digest.js'import { DEFAULT_TIME_ZONE } from './costs/reflection.js'@@ -99,6 +99,7 @@ const asleep = (agent: Agent): boolean => !!(agent as { asleep?: unknown }).asle* closed unless asleep, no launch still pending) with nothing in their hands and fewer than `maxHanded` handed tasks;* fewest handed first, then as the roster lists them. */export function freeCrew(state: SuperTabState, projectId: string, rules: DispatchRules, now: number): Agent[] {+ const project = projectOf(state, projectId)const leads = new Set(state.conversations.flatMap(c => c.leadId ? [c.leadId] : []))const handedBy = new Map<string, number>(), busy = new Set<string>()for (const group of state.conversations) {@@ -109,12 +110,18 @@ export function freeCrew(state: SuperTabState, projectId: string, rules: Dispatc}// A PM in a Harness Team account assigns only agents of its own machine or another Team account (store.ts teamCommand,// security review 2 of #2089): the main account stays out of its reach.- const leadId = state.conversations.find(c => c.id === projectOf(state, projectId).leadConversationId)?.leadId+ const leadId = state.conversations.find(c => c.id === project.leadConversationId)?.leadIdconst lead = leadId ? state.agents.find(a => a.id === leadId) : undefinedconst reachable = (agent: Agent) => !lead || !onTeamAccount(state, lead) || agent.machineId === lead.machineId || onTeamAccount(state, agent)const launching = (agent: Agent) => !!state.starts?.some(s => !s.poolSettled && s.poolGeneration && s.request.machineId === agent.machineId && s.harnessId === agent.harnessId)+ // An idle Regular agent is in no project until a task places it (task #4116): it is free in each project it may work in, so a+ // task its PM routed to it is handed over (task #4218). The assignment checks the same again (projects.ts sameProject).+ const inProject = (agent: Agent) => {+ const own = agentProjectId(state, agent)+ return own === projectId || (!!agent.regular && own === NO_PROJECT && regularMayWorkIn(state, agent, project))+ }return state.agents- .filter(agent => agentProjectId(state, agent) === projectId && !leads.has(agent.id) && !isBuddy(agent)+ .filter(agent => inProject(agent) && !leads.has(agent.id) && !isBuddy(agent)// Nor a Team account's, which takes no new work (task #4120).&& agent.workDecision !== 'stop' && !onTeamAccount(state, agent) && !moving(agent) && (asleep(agent) || !sessionClosed(state, agent, now)) && !launching(agent)&& !busy.has(agent.id) && (handedBy.get(agent.id) ?? 0) < rules.maxHanded && reachable(agent)@@ -168,7 +175,7 @@ const onStrongModel = (member: Agent): boolean => {/** The tasks [member] could be handed now, best first: those pinned to it (oldest pin first), then its lane's open tasks.* A task it just lost to the 3-hour clock is not offered to it. */-export function candidatesFor(state: SuperTabState, member: Agent, rules: DispatchRules, now: number, open = openTasks(state, agentProjectId(state, member)!, now),+export function candidatesFor(state: SuperTabState, member: Agent, rules: DispatchRules, now: number, open: Conversation[],skip: Skip = () => false) {const lostByIt = (group: Conversation) => group.lostAttempt?.agentId === member.id && group.assignment?.status === 'lost'const pinned = open.filter(g => pinOf(g)?.agentId === member.id).sort((a, b) => pinOf(a)!.at - pinOf(b)!.at)diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.tsindex b06612ffb..62e787e47 100644--- a/backend/src/superTabs/machines.ts+++ b/backend/src/superTabs/machines.ts@@ -292,7 +292,7 @@ export function startPreparing(state: SuperTabState, start: AgentStart, now: num// work. It would run as that machine's owner, with their files, logins and subscriptions, so it is admitted only on a// Team machine — the Mac's Harness Team account, or a machine used only for agents — that shows its privacy now.// Everything else refuses it and says why; a person's own projects on their own machines are unchanged.-// Until that is required everywhere (teamAccountRequired), it holds only on machines that have a team account.+// Swarm v3 (task #4120) runs a person's own agent on their own computer instead: this holds only on a Team account (#4218)./** How long a passed privacy check counts, from when this server first received it. The team account checks again* every 5 minutes (cli/src/team/privacy.ts PRIVACY_RECHECK_MS) and reports within a 15-second beat, so a healthy@@ -314,7 +314,7 @@ export function observedPrivacy(previous: StoredPrivacy | undefined, reported: M}export type TeamWorkCode = 'TEAM_WRITTEN_WORK' | 'MACHINE_OFFLINE' | 'TEAM_ACCOUNT_REQUIRED' | 'PRIVACY_UNCHECKED' | 'PRIVACY_CHECK_FAILED' | 'PRIVACY_CHECK_STALE'- | 'MACHINE_IN_OTHER_WORKSPACE' | 'NOT_SWARM_MACHINE' | 'MACHINE_PROJECTS' | 'ACCESS_MISSING' | 'TEAM_ACCOUNT_JOINING' | 'TEAM_ACCOUNTS_REMOVED' | 'NOT_YOUR_COMPUTER' | 'READ_ONLY' | 'STEP_OS'+ | 'MACHINE_IN_OTHER_WORKSPACE' | 'NOT_SWARM_MACHINE' | 'MACHINE_PROJECTS' | 'ACCESS_MISSING' | 'TEAM_ACCOUNTS_REMOVED' | 'NOT_YOUR_COMPUTER' | 'READ_ONLY' | 'STEP_OS'export interface TeamWorkRefusal { code: TeamWorkCode; reason: string }/** Refusals that hold until a person acts on the machine; a stale check or an offline machine may pass again by itself. */export const LASTING_TEAM_REFUSALS: readonly string[] = ['TEAM_ACCOUNT_REQUIRED', 'PRIVACY_UNCHECKED', 'PRIVACY_CHECK_FAILED', 'MACHINE_IN_OTHER_WORKSPACE']@@ -344,11 +344,12 @@ export function teamAccountRequired(): boolean {}/** Why this contributed machine may not run a teammate's project now, or null when it may. `teamRow`: its account row- * says it is signed in as a team account (`Machine.sessionKind`), read by the store. `required`: whether the Swarm it is- * in needs a team account on every machine ([teamAccountRequired] of that Swarm). */+ * says it is signed in as a team account (`Machine.sessionKind`), read by the store. A machine that is not a Team account+ * runs its own person's agents, whatever they work on (teamWorkCheck), so it reads no rule: it read "has no Harness Team+ * account yet" where the rule was required or it was added at join, and the route left those agents out (task #4218). *//** `otherWorkspace`: the machine is contributed to a Swarm of another Workspace too (store.ts otherWorkspaceMachines). Its Team account* runs every teammate's work as one macOS user, so it serves one Workspace's teammates at a time (swarm-workspaces design). */-export function teamWorkRefusal(pool: ContributedMachine, now: number, teamRow = false, required = teamAccountRequired(), otherWorkspace = false): TeamWorkRefusal | null {+export function teamWorkRefusal(pool: ContributedMachine, now: number, teamRow = false, otherWorkspace = false): TeamWorkRefusal | null {const reading = pool.observation, name = pool.name// A Mac's Harness Team account whose machine is no longer a Team machine was removed (`harness team remove` deletes it).// Its last reading stays fresh for a minute, and in that minute it read as taking teammates' work and a Lead's route@@ -357,7 +358,7 @@ export function teamWorkRefusal(pool: ContributedMachine, now: number, teamRow =// Its owner let teammates' work run in their own account here: their explicit choice wins over the Swarm-wide rule, for// this machine only (River, 11-04).if (ownAccountWork(pool)) return null- if (!teamRow && reading?.sessionKind !== 'team' && !required) return null+ if (!teamRow && reading?.sessionKind !== 'team') return nullif (otherWorkspace) return { code: 'MACHINE_IN_OTHER_WORKSPACE', reason: `The Harness Team account on ${name} also serves another ${WORKSPACE_LABEL}'s Swarms, ${ONLY_OWN} here.` }if (!reading || now - reading.receivedAt > MACHINE_FRESH_MS) {// A Mac's team account goes by its Mac's name ("One machine"), and the Mac itself may well be online.@@ -468,39 +469,13 @@ export function teamPoolOf(state: SuperTabState, pool: ContributedMachine, live?}/**- * Whether [pool] takes teammates' work, as a Swarm's reads say it: a Mac whose Harness Team account is in this Swarm runs- * that work there (teamMachineFor), so it reads as its account does. Read as itself, every Mac read "has no Harness- * Team account yet" next to the very account that took the work, and a Lead took that to mean the Mac could not- * (2026-10-28). Any other machine, and a Mac without one, reads as itself.+ * Whether [pool] takes teammates' work, as a Swarm's reads say it. Every machine reads as itself: a teammate's agent on a Mac+ * runs in its own person's account there, never in the Mac's Harness Team account (task #4120), so that account's privacy check+ * no longer speaks for the Mac (task #4218).*/-export function machineTeamWork(state: SuperTabState, pool: ContributedMachine, now: number, teamMachines: readonly string[],- otherWorkspaceMachines: readonly string[] = [], joiningTeams: readonly string[] = []): TeamWorkRefusal | null {- // Its owner lets teammates' work run in their own account: starts stay on the Mac, so the Mac itself is what routing reads- // (security review 2 of #2981).- const team = !pool.hostMachineId && !ownAccountWork(pool) ? teamPoolOf(state, pool, teamMachines) : undefined- const subject = team ?? pool- const refusal = teamWorkRefusal(subject, now, teamMachines.includes(subject.machineId), teamAccountRequired(), otherWorkspaceMachines.includes(subject.machineId))- // Its owner's Team account is on it and joins on the Mac's next poll (read/hostRows.ts joinTeam): not "not set up" meanwhile,- // which offered Set up for those seconds (Scholes, 11-05).- if (refusal?.code === 'TEAM_ACCOUNT_REQUIRED' && !team && joiningTeams.includes(pool.machineId)) {- return { code: 'TEAM_ACCOUNT_JOINING', reason: `The Harness Team account on ${pool.name} is joining this Swarm, ${ONLY_OWN} until it has.` }- }- return refusal-}--/** A Harness Team machine of an account (its account row): the Mac it lives on. */-export interface TeamMachineRow { machineId: string; userId: string; hostMachineId: string }--/**- * The Macs of the Swarm whose owner has a Harness Team account on it that the Swarm does not list yet, and room for it: the- * ones its host adds on its next poll (read/hostRows.ts joinTeam), from [teams], those owners' Team machines. A Team account- * of another account names that account's own Mac, never this one (#3122).- */-export function joiningTeamMacs(state: SuperTabState, teams: readonly TeamMachineRow[]): string[] {- const listed = (machineId: string) => state.machines?.some(m => m.machineId === machineId) || state.machineCleanups?.some(c => c.machineId === machineId)- return (state.machines ?? []).filter(mac => !mac.hostMachineId && !mac.removal && !mac.buddyOnly && mac.scope === 'swarm'- && teams.some(t => t.hostMachineId === mac.machineId && t.userId === mac.contributorId && !listed(t.machineId))- && machineRoom(state, mac.contributorId, { team: true }) > 0).map(mac => mac.machineId)+export function machineTeamWork(pool: ContributedMachine, now: number, teamMachines: readonly string[],+ otherWorkspaceMachines: readonly string[] = []): TeamWorkRefusal | null {+ return teamWorkRefusal(pool, now, teamMachines.includes(pool.machineId), otherWorkspaceMachines.includes(pool.machineId))}/** The projects with work on [machineId]: its agents' and its pending starts'. */diff --git a/backend/src/superTabs/ownAccountWork.test.ts b/backend/src/superTabs/ownAccountWork.test.tsindex 6f76a13bd..25efcf8b2 100644--- a/backend/src/superTabs/ownAccountWork.test.ts+++ b/backend/src/superTabs/ownAccountWork.test.ts@@ -89,7 +89,7 @@ describe('teammates\' work in a Mac owner\'s own account', () => {expect(f.machine('gray-mac').teamAccountOnly).toBe(true)// Routing reads it as a machine that takes a teammate's work.expect(teamWorkRefusal(f.machine('gray-mac'), NOW)).toBeNull()- expect(machineTeamWork(f.state, f.machine('gray-mac'), NOW, ['gray-team'])).toBeNull()+ expect(machineTeamWork(f.machine('gray-mac'), NOW, ['gray-team'])).toBeNull()})it('is changed by nobody but the machine\'s owner: not the Swarm\'s owner, a teammate, an agent or a Buddy', () => {@@ -126,13 +126,13 @@ describe('teammates\' work in a Mac owner\'s own account', () => {askedIn: { conversationId: 'lead', messageId: 'm-gray' } })})- it('reads the Mac itself, not its Team account, for routing once it is on', () => {+ // Swarm v3 (task #4218): the Mac reads as itself whether the choice is on or not; its Team account takes no new work.+ it('reads the Mac itself, not its Team account, for routing', () => {const f = swarm()- // A stale privacy check on the Team account refuses teammates there; with the owner's choice on, starts run on the Mac.f.machine('gray-team').observation = { ...reading('team', PASSED), privacy: { ...PASSED, seenAt: NOW - 24 * 60 * 60_000 } }- expect(machineTeamWork(f.state, f.machine('gray-mac'), NOW, ['gray-team'])?.code).toBe('PRIVACY_CHECK_STALE')+ expect(machineTeamWork(f.machine('gray-mac'), NOW, ['gray-team'])).toBeNull()f.choose(true)- expect(machineTeamWork(f.state, f.machine('gray-mac'), NOW, ['gray-team'])).toBeNull()+ expect(machineTeamWork(f.machine('gray-mac'), NOW, ['gray-team'])).toBeNull()})it('checks the owner before saying an entry is a Team account\'s', () => {diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.tsindex e581c9513..6736b0cfb 100644--- a/backend/src/superTabs/projects.ts+++ b/backend/src/superTabs/projects.ts@@ -327,6 +327,17 @@ export function requestedByLine(state: SuperTabState, project: SwarmProject, groreturn requester?.email ? `Start each pull request body with: Requested by ${agentWrittenNameOf(state, requester.id)} through Harness.` : null}+/** Where Regular agent [worker] finds [project]'s code, for its task's message. It starts in its own empty folder, in no project+ * (task #4116), and nothing prepares a checkout when it is given a task, so the message says where the code is (task #4218):+ * the GitHub repository to clone with its own person's git, or the checkout on its own computer. A checkout's folder is+ * named only on that computer, its person's own. */+export function regularCodeLine(project: SwarmProject, worker: Agent): string {+ const repository = project.repository+ if (repository?.repositoryUrl) return `This project's code is ${repository.repositoryUrl}. Clone it into a folder inside your own folder and work on a branch there, with the git and gh signed in on this computer.`+ if (repository && repository.machineId === worker.machineId) return `This project's code is checked out at ${repository.cwd} on this computer. Make a git worktree of it inside your own folder and work on a branch there.`+ return 'This project has no code this computer can reach: it has no GitHub repository. Ask its PM before changing code.'+}+export function readProject(state: SuperTabState, actor: Actor, projectId: string): SwarmProject {author(state, actor)const project = projectOf(state, projectId)@@ -640,7 +651,7 @@ export function readAgent(state: SuperTabState, actor: Actor, agentId: string):/** Whether Regular agent [target] may take a task in [project]: its person reads it (it works only where they could read it* themselves), and, once it has worked in a private project, it is that one: its one conversation holds that project's* content, which no other project's members may hear from it (security review 2 of #4116). Public work moves on freely. */-function regularMayWorkIn(state: SuperTabState, target: Agent, project: SwarmProject): boolean {+export function regularMayWorkIn(state: SuperTabState, target: Agent, project: SwarmProject): boolean {const member = state.people.find(p => p.id === target.contributorId)return !!member && canReadProject(state, { kind: 'person', userId: member.id, email: member.email }, project)&& (!target.privateProjectId || target.privateProjectId === project.id)diff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.tsindex 334d01f9a..3a97cc7d3 100644--- a/backend/src/superTabs/read/service.ts+++ b/backend/src/superTabs/read/service.ts@@ -60,7 +60,7 @@ export const SWARM_ROW_READS_MS = 3_000const MAX_SWARM_ROW_READS = 2_000type SwarmRow = { format: number | null; deletedAt: Date | null }type SwarmRowRead = { at: number; read: Promise<SwarmRow | null> }-type MachineReads = [teamMachines: string[], otherWorkspaceMachines: string[], machineVersions: Record<string, string>, joiningTeams: string[]]+type MachineReads = [teamMachines: string[], otherWorkspaceMachines: string[], machineVersions: Record<string, string>]/** The conversations the reader can read now, a dormant one read by id included. */function readableGroups(read: Read): Set<string> {@@ -241,8 +241,8 @@ export class SwarmReads {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 })+ const [teamMachines, otherWorkspaceMachines, machineVersions] = await this.machineLookups(state)+ const view = readerView(loaded, actor, t0, { teamMachines, otherWorkspaceMachines, machineVersions, 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)})@@ -665,13 +665,13 @@ export class SwarmReads {const loaded = await loader(cached, tabId, opts)const state = parts.reassemble(loaded, { share: true })const actor = await this.store.actor(tx, user, state, asAgentId)- const [[teamMachines, otherWorkspaceMachines, machineVersions, joiningTeams], counts, newest] = await Promise.all([+ const [[teamMachines, otherWorkspaceMachines, machineVersions], counts, newest] = await Promise.all([this.machineLookups(state),actor.kind === 'person' ? Promise.all([waitingMentions(tx, tabId, state, actor, t0, waitingRows), decisionsWaiting(tx, tabId, state, actor),activityDigest(tx, tabId, actor.userId, t0), remindersDigest(tx, tabId, actor.userId)]) : undefined,readLastChangedAt(tx, cached, tabId),])- const view = readerView(loaded, actor, t0, { teamMachines, otherWorkspaceMachines, machineVersions, joiningTeams, teamAccountsIdle: this.store.teamAccountsIdle,+ const view = readerView(loaded, actor, t0, { teamMachines, otherWorkspaceMachines, machineVersions, teamAccountsIdle: this.store.teamAccountsIdle,...(counts ? { mentionsWaiting: counts[0].count, mentionsDigest: counts[0].digest, decisionsWaiting: counts[1].count,decisionsDigest: counts[1].digest, activityDigest: counts[2], remindersDigest: counts[3] } : {}) }, state)// People count a chat unread by its newest main row; agents keep no read marks.@@ -683,7 +683,7 @@ export class SwarmReads {* same answer for every reader, whose view hides what it may not see, so one lookup serves every read of the Swarm for* MACHINE_READS_MS. Commands that admit work still look up afresh (store.ts executeOnce). Outside any transaction, as every read is. */private machineLookups(state: SuperTabState): Promise<MachineReads> {- if (!state.machines?.length) return Promise.resolve([[], [], {}, []])+ if (!state.machines?.length) return Promise.resolve([[], [], {}])const now = this.now()const key = JSON.stringify([state.id, state.environment, state.workspaceId ?? null, state.machines.map(m => m.machineId).sort()])const kept = this.machineReads.get(key)@@ -692,9 +692,8 @@ export class SwarmReads {if (now >= entry.at && now - entry.at < MACHINE_READS_MS) breakthis.machineReads.delete(old)}- const entry = { at: now, read: Promise.all([this.store.machineFacts(this.db, state), this.store.otherWorkspaceMachines(this.db, state),- this.store.joiningTeams(this.db, state)])- .then(([facts, other, joining]): MachineReads => [facts.team, other, facts.versions, joining]) }+ const entry = { at: now, read: Promise.all([this.store.machineFacts(this.db, state), this.store.otherWorkspaceMachines(this.db, state)])+ .then(([facts, other]): MachineReads => [facts.team, other, facts.versions]) }this.machineReads.delete(key)this.machineReads.set(key, entry)// A failed lookup is never reused.diff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.tsindex aeddc7c4c..46824f411 100644--- a/backend/src/superTabs/read/views.ts+++ b/backend/src/superTabs/read/views.ts@@ -45,8 +45,6 @@ export interface ReadExtras {teamAccountsIdle?: boolean/** Each contributed machine's CLI version as its daemon last connected (store.ts machineFacts). */machineVersions?: Record<string, string>- /** Macs whose owner's Harness Team account on them is not listed yet (store.ts joiningTeams). */- joiningTeams?: string[]/** A person's open mentions, counted by the store. */mentionsWaiting?: number/** Which ones they are, as a digest (mentions.ts). */@@ -187,7 +185,7 @@ function derive(state: SuperTabState, visible: SuperTabState, actor: Actor, now:const slots = slotCounter(state)const machine = (pool: ContributedMachine) => {const stored = state.machines!.find(m => m.machineId === pool.machineId)!- const refusal = machineTeamWork(state, stored, now, extras.teamMachines, extras.otherWorkspaceMachines ?? [], extras.joiningTeams ?? [])+ const refusal = machineTeamWork(stored, now, extras.teamMachines, extras.otherWorkspaceMachines ?? [])const version = extras.machineVersions?.[pool.machineId]const suspended = suspendedEngines(stored, now)const machineSuspended = machineSuspensionReason(stored, now)diff --git a/backend/src/superTabs/regularAssign.test.ts b/backend/src/superTabs/regularAssign.test.tsindex 9010f6435..218857c24 100644--- a/backend/src/superTabs/regularAssign.test.ts+++ b/backend/src/superTabs/regularAssign.test.ts@@ -2,7 +2,9 @@ import { describe, expect, it } from 'vitest'import { applyCommand, type Command, type CommandContext } from './commands.js'import { createSuperTab, SuperTabError, type Actor, type AgentConfiguration, type SuperTabState } from './model.js'import type { ContributedMachine } from './machines.js'-import { agentProjectId, canReadAgent, canReadGroup, NO_PROJECT } from './projects.js'+import { agentProjectId, canReadAgent, canReadGroup, NO_PROJECT, projectOf } from './projects.js'+import { DISPATCH_RULES, dispatchPlan, freeCrew } from './dispatch.js'+import { closedAgents, STOPPED_REMOVE_MS } from './closedAgents.js'// Task #4116 (Swarm v3, anh Dee 11-07): "A Regular agent isn't tied to a project; the task decides where it works." Its PM gives// it a task only in a project its person can read, so nothing reaches its person that they could not read anyway; while it@@ -186,3 +188,68 @@ describe('a Regular agent and its task', () => {expect(canReadAgent(f.state, owner, f.agent(f.ada))).toBe(false)})})++// Task #4218 (anh Dee's Buddy's review): a Regular agent starts in its own empty folder, so its task tells it where the code is.+describe('a Regular agent\'s task', () => {+ const brief = (f: ReturnType<typeof swarm>, app: ReturnType<ReturnType<typeof swarm>['project']>) =>+ f.run({ type: 'work.assign', conversationId: app.task, agentId: f.ada }, app.asPm).messages+ .find(m => m.recipients.includes(f.ada))!.text++ it('names its project\'s GitHub repository, to clone into its own folder', () => {+ const f = swarm(), app = f.project('app', 'public')+ projectOf(f.state, app.projectId).repository = { machineId: 'owner-mac', cwd: '/code/app', repositoryUrl: 'https://github.com/acme/app' }+ const text = brief(f, app)+ expect(text).toContain('https://github.com/acme/app')+ expect(text).not.toContain('/code/app')+ })++ it('names its project\'s checkout when it is on the agent\'s own computer', () => {+ const f = swarm(), app = f.project('app', 'public')+ projectOf(f.state, app.projectId).repository = { machineId: 'mate-mac', cwd: '/code/app', repositoryUrl: null }+ expect(brief(f, app)).toContain('/code/app')+ })++ it('says when its project has no code it can reach', () => {+ const f = swarm(), app = f.project('app', 'public')+ projectOf(f.state, app.projectId).repository = { machineId: 'owner-mac', cwd: '/code/app', repositoryUrl: null }+ const text = brief(f, app)+ expect(text).toContain('no code this computer can reach')+ expect(text).not.toContain('/code/app')+ })+})++// Task #4218: the automatic picks left out every idle Regular agent, which is in no project until a task places it, so a task+// its PM routed (pinned) to one was never handed over.+describe('the automatic picks and an idle Regular agent', () => {+ const pin = (f: ReturnType<typeof swarm>, task: string) => { f.group(task).pin = { agentId: f.ada, why: 'findings', at: NOW } }++ it('hand it a task pinned to it in a project its person reads', () => {+ const f = swarm(), app = f.project('app', 'public')+ pin(f, app.task)+ expect(freeCrew(f.state, app.projectId, DISPATCH_RULES, NOW).map(a => a.id)).toContain(f.ada)+ expect(dispatchPlan(f.state, app.projectId, DISPATCH_RULES, NOW)).toContainEqual(expect.objectContaining({ conversationId: app.task, agentId: f.ada }))+ })++ it('never in a project its person cannot read, nor outside the private project it worked in', () => {+ const f = swarm(), secret = f.project('secret', 'private')+ pin(f, secret.task)+ expect(freeCrew(f.state, secret.projectId, DISPATCH_RULES, NOW).map(a => a.id)).not.toContain(f.ada)+ expect(dispatchPlan(f.state, secret.projectId, DISPATCH_RULES, NOW)).toEqual([])+ const app = f.project('app', 'public')+ f.agent(f.ada).privateProjectId = 'elsewhere'+ pin(f, app.task)+ expect(freeCrew(f.state, app.projectId, DISPATCH_RULES, NOW).map(a => a.id)).not.toContain(f.ada)+ })+})++// Task #4218: a closed session removed its Regular agent, and nothing brought it back: its own chat made it count as+// confidential, and it has no project to restore into. It is its person's, as a Buddy is: it stays, shown closed, in its chat.+describe('a Regular agent whose session closed', () => {+ it('stays listed in its own chat, to come back when its session runs again', () => {+ const f = swarm()+ f.agent(f.ada).downSince = new Date(NOW - 10 * STOPPED_REMOVE_MS).toISOString()+ const report = { runningHarnessIds: ['h-other'], stoppedHarnessIds: ['h-ada'] }+ expect(closedAgents(f.state, 'mate-mac', report, NOW)).toEqual([])+ expect(f.state.conversations.some(c => c.kind === 'agent-chat' && c.agentIds.includes(f.ada))).toBe(true)+ })+})diff --git a/backend/src/superTabs/stepOs.test.ts b/backend/src/superTabs/stepOs.test.tsindex d51a74189..5984796db 100644--- a/backend/src/superTabs/stepOs.test.ts+++ b/backend/src/superTabs/stepOs.test.ts@@ -4,8 +4,9 @@*/import { describe, expect, it } from 'vitest'import { applyCommand, type Command, type CommandContext } from './commands.js'-import { candidatesFor, DISPATCH_RULES } from './dispatch.js'+import { candidatesFor, DISPATCH_RULES, openTasks } from './dispatch.js'import { sweepLiveness } from './liveness.js'+import { agentProjectId } from './projects.js'import { createSuperTab, type Actor, type AgentConfiguration } from './model.js'import { stepsOf } from './steps.js'@@ -65,7 +66,7 @@ function fixture() {held.lost = { reason: 'its machine went offline', at: NOW }linuxStep.lostAttempt = { id: held.id, agentId: linux, machineId: 'linux1', engine: 'claude' }}- const offered = (agentId: string) => candidatesFor(state, agent(agentId), DISPATCH_RULES, NOW).map(c => c.group.id)+ const offered = (agentId: string) => candidatesFor(state, agent(agentId), DISPATCH_RULES, NOW, openTasks(state, agentProjectId(state, agent(agentId))!, NOW)).map(c => c.group.id)return { run, as, lead, task, dev, linux, linux2, mac, mac2, win, linuxStep, step, lose, offered, get state() { return state } }}diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 92e0540e2..46d868cf8 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -10,7 +10,7 @@ import { isCrew } from './crew.js'import { writeReactionActivity, writeReplyActivity } from './activity.js'import { phoneNotices, type DecisionRow, type ReplyRow, type TagRow } from '../push/notices.js'import type { PhoneNotice } from '../push/sender.js'-import { admitMachineStart, joiningTeamMacs, type TeamMachineRow, accountMachineName, availableSlots, expireRemovals, followAccountName, LASTING_TEAM_REFUSALS, machineContribution, machineObservationSchema, slotCounter, machineTeamWork, preparableStart, readingOnly, refusableStart, recordAgentPresence, renamedBy, removalPreview, startPreparing, storedObservation, swarmGridRow, teamAccountRequired, teamWorkRefusal, ownAccountWork, ownAccountNote, type MachineObservation } from './machines.js'+import { admitMachineStart, accountMachineName, availableSlots, expireRemovals, followAccountName, LASTING_TEAM_REFUSALS, machineContribution, machineObservationSchema, slotCounter, machineTeamWork, preparableStart, readingOnly, refusableStart, recordAgentPresence, renamedBy, removalPreview, startPreparing, storedObservation, swarmGridRow, teamAccountRequired, teamWorkRefusal, ownAccountWork, ownAccountNote, type MachineObservation } from './machines.js'import { expireAccess } from './machineAccess.js'import { authorForAgent, lazyUsernames, namesPerson, rowForAgent, shownNameOf } from './personNames.js'import { machineSuspensionReason, readingClearsSuspensions, suspendedEngines } from './engineHealth.js'@@ -923,19 +923,6 @@ export class SuperTabStore {versions: Object.fromEntries(rows.flatMap(r => r.clientVersion ? [[r.machineId, r.clientVersion] as const] : [])) }}- /** The Swarm's Macs whose owner's Harness Team account on it is not listed yet (machines.ts joiningTeamMacs): they read- * joining, not "not set up" (#3122). One read of those owners' Team machines on their account index; none with no Mac. */- async joiningTeams(tx: Transaction, state: SuperTabState): Promise<string[]> {- const macs = (state.machines ?? []).filter(m => !m.hostMachineId && !m.removal && !m.buddyOnly)- if (!macs.length) return []- const teams = await tx.machine.aggregateRaw({ pipeline: [- { $match: { userId: { $in: [...new Set(macs.map(m => m.contributorId))] }, sessionKind: 'team', hostMachineId: { $in: macs.map(m => m.machineId) },- autonomousEnv: state.environment, deletedAt: null } },- { $limit: 200 }, { $project: { _id: 0, machineId: 1, userId: 1, hostMachineId: 1 } }],- options: { hint: { userId: 1 } } }) as unknown as TeamMachineRow[]- return joiningTeamMacs(state, teams)- }-/** This Swarm's contributed machines that are also contributed to a Swarm of another Workspace: their Harness Team account* takes no teammate's work here (machines.ts teamWorkRefusal). One indexed read of the machines' parts, one of rows. */async otherWorkspaceMachines(tx: Transaction, state: SuperTabState): Promise<string[]> {@@ -1582,13 +1569,12 @@ export class SuperTabStore {const facts = visible.machines?.length ? await this.machineFacts(tx, state) : { team: [], versions: {} as Record<string, string> }const teamMachines = facts.teamconst otherWorkspace = visible.machines?.length ? await this.otherWorkspaceMachines(tx, state) : []- const joining = visible.machines?.length ? await this.joiningTeams(tx, state) : []const slots = slotCounter(state)return { lastChangedAt: await readLastChangedAt(tx, view, tabId) ?? 0, state: { ...visible, ...mentions, machines: visible.machines?.map(pool => {const stored = state.machines!.find(m => m.machineId === pool.machineId)!// Whether it takes teammates' projects now, and if not why (machines.ts teamWorkRefusal): what routing leaves it// out for, and what Desktop can show on the machine.- const refusal = machineTeamWork(state, stored, now, teamMachines, otherWorkspace, joining)+ const refusal = machineTeamWork(stored, now, teamMachines, otherWorkspace)const suspended = suspendedEngines(stored, now)const machineSuspended = machineSuspensionReason(stored, now)return { ...pool, availableSlots: availableSlots(state, stored, slots(stored)),@@ -2639,7 +2625,7 @@ export class SuperTabStore {const assigned = command.type === 'work.assign' ? command.agentId : undefinedconst rules = dispatchRules((await currentRules(tx, state.id, project.id)).rules)const now = this.now(), member = freeCrew(state, project.id, rules, now).find(a => a.id === assigned)- if (!member || !candidatesFor(state, member, rules, now).some(c => c.group.id === task.id)) {+ if (!member || !candidatesFor(state, member, rules, now, openTasks(state, project.id, now)).some(c => c.group.id === task.id)) {fail('DISPATCH_STALE', 'This task is no longer one to hand out to this member.', 409)}try {diff --git a/backend/src/superTabs/taskApproval.test.ts b/backend/src/superTabs/taskApproval.test.tsindex e6a1899a7..cbcfef2e4 100644--- a/backend/src/superTabs/taskApproval.test.ts+++ b/backend/src/superTabs/taskApproval.test.ts@@ -116,6 +116,24 @@ describe('personal approval enforced before work', () => {expect(() => f.runCommand({ type: 'task.approve', conversationId: id })).toThrow(expect.objectContaining({ code: 'TASK_APPROVAL_DECIDED' }))expect(() => f.runCommand({ type: 'work.assign', conversationId: id, agentId: f.candidate }, f.pm)).toThrow(expect.objectContaining({ code: 'TASK_APPROVAL_REQUIRED' }))})+ // Task #4218: a rejection wrote only the approval, so the PM was told the proposal still waited and could accept it into a task+ // that could never run.+ it('settles the proposal its person rejects, which its PM can no longer accept', () => {+ const f = fixture(); f.mode('review'); f.propose()+ const card = f.state.conversations.find(c => c.proposal)!+ f.runCommand({ type: 'task.reject', conversationId: card.id, reason: 'Not now' })+ expect(f.card(card.id).proposal).toMatchObject({ decision: { kind: 'no', reason: 'Not now', at: NOW } })+ expect(() => f.runCommand({ type: 'proposal.decide', conversationId: card.id, decision: 'accept', reason: 'Build it', task,+ checks: [{ description: 'Restores drafts' }] }, f.pm)).toThrow(expect.objectContaining({ code: 'PROPOSAL_DECIDED' }))+ })+ // Task #4218: approval is the requesting membership's, so once they left nobody could approve or reject it again, and the task+ // stayed open for good. A rejoined person decides nothing of the membership they left.+ it('rejects a leaving requester\'s pending approvals and tells the PM', () => {+ const f = fixture(); f.mode('review'); const id = f.create()+ const left = f.runCommand({ type: 'member.remove', userId: peer.userId })+ expect(f.card(id).taskApproval).toMatchObject({ state: 'rejected', decidedAt: NOW, reason: 'Its requester left the Swarm.' })+ expect(left.messages.some(m => m.conversationId === id && m.recipients.includes(f.lead))).toBe(true)+ })it.each([undefined, owner.userId])('stages personal approval when an unassigned task is attributed from %s to a Review requester', previous => {const f = fixture(); f.mode('review')const id = f.runCommand({ type: 'conversation.create', title: 'PM maintenance', task, priority: 'P2',diff --git a/backend/src/superTabs/taskApproval.ts b/backend/src/superTabs/taskApproval.tsindex cdbb520b4..5cbceae14 100644--- a/backend/src/superTabs/taskApproval.ts+++ b/backend/src/superTabs/taskApproval.ts@@ -52,6 +52,21 @@ export function authorizeTaskApproval(state: SuperTabState, actor: Actor, type:if (!approval || (!own && !pm)) fail('TASK_APPROVAL_FORBIDDEN', 'Only the requesting person can approve or reject; their PM may suggest an agent.', 403)return group}+/** Why a leaving person's pending approvals are rejected (commands.ts member.remove). */+export const REQUESTER_LEFT = 'Its requester left the Swarm.'+/** Rejects [group]'s approval for [reason], and settles its proposal with it (task #4218): the PM's clock and proposal.decide read+ * the proposal's own decision, so a rejection that left it open was overdue for good and could still be accepted. */+export function rejectTaskApproval(group: Conversation, reason: string, by: string, now: number): void {+ const approval = pendingTaskApproval(group)+ approval.state = 'rejected'+ approval.decidedAt = now+ approval.reason = reason+ const proposal = group.proposal+ if (proposal && !proposal.decision && !proposal.mergedInto) {+ proposal.decision = { kind: 'no', reason, at: now, by }+ delete proposal.overdue+ }+}export function pendingTaskApproval(group: Conversation): TaskApproval {const approval = group.taskApprovalif (!approval || approval.state !== 'proposal') fail('TASK_APPROVAL_DECIDED', 'This task already has an approval decision.', 409)diff --git a/backend/src/superTabs/teamRouting.test.ts b/backend/src/superTabs/teamRouting.test.tsindex 129e0ffc7..a0e20a5f2 100644--- a/backend/src/superTabs/teamRouting.test.ts+++ b/backend/src/superTabs/teamRouting.test.ts@@ -142,12 +142,13 @@ describe('which machines take a teammate\'s project', () => {expect(teamWorkRefusal(pool(reading('team', { ...FAILED, item: 'credentials' })), NOW)?.reason).toContain('(credentials: it could list its owner\'s Windows Credential Manager folder)')})- it('not on a machine with no Harness Team account', () => {- expect(teamWorkRefusal(pool(reading('computer')), NOW)).toEqual({ code: 'TEAM_ACCOUNT_REQUIRED',- reason: 'MacBook Pro has no Harness Team account yet, so it runs only its owner\'s projects.' })+ // Swarm v3 (task #4120): a person's own agent works on their own computer, in their own account, so a machine that is not a+ // Team account reads no Team-account rule, even where the rule was required everywhere (task #4218).+ it('on a machine with no Harness Team account, which runs its own person\'s agents', () => {+ expect(teamWorkRefusal(pool(reading('computer')), NOW)).toBeNull()// A reading from before readings were stamped with their session is an ordinary machine's.const { sessionKind: _kind, ...unstamped } = reading('computer')- expect(teamWorkRefusal(pool(unstamped as Reading), NOW)?.code).toBe('TEAM_ACCOUNT_REQUIRED')+ expect(teamWorkRefusal(pool(unstamped as Reading), NOW)).toBeNull()})it('not on a Team machine that reported no privacy check', () => {@@ -158,10 +159,8 @@ describe('which machines take a teammate\'s project', () => {})it('not while offline', () => {- for (const offline of [pool(), pool(reading('team', PASSED, NOW - 46_000))]) {- expect(teamWorkRefusal(offline, NOW)).toEqual({ code: 'MACHINE_OFFLINE',- reason: 'MacBook Pro is offline, so it cannot show that its Harness Team account is private.' })- }+ expect(teamWorkRefusal(pool(reading('team', PASSED, NOW - 46_000)), NOW)).toEqual({ code: 'MACHINE_OFFLINE',+ reason: 'MacBook Pro is offline, so it cannot show that its Harness Team account is private.' })// A Mac's team account has its Mac's name, and the Mac may be online: the account is what is offline (third VM run).expect(teamWorkRefusal({ ...pool(), hostMachineId: 'mac' }, NOW, true)).toEqual({ code: 'MACHINE_OFFLINE',reason: 'The Harness Team account on MacBook Pro is offline, so it cannot show that it is private.' })@@ -390,18 +389,17 @@ describe('one machine: a Mac and its Harness Team account', () => {expect(f.state.starts).toEqual([expect.objectContaining({ request: expect.objectContaining({ machineId: 'mate-mac', cwd: '/swarm/lead' }) })])})- // 2026-10-28: every Mac read "has no Harness Team account yet" beside the account that took its teammates' work.- it('reads a Mac as its Harness Team account does, since that is where its teammates\' work runs', () => {+ // Swarm v3 (task #4218): a teammate's work on the Mac runs as its own person's agent there, never in its Team account, so the+ // Mac reads as itself: its Team account's privacy check no longer leaves its person's agents out of the route.+ it('reads a Mac as itself, not as its Harness Team account', () => {const f = oneMachine()f.machine('mate-mac').observation = reading('computer')- f.machine('mate-team').observation = reading('team', PASSED)- expect(machineTeamWork(f.state, f.machine('mate-mac'), NOW, ['mate-team'])).toBeNull()f.machine('mate-team').observation = reading('team', FAILED)- expect(machineTeamWork(f.state, f.machine('mate-mac'), NOW, ['mate-team'])?.code).toBe('PRIVACY_CHECK_FAILED')- expect(machineTeamWork(f.state, f.machine('mate-mac'), NOW, ['mate-team'], ['mate-team'])?.code).toBe('MACHINE_IN_OTHER_WORKSPACE')- // The account itself reads as itself; a Mac whose account is no longer signed in reads as a Mac without one.- expect(machineTeamWork(f.state, f.machine('mate-team'), NOW, ['mate-team'])?.code).toBe('PRIVACY_CHECK_FAILED')- expect(machineTeamWork(f.state, f.machine('mate-mac'), NOW, [])?.code).toBe('TEAM_ACCOUNT_REQUIRED')+ expect(machineTeamWork(f.machine('mate-mac'), NOW, ['mate-team'])).toBeNull()+ expect(machineTeamWork(f.machine('mate-mac'), NOW, ['mate-team'], ['mate-team'])).toBeNull()+ expect(machineTeamWork(f.machine('mate-mac'), NOW, [])).toBeNull()+ // The account itself reads as itself.+ expect(machineTeamWork(f.machine('mate-team'), NOW, ['mate-team'])?.code).toBe('PRIVACY_CHECK_FAILED')})it('takes nothing in its Team account, whether its account row is still listed or not', () => {@@ -410,7 +408,7 @@ describe('one machine: a Mac and its Harness Team account', () => {expect(refusal(() => f.run({ type: 'agent.start', request: { ...f.request(group, 'mate-team'), cwd: '/team-swarm/lead' } }, mate,{ ...f.pooled('mate-team'), teamMachines }))?.code).toBe('TEAM_ACCOUNTS_REMOVED')}- expect(machineTeamWork(f.state, f.machine('mate-team'), NOW, [])?.code).toBe('TEAM_ACCOUNT_REQUIRED')+ expect(machineTeamWork(f.machine('mate-team'), NOW, [])?.code).toBe('TEAM_ACCOUNT_REQUIRED')expect(f.state.starts ?? []).toEqual([])})@@ -518,8 +516,8 @@ describe('one machine: a Mac whose Harness Team account was made again', () => {describe('a Team machine serving more than one Workspace', () => {it('shows routing the reason, like any other refusal', () => {const f = swarm()- expect(teamWorkRefusal(f.machine('mate-team'), NOW, true, true, true)?.code).toBe('MACHINE_IN_OTHER_WORKSPACE')- expect(teamWorkRefusal(f.machine('mate-team'), NOW, true, true, false)).toBeNull()+ expect(teamWorkRefusal(f.machine('mate-team'), NOW, true, true)?.code).toBe('MACHINE_IN_OTHER_WORKSPACE')+ expect(teamWorkRefusal(f.machine('mate-team'), NOW, true, false)).toBeNull()})})@@ -542,14 +540,14 @@ describe('a machine added as its person joined', () => {expect(f.state.starts).toHaveLength(2)})- // Swarm v3 has no Team accounts (#4248, finding 8 of #4212): its reading no longer keeps routing off it for a teammate's- // project, so the route keeps its person's own agents; the pick itself is held to what its person reads (teamWorkCheck).- it('reads as taking teammates\' projects, as a machine contributed by hand does', () => {+ // Task #4218: it read "has no Harness Team account yet", and routing left its person's own agents out of every teammate's+ // project the server would let them work on.+ it('reads as taking its person\'s agents\' work, so routing keeps them for a teammate\'s project', () => {const f = swarm()f.run(joined, mate, contribution)f.machine('joined-mac').observation = reading('computer')- expect(machineTeamWork(f.state, f.machine('joined-mac'), NOW, [])).toBeNull()- expect(machineTeamWork(f.state, f.machine('mate-mac'), NOW, [])).toBeNull()+ expect(machineTeamWork(f.machine('joined-mac'), NOW, [])).toBeNull()+ expect(machineTeamWork(f.machine('mate-mac'), NOW, [])).toBeNull()})it('keeps the rule when its settings are saved again, which sends the contribution without it', () => {diff --git a/docs/plans/2026-11-07-regular-agent-routing-gaps-plan.md b/docs/plans/2026-11-07-regular-agent-routing-gaps-plan.mdnew file mode 100644index 000000000..3b46dc349--- /dev/null+++ b/docs/plans/2026-11-07-regular-agent-routing-gaps-plan.md@@ -0,0 +1,127 @@+# Routing gaps for Regular agents after Swarm v3: implementation plan++> Written by the project's Engineer way of working (project instructions, Engineer): plan first, then each task test first,+> the failing test committed before its code. No Execution Handoff.++**Goal:** fix the six gaps anh Dee's Buddy found in its code review of main 0413586e (task #4218, 2026-11-07), each verified+against main d1f33f5ca first. All six are real; none was dropped.++**Architecture:** six small fixes in backend/src/superTabs, one per finding:++1. **Read says Team-account rules on an own computer** (machines.ts teamWorkRefusal, the finding's routeCommand.ts:385). The Swarm+ read still gives `teamWork.allowed: false, TEAM_ACCOUNT_REQUIRED` for any machine without a Team session when the machine was+ added at join (`teamAccountOnly`) or `SWARM_TEAM_ACCOUNT_REQUIRED=1`. The CLI route turns that into `teammatesRefused` and+ leaves out every teammate's own agent there. The server's own check (teamWorkCheck, task #4120) allows that agent. Fix: a+ machine that is not a Team account reads no Team-account refusal. A Mac reads as itself, no longer as its Team account,+ whose privacy check left its person's own agents out the same way. The `required` parameter goes, and so does the+ "Team account joining" reading (#3122), which can no longer happen, with the database read behind it. Team account entries+ keep their reading until #4120's follow-up removes them.+2. **An assigned Regular agent gets no project code** (commands.ts assignTo, the finding's start.ts:428). A Regular agent starts+ in its own empty folder. Assigning it a task changes only its project membership, and the brief does not say where the code+ is. Fix: its task message names the project's code: the GitHub address to clone into its own folder with its person's own+ git, or the checkout on this computer to make a worktree of. When there is neither, it says so.+3. **Automatic picks skip idle Regular agents** (dispatch.ts freeCrew). freeCrew keeps only agents whose project is this one, and+ an idle Regular agent has none. A task the PM routed (pinned) to it is never handed over. The write-time check+ (store.ts) calls candidatesFor without the project's open tasks, so it also reads the Regular agent's empty project. Fix: an+ idle Regular agent is free crew of every project it may work in (projects.ts regularMayWorkIn, exported). candidatesFor takes+ the open tasks as a required argument, and the write-time check passes its project's. A second project's pick of an agent+ placed in the same pass is refused at write time (DISPATCH_STALE), bounded by DISPATCH_TRIES as any stale pick is.+4. **A closed Regular agent never returns** (closedAgents.ts). A closed session removes the agent. Its record is dropped+ because its own chat has an audience, so it counts as confidential. A restore would be refused anyway (`project-ended`) and+ would skip its chat. Fix: a Regular agent is not removed when its session closes, the same as a Buddy. It stays listed as+ closed, in its chat, and is back when its session runs again. Only its person's stop removes it.+5. **A rejection doesn't settle the proposal** (commands.ts task.reject, proposalCards.ts:206). task.reject writes only+ `taskApproval`. The proposal keeps no decision, so the PM is told it is overdue and can still accept it into a task that can+ never run. Fix: a rejection also records the proposal's decision as `no` with the reason, and clears its overdue mark.+6. **A pending approval strands after rejoin** (taskApproval.ts:40, commands.ts member.remove). Approval belongs to the+ requester's membership. When they leave, nobody can approve or reject it again and the task stays open forever. Fix: when a+ person leaves, every approval of theirs still in `proposal` is rejected ("Its requester left the Swarm."), settled as in 5,+ and its PM is told. A rejoined person gets no authority back (plan 2026-11-07-swarm-v3-approval-plan.md).++**Tech Stack:** TypeScript backend, vitest.++**Spec:** task #4218's brief; docs/specs/2026-11-07-swarm-v3.md; docs/plans/2026-11-07-regular-or-pm-agents-plan.md.++## Global Constraints++- Only backend/src/superTabs. No CLI or Desktop change.+- No code path reads a login or a secret. A Regular agent still works only where its person can read.+- One rejection path: task.reject and a leave share one helper.++## Design++- growth: no new records. A proposal's decision and a rejected approval are fields that exist already. A closed Regular agent stays+ listed until its person stops it, as a Buddy does (bounded by the Swarm's agent limit).+- concurrency: the Swarm's usual single write per command.+- read cost: unchanged. freeCrew reads the loaded state; regularMayWorkIn is one people lookup and one project read per agent.+- scale: 10x agents are 10x freeCrew rows per project pass, inside the existing per-agent cost. The dispatch pass time warns first.+- compatibility: backend only. Older clients read the same fields. An older CLI route reads the corrected `teamWork`.+- migration and rollback: none. Rolled back, the gaps return; no data needs undoing.+- audience: unchanged. The server enforces it (teamWorkCheck, regularMayWorkIn, authorizeTaskApproval).+- identity: a Regular agent clones with its own person's git on their own computer, never the machine owner's.+- failure: a Regular agent with no reachable code is told so in its task message.+- platforms: backend (Linux in CI).++## Review Focus++- That 1 only drops Team-account refusals of machines that are not Team accounts, and that teamWorkCheck still enforces access.+- That 3 never hands a Regular agent work in a project its person cannot read, or outside its private project.+- That 4 leaves the stop path (agent.release stop, agent.remove) removing a Regular agent as before.++## Tasks++### Task 1: own computers read no Team-account refusal++**Files:** backend/src/superTabs/machines.ts, store.ts, read/views.ts, read/service.ts, and the tests teamRouting, ownAccountWork,+computerMoves.++**Interfaces:** `teamWorkRefusal(pool, now, teamRow, otherWorkspace)` (no `required`); `machineTeamWork(pool, now, teamMachines,+otherWorkspaceMachines)` (no state, no joining list); `joiningTeamMacs` and `store.joiningTeams` removed.++- [ ] Change the tests that pinned the pre-v3 rule to the v3 one: a machine with no Team session (added at join, or under+ `SWARM_TEAM_ACCOUNT_REQUIRED=1`) reads `teamWork` allowed. Watch them fail.+- [ ] Drop the `required` and `teamAccountOnly` refusal in teamWorkRefusal; watch them pass.++### Task 2: a Regular agent's task names its project's code++**Files:** backend/src/superTabs/commands.ts, backend/src/superTabs/regularAssign.test.ts++- [ ] Test: Ada assigned a task in a project with a GitHub address; the task message names it. A project checked out on Ada's+ computer names that folder. One with neither says the code is not reachable. Watch it fail.+- [ ] Add the line in assignTo for `worker.regular`; watch it pass.++### Task 3: dispatch hands work to idle Regular agents++**Files:** backend/src/superTabs/dispatch.ts, backend/src/superTabs/projects.ts, backend/src/superTabs/store.ts,+backend/src/superTabs/regularAssign.test.ts++**Interfaces:** `regularMayWorkIn` exported from projects.ts.++- [ ] Test: a task pinned to idle Ada is in dispatchPlan for its project; not for a project Ada's person cannot read. Watch it fail.+- [ ] freeCrew takes idle Regular agents that may work in the project; the write-time check passes the project's open tasks.+ Watch it pass.++### Task 4: a closed Regular agent stays and returns++**Files:** backend/src/superTabs/closedAgents.ts, backend/src/superTabs/regularAssign.test.ts++- [ ] Test: Ada's session proved stopped past STOPPED_REMOVE_MS is not in closedAgents, so she stays in her chat. Watch it fail.+- [ ] `removable` leaves out Regular agents; watch it pass.++### Task 5: a rejection settles its proposal++**Files:** backend/src/superTabs/taskApproval.ts, backend/src/superTabs/commands.ts, backend/src/superTabs/taskApproval.test.ts++**Interfaces:** `rejectTaskApproval(group, reason, by, now)` in taskApproval.ts.++- [ ] Test: a Review-mode proposal rejected by its person; `proposal.decide accept` is refused PROPOSAL_DECIDED and the proposal+ has decision `no`. Watch it fail.+- [ ] task.reject goes through rejectTaskApproval; watch it pass.++### Task 6: a leave settles the person's pending approvals++**Files:** backend/src/superTabs/commands.ts, backend/src/superTabs/taskApproval.test.ts++- [ ] Test: the requester leaves with a task awaiting their approval; it is rejected with the reason and its PM is told. Watch it+ fail.+- [ ] member.remove rejects them through rejectTaskApproval; watch it pass.