Skip to content

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.

Merge batch 11-06 train-0739: #3322 (#3382)

harness-for-autonomous[bot]6e18ffcee728
diff --git a/backend/integration/crewDispatch.test.ts b/backend/integration/crewDispatch.test.ts
index 193499384..b12bd20c1 100644
--- a/backend/integration/crewDispatch.test.ts
+++ b/backend/integration/crewDispatch.test.ts
@@ -3,11 +3,14 @@ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
import type { MongoMemoryReplSet } from 'mongodb-memory-server-core'
import type { Prisma, PrismaClient } from '@prisma/client'
import type { AuthUser } from '../src/lib/ssoAuth.js'
+import { SEED_RULES, type ProjectRules } from '../src/superTabs/policy.js'
import { DISPATCH_RETRY_MS, SuperTabStore } from '../src/superTabs/store.js'
import { noteChange, swarmTransaction } from '../src/superTabs/cache.js'
import type { Command } from '../src/superTabs/commands.js'
import type { Agent, Conversation } from '../src/superTabs/model.js'
import { planDatabase } from './plans.test-support.js'
+import { poolRows } from './hostRows.test-support.js'
+import { logger } from '../src/utils/logger.js'
// The Swarm hands the next task to a free crew member by itself (task #3400). A fresh loopback replica set; never DATABASE_URL.
let replica: MongoMemoryReplSet
@@ -83,6 +86,177 @@ async function readGroup(tabId: string, groupId: string): Promise<Conversation>
}
describe('the crew dispatch pass', () => {
+ const save = (s: Awaited<ReturnType<typeof swarm>>, revision: number, change: Partial<ProjectRules>) => s.execute({
+ type: 'rules.set', projectId: 'lead', baseRevision: revision, rules: { ...structuredClone(SEED_RULES), ...change }, summary: 'Project dispatch policy',
+ })
+
+ /** Two projects, so a broken lead policy cannot hide a healthy project's work. */
+ async function twoProjects() {
+ const s = await swarm({ Ash: 'backend' }, { Api: 'backend/a.ts' })
+ const other = String((await s.execute({ type: 'project.create', name: 'Phone', visibility: 'public', brief: '' })).result.projectId)
+ const head = (await db.swarmHead.findUniqueOrThrow({ where: { tabId_key: { tabId: s.tab, key: 'head' } } })).data as unknown as { projects: { id: string; leadConversationId: string }[] }
+ const chat = head.projects.find(p => p.id === other)!.leadConversationId
+ await s.execute({ type: 'agent.add', conversationId: chat, machineId: 'owner-mac', harnessId: randomUUID(), name: 'Phone PM', configuration: config, lead: true })
+ const worker = String((await s.execute({ type: 'agent.add', conversationId: chat, machineId: 'owner-mac', harnessId: randomUUID(), name: 'Phone worker', configuration: config, lead: false })).result.agentId)
+ await s.execute({ type: 'crew.add', agentId: worker, lane: 'mobile', role: 'Engineer' })
+ const phone = String((await s.execute({ type: 'conversation.create', projectId: other, title: 'Phone', checks: [], task: { goal: 'Phone.', changes: 'Change.', constraints: 'None.', owns: ['mobile/a.dart'] } })).result.conversationId)
+ const fast = { ...structuredClone(SEED_RULES), dispatch: { ...SEED_RULES.dispatch, nudgeAfterMs: 60_000, returnAfterMs: 120_000 } }
+ await save(s, 0, fast)
+ await s.execute({ type: 'rules.set', projectId: other, baseRevision: 0, rules: fast, summary: 'Fast phone clock' })
+ const corrupt = () => db.superTabProjectRules.updateMany({ where: { tabId: s.tab, projectId: 'lead' }, data: { rules: { ...fast, dispatch: { ...fast.dispatch, maxHanded: 0 } } } })
+ return { ...s, other, worker, phone, corrupt }
+ }
+
+ it('isolates invalid project rules from another project’s dispatch', async () => {
+ const s = await twoProjects()
+ await s.corrupt()
+ const errors = vi.spyOn(logger, 'error')
+ try {
+ expect(await s.store.dispatchCrew(s.tab)).toMatchObject({ assigned: 1 })
+ expect((await readGroup(s.tab, s.tasks.Api!)).assignment).toBeNull()
+ expect((await readGroup(s.tab, s.phone)).assignment?.agentId).toBe(s.worker)
+ expect(errors.mock.calls).toContainEqual([expect.any(String), expect.anything(), expect.objectContaining({ tabId: s.tab, projectId: 'lead' })])
+ } finally { errors.mockRestore() }
+ })
+
+ it('keeps host reports and the lead sweep working when one project’s rules are invalid', async () => {
+ const s = await twoProjects()
+ await s.execute({ type: 'machine.contribute', machineId: 'owner-mac', name: 'Mac', cwd: '/repo', engines: ['claude'], maxAgents: 8 })
+ await s.execute({ type: 'work.assign', conversationId: s.tasks.Api!, agentId: s.crew.Ash! })
+ await s.execute({ type: 'work.assign', conversationId: s.phone, agentId: s.worker })
+ const pool = (await poolRows(s.store, owner, 'owner-mac')).find(p => p.tabId === s.tab)!.machine
+ const agents = (await db.swarmAgent.findMany({ where: { tabId: s.tab } })).map(row => row.data as unknown as Agent)
+ await s.corrupt()
+ s.advance(60_000)
+ const report = () => s.store.observeMachine(owner, s.tab, 'owner-mac', { generation: pool.generation, resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9, diskFreeBytes: 120e9, diskTotalBytes: 500e9, projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Fixture', os: 'macOS', gpuPercent: null }, quotas: [], tools: {},
+ runningHarnessIds: agents.map(a => a.harnessId), stoppedHarnessIds: [] })
+ await report()
+ const messages = (await s.store.messages(owner, s.tab, s.phone, {}, s.worker)).messages
+ expect(messages.filter(m => (m.source as { kind?: string })?.kind === 'crew-nudge')).toHaveLength(1)
+ s.advance(3 * 3_600_000)
+ await report()
+ await s.store.runTimeChecks(s.tab)
+ expect((await readGroup(s.tab, s.phone)).assignment?.status).toBe('lost')
+ expect((await readGroup(s.tab, s.tasks.Api!)).assignment?.status).toBe('working')
+ expect((await readGroup(s.tab, s.tasks.Api!)).assignment?.nudgedAt).toBeUndefined()
+ })
+
+ it('lets a review step open under invalid rules but refuses new tasks with a repair instruction', async () => {
+ const s = await twoProjects()
+ await s.corrupt()
+ const step = await s.execute({ type: 'conversation.create', title: 'Review', brief: 'Review the change.', reviewOf: s.tasks.Api!, step: 'Review', checks: [] })
+ expect((await readGroup(s.tab, String(step.result.conversationId))).reviewOf).toBe(s.tasks.Api)
+ await expect(s.execute({ type: 'conversation.create', title: 'New task', brief: 'A new task.', checks: [] })).rejects.toMatchObject({
+ code: 'RULES_INVALID', message: expect.stringMatching(/lead.*repair.*rules/i),
+ })
+ })
+
+ it('uses custom lanes for crew, work.lane, stamps and dispatch while another project retains mobile', async () => {
+ const s = await swarm({ Ash: null }, { Board: 'devices/main.c' })
+ await save(s, 0, { lanes: [{ name: 'firmware', owns: ['devices/'] }] })
+ expect((await readGroup(s.tab, s.tasks.Board!)).handOutLane).toBe('firmware')
+ await s.execute({ type: 'crew.add', agentId: s.crew.Ash!, lane: 'Firmware', role: 'Engineer' })
+ await s.execute({ type: 'work.lane', conversationId: s.tasks.Board!, lane: 'FIRMWARE' })
+ expect((await readGroup(s.tab, s.tasks.Board!)).lane).toBe('firmware')
+ await expect(s.execute({ type: 'crew.add', agentId: s.crew.Ash!, lane: 'mobile' })).rejects.toMatchObject({ code: 'LANE_UNKNOWN' })
+ await expect(s.execute({ type: 'work.lane', conversationId: s.tasks.Board!, lane: 'mobile' })).rejects.toMatchObject({ code: 'LANE_UNKNOWN' })
+ expect(await s.store.dispatchCrew(s.tab)).toMatchObject({ assigned: 1 })
+ expect(await s.holders()).toEqual({ Board: 'Ash' })
+ const other = await swarm({ Birch: 'mobile' }, { Phone: 'mobile/lib/app.dart' })
+ expect(await other.store.dispatchCrew(other.tab)).toMatchObject({ assigned: 1 })
+ expect(await other.holders()).toEqual({ Phone: 'Birch' })
+ })
+
+ it('does not dispatch removed lanes even with old crew marks', async () => {
+ const s = await swarm({ Ash: 'mobile', Birch: null }, { Phone: 'mobile/lib/app.dart' })
+ await s.execute({ type: 'work.lane', conversationId: s.tasks.Phone!, lane: 'mobile' })
+ await save(s, 0, { lanes: [{ name: 'firmware', owns: ['devices/'] }] })
+ expect((await readGroup(s.tab, s.tasks.Phone!)).handOutLane).toBeNull()
+ expect(await s.store.dispatchCrew(s.tab)).toMatchObject({ assigned: 0 })
+ expect(await s.holders()).toEqual({ Phone: null })
+ })
+
+ it('rechecks project lane policy inside an automatic assignment', async () => {
+ const s = await swarm({ Ash: 'backend' }, { Api: 'backend/src/a.ts' })
+ const store = s.store as unknown as { pushOriginFor: (...args: unknown[]) => Promise<unknown> }
+ vi.spyOn(store, 'pushOriginFor').mockImplementationOnce(async () => {
+ await save(s, 0, { lanes: [] })
+ return undefined
+ })
+ expect(await s.store.dispatchCrew(s.tab)).toMatchObject({ assigned: 0, skipped: { DISPATCH_STALE: 1 } })
+ expect(await s.holders()).toEqual({ Api: null })
+ })
+
+ it('rechecks a reduced handed-work cap inside an automatic assignment', async () => {
+ const s = await swarm({ Ash: 'backend' }, { First: 'backend/src/a.ts', Next: 'backend/src/b.ts' })
+ await s.execute({ type: 'work.assign', conversationId: s.tasks.First!, agentId: s.crew.Ash! })
+ const id = (await readGroup(s.tab, s.tasks.First!)).assignment!.id
+ await s.execute({ type: 'work.status', conversationId: s.tasks.First!, assignmentId: id, status: 'review', result: 'Ready at abc1234.' }, s.crew.Ash)
+ const store = s.store as unknown as { pushOriginFor: (...args: unknown[]) => Promise<unknown> }
+ vi.spyOn(store, 'pushOriginFor').mockImplementationOnce(async () => {
+ await save(s, 0, { dispatch: { ...SEED_RULES.dispatch, maxHanded: 1 } })
+ return undefined
+ })
+ expect(await s.store.dispatchCrew(s.tab)).toMatchObject({ assigned: 0, skipped: { DISPATCH_STALE: 1 } })
+ expect(await s.holders()).toEqual({ First: 'Ash', Next: null })
+ })
+
+ it('honors periodic project cadence while direct work events bypass it', async () => {
+ const s = await swarm({ Ash: 'backend' }, { First: 'backend/a.ts', Next: 'backend/b.ts', Third: 'backend/c.ts' })
+ await save(s, 0, { dispatch: { ...SEED_RULES.dispatch, everyMs: 60_000 } })
+ expect(await s.store.dispatchCrew(s.tab, true)).toMatchObject({ assigned: 1 })
+ const first = (await readGroup(s.tab, s.tasks.First!)).assignment!.id
+ await s.execute({ type: 'work.status', conversationId: s.tasks.First!, assignmentId: first, status: 'review', result: 'Ready at abc1234.' }, s.crew.Ash)
+ s.advance(30_000)
+ expect(await s.store.dispatchCrew(s.tab, true)).toMatchObject({ assigned: 0 })
+ s.advance(30_000)
+ expect(await s.store.dispatchCrew(s.tab, true)).toMatchObject({ assigned: 1 })
+ const next = (await readGroup(s.tab, s.tasks.Next!)).assignment!.id
+ await s.execute({ type: 'work.status', conversationId: s.tasks.Next!, assignmentId: next, status: 'review', result: 'Ready at abc1234.' }, s.crew.Ash)
+ expect(await s.store.dispatchCrew(s.tab)).toMatchObject({ assigned: 1 })
+ expect(await s.holders()).toEqual({ First: 'Ash', Next: 'Ash', Third: 'Ash' })
+ })
+
+ it('upgrades a pending periodic pass when a work event arrives', async () => {
+ const s = await swarm({ Ash: 'backend' }, { First: 'backend/a.ts', Next: 'backend/b.ts' })
+ await save(s, 0, { dispatch: { ...SEED_RULES.dispatch, everyMs: 60_000 } })
+ const automatic = new SuperTabStore(db, () => NOW, null, { dispatch: true })
+ await automatic.dispatchCrew(s.tab, true)
+ const id = (await readGroup(s.tab, s.tasks.First!)).assignment!.id
+ await s.execute({ type: 'work.status', conversationId: s.tasks.First!, assignmentId: id, status: 'review', result: 'Ready at abc1234.' }, s.crew.Ash)
+ const schedule = automatic as unknown as { dispatchSoon(tabId: string, periodic: boolean): void }
+ const passes = vi.spyOn(automatic, 'dispatchCrew')
+ schedule.dispatchSoon(s.tab, true)
+ await vi.waitFor(() => expect(passes.mock.results.length).toBe(1), { timeout: 5_000, interval: 100 })
+ await passes.mock.results[0]!.value
+ expect((await readGroup(s.tab, s.tasks.Next!)).assignment).toBeNull()
+ schedule.dispatchSoon(s.tab, true)
+ await automatic.execute(owner, s.tab, { operationId: randomUUID(), command: { type: 'work.queue', conversationId: s.tasks.Next!, after: null } })
+ await vi.waitFor(async () => expect((await readGroup(s.tab, s.tasks.Next!)).assignment?.agentId).toBe(s.crew.Ash), { timeout: 5_000, interval: 100 })
+ })
+
+ it('uses each project’s progress clock without changing another project’s seed', async () => {
+ const s = await swarm({ Ash: 'backend' }, { Api: 'backend/a.ts' })
+ const other = String((await s.execute({ type: 'project.create', name: 'Phone', visibility: 'public', brief: '' })).result.projectId)
+ const projects = (await db.swarmHead.findUniqueOrThrow({ where: { tabId_key: { tabId: s.tab, key: 'head' } } })).data as unknown as { projects: { id: string; leadConversationId: string }[] }
+ const chat = projects.projects.find(p => p.id === other)!.leadConversationId
+ const mobile = String((await s.execute({ type: 'agent.add', conversationId: chat, machineId: 'owner-mac', harnessId: randomUUID(), name: 'Phone worker', configuration: config, lead: false })).result.agentId)
+ await s.execute({ type: 'crew.add', agentId: mobile, lane: 'mobile', role: 'Engineer' })
+ const phone = String((await s.execute({ type: 'conversation.create', projectId: other, title: 'Phone', checks: [], task: { goal: 'Phone.', changes: 'Change.', constraints: 'None.', owns: ['mobile/a.dart'] } })).result.conversationId)
+ await save(s, 0, { lanes: [{ name: 'firmware', owns: ['backend/'] }], dispatch: { ...SEED_RULES.dispatch, nudgeAfterMs: 60_000, returnAfterMs: 120_000 } })
+ await s.execute({ type: 'work.assign', conversationId: s.tasks.Api!, agentId: s.crew.Ash! })
+ await s.execute({ type: 'work.assign', conversationId: phone, agentId: mobile })
+ s.advance(60_000)
+ await s.store.runTimeChecks(s.tab)
+ const messages = (await s.store.messages(owner, s.tab, s.tasks.Api!, {}, s.crew.Ash)).messages
+ expect(messages.filter(m => (m.source as { kind?: string })?.kind === 'crew-nudge')).toHaveLength(1)
+ s.advance(60_000)
+ await s.store.runTimeChecks(s.tab)
+ expect((await readGroup(s.tab, s.tasks.Api!)).assignment?.status).toBe('lost')
+ expect((await readGroup(s.tab, phone)).assignment?.status).toBe('working')
+ expect((await readGroup(s.tab, phone)).handOutLane).toBe('mobile')
+ })
+
it('hands a free member its pinned task first, then its lane\'s top task, as the PM, through work.assign', async () => {
const s = await swarm({ Ash: 'backend', Birch: 'desktop' }, { Api: 'backend/src/a.ts', Store: 'backend/src/b.ts', Board: 'desktop/lib/c.dart' })
await editGroup(s.tab, s.tasks.Store!, group => ({ ...group, pin: { agentId: s.crew.Ash!, why: 'ci', at: NOW } }))
diff --git a/backend/integration/superTabProjectRules.test.ts b/backend/integration/superTabProjectRules.test.ts
index cba644312..78e77f886 100644
--- a/backend/integration/superTabProjectRules.test.ts
+++ b/backend/integration/superTabProjectRules.test.ts
@@ -103,7 +103,39 @@ describe('a project\'s rules record', () => {
const { tab } = await swarm()
expect(await currentRules(db, tab, 'lead')).toEqual({ revision: 0, rules: SEED_RULES })
await run(tab, set(0, rules('10:00')))
- expect(await currentRules(db, tab, 'lead')).toEqual({ revision: 1, rules: rules('10:00') })
+ const started = performance.now()
+ const entries = await profiled(db, async () => {
+ expect(await currentRules(db, tab, 'lead')).toEqual({ revision: 1, rules: rules('10:00') })
+ })
+ const read = reads(entries, 'SuperTabProjectRules', ['tabId', 'projectId'])
+ expect(read).toHaveLength(1)
+ expect(read[0]!.planSummary).toMatch(/IXSCAN/)
+ expect(read[0]!.docsExamined).toBeLessThanOrEqual(1)
+ console.info('project dispatch policy read', { elapsedMs: performance.now() - started, returned: read[0]!.nreturned, examined: read[0]!.docsExamined, plan: read[0]!.planSummary })
+ })
+
+ it('normalizes legacy stored dispatch policy and keeps new empty lanes explicit', async () => {
+ const { tab } = await swarm()
+ await run(tab, set(0, rules('10:00')))
+ const { dispatch: _unused, ...legacy } = rules('10:00')
+ await db.superTabProjectRules.updateMany({ where: { tabId: tab }, data: { rules: { ...legacy, lanes: [] } } })
+ expect((await currentRules(db, tab, 'lead')).rules.lanes.map(l => l.name)).toEqual(['backend', 'CLI', 'Desktop', 'mobile', 'docs'])
+ const loaded = (await get(owner, tab)).json().data
+ expect(loaded.rules.dispatch).toEqual({ everyMs: 30_000, maxHanded: 3, nudgeAfterMs: 7_200_000, returnAfterMs: 10_800_000 })
+ await run(tab, set(1, { ...rules('10:00'), lanes: [] }))
+ expect((await currentRules(db, tab, 'lead')).rules.lanes).toEqual([])
+ })
+
+ it('holds workers on invalid stored policy while a person can read and repair it', async () => {
+ const { tab } = await swarm()
+ await run(tab, set(0, rules('10:00')))
+ await db.superTabProjectRules.updateMany({ where: { tabId: tab }, data: { rules: { ...rules('10:00'), dispatch: { ...SEED_RULES.dispatch, maxHanded: 0 } } } })
+ await expect(currentRules(db, tab, 'lead')).rejects.toThrow(/does not pass the schema/)
+ const read = await get(owner, tab)
+ expect(read.statusCode).toBe(200)
+ expect(read.json().data.rules.dispatch.maxHanded).toBe(0)
+ await run(tab, set(1, rules('10:00')))
+ expect(await currentRules(db, tab, 'lead')).toEqual({ revision: 2, rules: rules('10:00') })
})
it('keeps one of two saves on the same revision, refusing the other', async () => {
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 2f6eef1fa..484a38fb3 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -8,7 +8,7 @@ import { admitByRoom, admitMachineStart, noRepositoryStart, failOwnAccountTeamEn
import { movableEntry } from './computerMoves.js'
import { agentDisplayName, assignAgentDisplayNames } from './agentNames.js'
import { addedAgentName, renameAgentTo } from './agentRename.js'
-import { addCrew, CREW_LANES, CREW_ROLE_MAX, removeCrew } from './crew.js'
+import { addCrew, CREW_ROLE_MAX, removeCrew } from './crew.js'
import { noteIndex } from './processNotes.js'
import { keepUsernames, setUsername, swarmUsernames, usernameOf } from './usernames.js'
import { agentWrittenNameOf, setName, shownNameOf } from './personNames.js'
@@ -82,7 +82,7 @@ import { contractRefusal, missingContract } from './taskContract.js'
import { DEFAULT_PRIORITY, PRIORITY_DEFAULTED, TASK_PRIORITIES, priorityLine, proposalPriority, titlePriority, type TaskPriority } from './taskPriority.js'
import { placeAfter, queueSiblings } from './taskQueue.js'
import { inThread, leadsGroup, recordAnswered, requireUnanswered } from './answers.js'
-import { DISPATCH_RULES, laneNamed, pinBuilder, spokenList, stampLane } from './dispatch.js'
+import { laneNamed, pinBuilder, spokenList, stampLane } from './dispatch.js'
const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
/** The most steps a task lists (Conversation.stepIds): production's most was 14 (2026-11-05). */
@@ -380,7 +380,7 @@ export const commandSchema = z.discriminatedUnion('type', [
// Rename Harness on the agent's Mac renames the agent for every reader (task #2912); the contributor or machine owner only.
z.object({ type: z.literal('agent.rename'), agentId: id, name: z.string().max(200) }).strict(),
z.object({ type: z.literal('agent.release'), agentId: id, decision: z.enum(['keep', 'stop']) }).strict(),
- z.object({ type: z.literal('crew.add'), agentId: id, role: z.string().trim().min(1).max(CREW_ROLE_MAX).regex(/^[^\x00-\x1f\x7f]+$/).optional(), lane: z.enum(CREW_LANES).optional() }).strict(),
+ z.object({ type: z.literal('crew.add'), agentId: id, role: z.string().trim().min(1).max(CREW_ROLE_MAX).regex(/^[^\x00-\x1f\x7f]+$/).optional(), lane: z.string().trim().min(1).max(80).regex(/^[^\x00-\x1f\x7f]+$/).optional() }).strict(),
z.object({ type: z.literal('crew.remove'), agentId: id }).strict(),
z.object({ type: z.literal('agent.sessionClosed'), agentId: id, harnessId: id }).strict(),
z.object({ type: z.literal('agent.configuration'), previousVersion: id.nullable(), configuration }).strict(),
@@ -2153,6 +2153,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
const revision = current.revision + 1
effects.projectRules = { projectId: project.id, revision, rules: command.rules, diff: rulesDiff(current.rules, command.rules),
summary: command.summary, writtenBy: { kind: sender.kind, id: sender.id }, askedBy, askedIn, at: context.now }
+ for (const group of state.conversations) if (!group.kind && !group.audience && !group.reviewOf
+ && (group.projectId ?? 'lead') === project.id) stampLane(group, command.rules.lanes)
Object.assign(result, { projectId: project.id, revision })
break
}
@@ -2631,7 +2633,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
assignment: null, lastMessageSequence: 0, codePullRequestUrls: [],
checks: storedChecks(command.checks, operationId),
})
- stampLane(state.conversations.at(-1)!)
+ stampLane(state.conversations.at(-1)!, (context.projectRules?.rules ?? SEED_RULES).lanes)
recordAsked(state.conversations.at(-1)!, requesterId, context.now)
if (command.reviewOf) listStep(conversation(state, command.reviewOf), operationId)
// The reason stands only where nobody is named, and is shown in the task's first row beside its goal.
@@ -2727,9 +2729,9 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
fail('LANE_TASK_ONLY', 'Only a task has a lane: name a task, not a chat or a step.', 400)
}
if (command.lane === null) delete task.lane
- else task.lane = laneNamed(DISPATCH_RULES.lanes, command.lane)
- ?? fail('LANE_UNKNOWN', `Name a lane: ${spokenList(DISPATCH_RULES.lanes.map(l => l.name))}.`, 400)
- stampLane(task)
+ else task.lane = laneNamed((context.projectRules?.rules ?? SEED_RULES).lanes, command.lane)
+ ?? fail('LANE_UNKNOWN', `Name a lane: ${spokenList((context.projectRules?.rules ?? SEED_RULES).lanes.map(l => l.name))}.`, 400)
+ stampLane(task, (context.projectRules?.rules ?? SEED_RULES).lanes)
break
}
case 'work.priority': {
@@ -3616,7 +3618,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
renameAgentTo(state, actor, agent(state, command.agentId), command.name)
break
case 'crew.add':
- addCrew(state, actor, agent(state, command.agentId), command.role, command.lane, context.now)
+ addCrew(state, actor, agent(state, command.agentId), command.role, command.lane, context.now, (context.projectRules?.rules ?? SEED_RULES).lanes)
break
case 'crew.remove':
removeCrew(state, actor, agent(state, command.agentId))
@@ -4092,7 +4094,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
if (command.task) group.task = command.task
else delete group.task
group.briefAt = context.now
- stampLane(group)
+ stampLane(group, (context.projectRules?.rules ?? SEED_RULES).lanes)
group.checks = storedChecks(command.checks, operationId)
message(group.id, group.brief, [], null, SYSTEM_ROW)
bindTaskCard(group, effects.messages.at(-1)!)
diff --git a/backend/src/superTabs/crew.test.ts b/backend/src/superTabs/crew.test.ts
index 42b49d1a2..beb9cedbf 100644
--- a/backend/src/superTabs/crew.test.ts
+++ b/backend/src/superTabs/crew.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'
import { applyCommand, commandSchema, type Command, type CommandContext } from './commands.js'
import { createSuperTab, visibleState, type Actor, type AgentConfiguration } from './model.js'
+import { SEED_RULES } from './policy.js'
import { isCrew } from './crew.js'
import { projectsOf } from './projects.js'
@@ -73,7 +74,16 @@ describe('crew.add and crew.remove', () => {
f.run({ type: 'crew.add', agentId: f.worker, role: 'Engineer' }, f.agentActor(f.pm))
expect(f.target().crew).toEqual({ role: 'Engineer', at: 5000, by: f.pm })
for (const lane of ['backend', 'cli', 'desktop', 'mobile', 'docs']) expect(commandSchema.safeParse({ type: 'crew.add', agentId: 'a1', lane }).success).toBe(true)
- for (const lane of ['', 'web', 'Backend']) expect([lane, commandSchema.safeParse({ type: 'crew.add', agentId: 'a1', lane }).success]).toEqual([lane, false])
+ for (const lane of ['']) expect([lane, commandSchema.safeParse({ type: 'crew.add', agentId: 'a1', lane }).success]).toEqual([lane, false])
+ })
+
+ it('accepts custom project lanes in any case and refuses a removed seeded lane', () => {
+ const f = fixture()
+ const projectRules = { revision: 1, rules: { ...structuredClone(SEED_RULES), lanes: [{ name: 'firmware', owns: ['devices/'] }] } }
+ f.run({ type: 'crew.add', agentId: f.worker, lane: 'Firmware' }, owner, { projectRules })
+ expect(f.target().crew?.lane).toBe('firmware')
+ expect(() => f.run({ type: 'crew.add', agentId: f.worker, lane: 'mobile' }, owner, { projectRules }))
+ .toThrow(expect.objectContaining({ code: 'LANE_UNKNOWN' }))
})
// River for security review 1 of #3222 (the Swarm goes public): of the people, only the Swarm's or the project's owner,
diff --git a/backend/src/superTabs/crew.ts b/backend/src/superTabs/crew.ts
index 45e6dc49c..f74086763 100644
--- a/backend/src/superTabs/crew.ts
+++ b/backend/src/superTabs/crew.ts
@@ -6,6 +6,7 @@
*
* The numbers here stay in this one place until the project rules record lands (sibling task of #3397).
*/
+import { DISPATCH_RULES, laneNamed, spokenList, type Lane } from './dispatch.js'
import { isBuddy } from './buddies.js'
import { roleNameOf } from './instructions.js'
import { fail, type Actor, type Agent, type SuperTabState } from './model.js'
@@ -15,11 +16,6 @@ import { agentProjectId, canReadProject, ledProject, ownsProject, projectOf } fr
export const CREW_REOPEN_GRACE_MS = 5 * 60_000
/** The longest role a crew entry names, in characters. */
export const CREW_ROLE_MAX = 40
-/** The lanes a crew member may work in: automatic assignment gives it its lane's top task, and one with no lane the
- * project's (River for Budget, 11-05). */
-export const CREW_LANES = ['backend', 'cli', 'desktop', 'mobile', 'docs'] as const
-export type CrewLane = typeof CREW_LANES[number]
-
export const isCrew = (target: Pick<Agent, 'crew'>): boolean => !!target.crew
/** Who may change [target]'s crew mark: its project's PM, or, of the people who read the project and are no viewer, the
@@ -36,10 +32,11 @@ function mayManageCrew(state: SuperTabState, actor: Actor, target: Agent): void
/** `crew.add`: marks [target] as crew, with [role] or the role it goes by, and its [lane] if any. Again on crew replaces it.
* Never the PM (kept alive already) nor a Buddy. */
-export function addCrew(state: SuperTabState, actor: Actor, target: Agent, role: string | undefined, lane: CrewLane | undefined, now: number): void {
+export function addCrew(state: SuperTabState, actor: Actor, target: Agent, role: string | undefined, lane: string | undefined, now: number, lanes: readonly Lane[] = DISPATCH_RULES.lanes): void {
mayManageCrew(state, actor, target)
if (isBuddy(target)) fail('CREW_BUDDY', 'A Buddy waits for its person; it is never crew.')
if (ledProject(state, target.id)) fail('CREW_LEAD', 'The PM is already kept alive; it needs no crew mark.')
+ if (lane) lane = (laneNamed(lanes, lane) ?? fail('LANE_UNKNOWN', `Name a lane: ${spokenList(lanes.map(l => l.name))}.`, 400)).toLowerCase()
target.crew = { role: role ?? roleNameOf(state, target).slice(0, CREW_ROLE_MAX), ...lane ? { lane } : {}, at: now, by: actor.kind === 'agent' ? actor.agentId : actor.userId }
}
diff --git a/backend/src/superTabs/dispatch.test.ts b/backend/src/superTabs/dispatch.test.ts
index f94a01c61..ec762178f 100644
--- a/backend/src/superTabs/dispatch.test.ts
+++ b/backend/src/superTabs/dispatch.test.ts
@@ -247,15 +247,26 @@ describe('the crew\'s clocks: 2 hours without progress tells the member, 3 hours
const api = s.task('Api', ['backend/src/a.ts'])
s.run({ type: 'work.assign', conversationId: api, agentId: s.ids.Ash! }, s.as(s.pm))
/** The liveness sweep at [now], with the machine reporting every session running and busy on screen till then. */
- const sweep = (now: number) => {
+ const sweep = (now: number, rules = DISPATCH_RULES) => {
s.state.machines = [{ machineId: 'host', name: 'Mac', observation: { runningHarnessIds: s.state.agents.map(a => a.harnessId),
stoppedHarnessIds: [], receivedAt: now, harnessProgress: Object.fromEntries(s.state.agents.map(a => [a.harnessId, now])) } }] as never
- return sweepLiveness(s.state, now)
+ return sweepLiveness(s.state, now, () => rules)
}
const lines = (rows: MessageDraft[]) => rows.filter(r => r.conversationId === api && r.recipients.includes(s.ids.Ash!)).map(r => r.text)
return { ...s, api, sweep, lines, get state() { return s.state } }
}
+ it('uses a project’s own progress thresholds and names them in notices', () => {
+ const s = working()
+ const rules = { ...DISPATCH_RULES, nudgeAfterMs: 60_000, returnAfterMs: 120_000 }
+ expect(s.lines(s.sweep(AT + 59_999, rules))).toEqual([])
+ expect(s.lines(s.sweep(AT + 60_000, rules))).toEqual([
+ 'No progress on this task for 1 minute. Post where it stands, or set it blocked with why; at 2 minutes it goes back to the backend lane.',
+ ])
+ s.sweep(AT + 120_000, rules)
+ expect(s.group(s.api).assignment).toMatchObject({ status: 'lost', lost: { reason: 'no progress for 2 minutes: back in the backend lane' } })
+ })
+
it.each([true, false])('tells the worker once at 2 hours, reset only after progress (crew: %s)', crew => {
const s = working(crew)
expect(s.lines(s.sweep(AT + 2 * HOUR - 60_000))).toEqual([])
diff --git a/backend/src/superTabs/dispatch.ts b/backend/src/superTabs/dispatch.ts
index e92ed4123..d30ada063 100644
--- a/backend/src/superTabs/dispatch.ts
+++ b/backend/src/superTabs/dispatch.ts
@@ -4,6 +4,7 @@
* each free member gets, the two clocks and the capacity line. The store's pass (store.ts dispatchCrew) sends each pick
* through work.assign, whose own write refuses a second assignment.
*/
+import { SEED_RULES, type ProjectRules } from './policy.js'
import { isBuddy } from './buddies.js'
import { sessionClosed } from './closedAgents.js'
import { activeWork, handed, occupiesAgent, type Agent, type Assignment, type Conversation, type SuperTabState } from './model.js'
@@ -23,25 +24,12 @@ const HOUR_MS = 3_600_000
/** A lane of work and the repository paths it owns: the project rules record's `lanes` entry (#3393), the same shape. */
export interface Lane { name: string; owns: readonly string[] }
-/** The numbers of the dispatch, in one place until the project rules record (#3393) holds them. */
-export const DISPATCH_RULES = Object.freeze({
- /** How often the worker's pass runs; commits that free a member or open a task run it at once too. */
- everyMs: 30_000,
- /** A member with this many handed tasks (ready for review, still its own) takes no new one. */
- maxHanded: 3,
- /** Without progress this long, the member is told once. */
- nudgeAfterMs: 2 * HOUR_MS,
- /** Without progress this long, the task goes back to its lane. */
- returnAfterMs: 3 * HOUR_MS,
- lanes: Object.freeze([
- { name: 'backend', owns: ['backend/'] },
- { name: 'CLI', owns: ['cli/'] },
- { name: 'Desktop', owns: ['desktop/'] },
- { name: 'mobile', owns: ['mobile/'] },
- { name: 'docs', owns: ['docs/'] },
- ] as readonly Lane[]),
-})
-export type DispatchRules = typeof DISPATCH_RULES
+/** The validated dispatch policy of one project; the default is only for legacy pure callers. */
+export interface DispatchRules extends Readonly<ProjectRules['dispatch']> { readonly lanes: readonly Lane[] }
+export const dispatchRules = (rules: ProjectRules): DispatchRules => ({ ...rules.dispatch, lanes: rules.lanes })
+/** Null holds only this project's configurable clocks and dispatch until its rules can be repaired/read. */
+export type DispatchLookup = (projectId: string) => DispatchRules | null
+export const DISPATCH_RULES: DispatchRules = Object.freeze(dispatchRules(SEED_RULES))
/** The lane [name] means, matched in any case, as the table writes it; undefined when the table has none by that name. */
export function laneNamed(lanes: readonly Lane[], name: string): string | undefined {
@@ -50,8 +38,8 @@ export function laneNamed(lanes: readonly Lane[], name: string): string | undefi
/** Stores [group]'s hand-out lane, when it is a task (not a chat, a step or a private chat), after its paths or lane changed:
* readers copy it (read/views.ts groupView), no read computes it. */
-export function stampLane(group: Conversation): void {
- if (group.task && !group.reviewOf && !group.kind && !group.audience) group.handOutLane = laneOf(group, DISPATCH_RULES.lanes)
+export function stampLane(group: Conversation, lanes: readonly Lane[] = DISPATCH_RULES.lanes): void {
+ if (group.task && !group.reviewOf && !group.kind && !group.audience) group.handOutLane = laneOf(group, lanes)
else delete group.handOutLane
}
@@ -69,7 +57,7 @@ const under = (path: string, area: string): boolean => {
/** The lane [group]'s task is handed out in: the one its PM or a person set (work.lane), else the lane owning most of its
* owned paths, a tie going to the table's first; null when no lane owns any of them. */
export function laneOf(group: Pick<Conversation, 'lane' | 'task'>, lanes: readonly Lane[]): string | null {
- if (group.lane) return laneNamed(lanes, group.lane) ?? group.lane
+ if (group.lane) return laneNamed(lanes, group.lane) ?? null
let best: string | null = null, most = 0
for (const lane of lanes) {
const count = (group.task?.owns ?? []).filter(path => lane.owns.some(area => under(path.replace(/^\.?\//, ''), area))).length
@@ -78,13 +66,16 @@ export function laneOf(group: Pick<Conversation, 'lane' | 'task'>, lanes: readon
return best
}
-/** The reason the 3-hour clock gives a task it puts back in its lane (liveness.ts); the dispatch reads it to keep that task
- * from its last member for one pass. */
-export const returnReason = (lane: string | null): string => `no progress for 3 hours: back in the ${lane ?? 'project'} lane`
+/** Configured time in a progress notice, without rounding a project's threshold. */
+const duration = (ms: number): string => {
+ const [value, unit] = ms % HOUR_MS === 0 ? [ms / HOUR_MS, 'hour'] : ms % 60_000 === 0 ? [ms / 60_000, 'minute'] : [ms / 1000, 'second']
+ return `${value} ${unit}${value === 1 ? '' : 's'}`
+}
+export const returnReason = (lane: string | null, rules: DispatchRules = DISPATCH_RULES): string =>
+ `no progress for ${duration(rules.returnAfterMs)}: back in the ${lane ?? 'project'} lane`
-/** What a worker hears after 2 hours without progress on its task. */
-export const nudgeLine = (lane: string | null): string =>
- `No progress on this task for 2 hours. Post where it stands, or set it blocked with why; at 3 hours it goes back to the ${lane ?? 'project'} lane.`
+export const nudgeLine = (lane: string | null, rules: DispatchRules = DISPATCH_RULES): string =>
+ `No progress on this task for ${duration(rules.nudgeAfterMs)}. Post where it stands, or set it blocked with why; at ${duration(rules.returnAfterMs)} it goes back to the ${lane ?? 'project'} lane.`
/** The progress clocks on [assignment] of [group], held by any project worker (liveness.ts): from its own last progress
* (its assignment, status, check or post: `progressAt`), only while working. `nudge` after `nudgeAfterMs`, once
@@ -173,7 +164,7 @@ export function candidatesFor(state: SuperTabState, member: Agent, rules: Dispat
const head = latest ? task.pullRequestHeads?.[latest]?.head ?? null : null
return reviewerCandidates(state, task, kind, head, now).some(a => a.id === member.id)
})
- const lane = open.filter(g => !g.reviewOf && !pinned.includes(g) && !(pinOf(g) && members.has(pinOf(g)!.agentId)) && !lostByIt(g)
+ const lane = open.filter(g => (!g.lane || !!laneNamed(rules.lanes, g.lane)) && !g.reviewOf && !pinned.includes(g) && !(pinOf(g) && members.has(pinOf(g)!.agentId)) && !lostByIt(g)
// Ordinary workers recover work; new tasks still need the PM's route or a standing crew lane.
&& (member.crew || (g.assignment?.status === 'lost' && g.lostAttempt))
&& acceptsLane(laneOf(g, rules.lanes)))
diff --git a/backend/src/superTabs/liveness.ts b/backend/src/superTabs/liveness.ts
index 0c1719833..c7d65f1ce 100644
--- a/backend/src/superTabs/liveness.ts
+++ b/backend/src/superTabs/liveness.ts
@@ -16,7 +16,7 @@ import { coordinatorNameOf } from './instructions.js'
import { waitedOn } from './leaderboard/record.js'
import { isStep } from './steps.js'
import { endedReply } from './taskLine.js'
-import { crewClock, DISPATCH_RULES, laneOf, nudgeLine, returnReason } from './dispatch.js'
+import { crewClock, DISPATCH_RULES, laneOf, nudgeLine, returnReason, type DispatchLookup } from './dispatch.js'
import { handed, pickUp, unclaimedAt, unclaimedReason } from './handed.js'
import { isBuddy } from './buddies.js'
@@ -332,7 +332,7 @@ export function unavailableReason(state: SuperTabState, worker: Agent, now: numb
}
/** Why a worker has lost its task now, or null while it still holds it. */
-function lostReason(state: SuperTabState, group: Conversation, worker: Agent, assignment: Assignment, now: number, steps: StepIndex): string | null {
+function lostReason(state: SuperTabState, group: Conversation, worker: Agent, assignment: Assignment, now: number, steps: StepIndex, rulesFor: DispatchLookup): string | null {
// A handed task waits on its Reviewers and CI, not on its Engineer, which may be down or at work elsewhere (task #3399).
if (handed(group)) return null
// A crew member its host is reopening keeps its task for the reopen's grace (crew.ts).
@@ -343,7 +343,9 @@ function lostReason(state: SuperTabState, group: Conversation, worker: Agent, as
if (unclaimed) return unclaimed
if (waitingForReview(assignment) || waitingForRevision(state, group) || waitingOnSteps(state, group, steps) || waitingOnPerson(state, group, worker, assignment)) return null
// A crew member 3 hours without progress of its own puts its task back in its lane (task #3400), however busy its screen.
- if (crewClock(group, worker, assignment, now, DISPATCH_RULES) === 'return') return returnReason(laneOf(group, DISPATCH_RULES.lanes))
+ const rules = rulesFor(group.projectId ?? 'lead')
+ if (!rules) return null
+ if (crewClock(group, worker, assignment, now, rules) === 'return') return returnReason(laneOf(group, rules.lanes), rules)
const end = leaseEnd(group, assignment, reportRenewedAt(state, worker))
if (end !== undefined && now > end) {
const progress = lastProgress(state, worker, assignment)
@@ -382,12 +384,15 @@ function loseTask(state: SuperTabState, group: Conversation, worker: Agent, reas
}
/** Every worker 2 hours without progress hears it once in its task, without waiting for the PM (dispatch.ts crewClock). */
-function crewNudges(state: SuperTabState, now: number): MessageDraft[] {
+function crewNudges(state: SuperTabState, now: number, rulesFor: DispatchLookup): MessageDraft[] {
const workers = new Map(state.agents.filter(a => !isBuddy(a)).map(a => [a.id, a]))
let leaders: Set<string> | undefined, steps: StepIndex | undefined
return state.conversations.flatMap(group => {
const assignment = group.assignment, worker = assignment && workers.get(assignment.agentId)
- if (!worker || !activeWork(group) || crewClock(group, worker, assignment, now, DISPATCH_RULES) !== 'nudge') return []
+ if (!worker || !activeWork(group)) return []
+ const rules = rulesFor(group.projectId ?? 'lead')
+ if (!rules) return []
+ if (crewClock(group, worker, assignment, now, rules) !== 'nudge') return []
leaders ??= new Set(state.conversations.flatMap(c => c.leadId ? [c.leadId] : []))
if (leaders.has(worker.id)) return []
steps ??= stepIndex(state)
@@ -395,19 +400,19 @@ function crewNudges(state: SuperTabState, now: number): MessageDraft[] {
if (waitingForReview(assignment) || waitingForRevision(state, group) || waitingOnSteps(state, group, steps) || waitingOnPerson(state, group, worker, assignment)) return []
assignment.nudgedAt = now
return [reachable(state, { id: stableId('crew-nudge', assignment.id, String(now)), conversationId: group.id, author: writtenBy(state, leadOf(state, worker) ?? worker),
- replyTo: null, recipients: [worker.id], text: nudgeLine(laneOf(group, DISPATCH_RULES.lanes)), source: { kind: 'crew-nudge', assignmentId: assignment.id } })]
+ replyTo: null, recipients: [worker.id], text: nudgeLine(laneOf(group, rules.lanes), rules), source: { kind: 'crew-nudge', assignmentId: assignment.id } })]
})
}
/** Loses at once the tasks of the workers `which` picks that have a reason now: an agent that just reported a usage limit,
* the agents of a machine that just reported. A task lost to that limit resumes at `resumeAt` when its screen said when the
* limit resets (the host types into the same session then, cli superTabs/limitResume.ts). */
-export function loseTasks(state: SuperTabState, now: number, which: (worker: Agent) => boolean = () => true, resumeAt?: string): MessageDraft[] {
+export function loseTasks(state: SuperTabState, now: number, which: (worker: Agent) => boolean = () => true, resumeAt?: string, rulesFor: DispatchLookup = () => DISPATCH_RULES): MessageDraft[] {
const steps = stepIndex(state)
return workerTasks(state).filter(t => which(t.worker)).flatMap(({ group, assignment, worker }) => {
// A step that ended with no write to its task, or was lost earlier in this same pass, ends its Engineer's wait first.
stepsEnded(state, group, now, steps)
- const reason = lostReason(state, group, worker, assignment, now, steps)
+ const reason = lostReason(state, group, worker, assignment, now, steps, rulesFor)
return reason ? loseTask(state, group, worker, reason, now, resumeAt && reason === limitReason(worker, now) ? resumeAt : undefined) : []
})
}
@@ -446,8 +451,8 @@ function leadNotice(state: SuperTabState, start: AgentStart, text: string | null
/** The time checks, run on the Lead's poll and on any machine's report: every worker task with a reason is lost, and
* every start dispatched over 3 minutes ago that is not running fails, unless its machine is still preparing it. */
-export function sweepLiveness(state: SuperTabState, now: number): MessageDraft[] {
- const drafts = [...loseTasks(state, now), ...crewNudges(state, now), ...failStalledStarts(state, now), ...unpurged(state, now), ...staleSwitches(state, now), ...staleModelRequests(state, now)]
+export function sweepLiveness(state: SuperTabState, now: number, rulesFor: DispatchLookup = () => DISPATCH_RULES): MessageDraft[] {
+ const drafts = [...loseTasks(state, now, undefined, undefined, rulesFor), ...crewNudges(state, now, rulesFor), ...failStalledStarts(state, now), ...unpurged(state, now), ...staleSwitches(state, now), ...staleModelRequests(state, now)]
// A Buddy start that timed out may have been the last on its Buddy-only machine (security review 1 of #2234).
dropIdleBuddyMachines(state, now)
return drafts
@@ -481,8 +486,8 @@ function unpurged(state: SuperTabState, now: number): MessageDraft[] {
/** The Lead's own time checks: those above, then each task's state, waking the Lead for those that just stalled. Only the
* Lead's poll runs them, where the whole active Swarm is loaded and the one they wake is listening: a machine's reading
* loads only running work and must write no group (read/host.ts). */
-export function sweepForLead(state: SuperTabState, now: number): MessageDraft[] {
- const drafts = [...sweepLiveness(state, now), ...recordTaskStates(state, now)]
+export function sweepForLead(state: SuperTabState, now: number, rulesFor: DispatchLookup = () => DISPATCH_RULES): MessageDraft[] {
+ const drafts = [...sweepLiveness(state, now, rulesFor), ...recordTaskStates(state, now)]
// Where the whole active Swarm is loaded, as for a command: a task lost here may leave Working at 0 (pulse.ts).
recordPulse(state, now)
return drafts
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 43a883949..e036b2218 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -78,7 +78,7 @@ export interface Agent {
releaseId?: string
/** Set while it is one of its project's crew (crew.ts): its host keeps it alive, and no idle path closes or removes it.
* `by` is the person's or PM agent's id that marked it. */
- crew?: { role: string; lane?: 'backend' | 'cli' | 'desktop' | 'mobile' | 'docs'; at: number; by: string }
+ crew?: { role: string; lane?: string; at: number; by: string }
/** A person's request to move this Product Manager to another engine or account (lead.switch), carried out by its host.
* `id` is the operation that asked; `claimedUntil` is set once the host took it (agent.switchClaim). */
/** The switch request the last rebind settled, until its result arrives: that result is the one line the chat gets, and
diff --git a/backend/src/superTabs/policy.test.ts b/backend/src/superTabs/policy.test.ts
index 0d18d90a4..4982d8835 100644
--- a/backend/src/superTabs/policy.test.ts
+++ b/backend/src/superTabs/policy.test.ts
@@ -25,7 +25,38 @@ describe('the project rules record', () => {
'The phone app in a simulator', 'The web in a browser', 'Install and update on a Mac', 'Firmware on the device plugged into a machine'])
// The merge train is opt-in per project (River, #3402).
expect(SEED_RULES.mergeTrain).toEqual({ enabled: false, everyMinutes: 10 })
- expect(SEED_RULES).toMatchObject({ caps: [], paths: [], crew: [], lanes: [] })
+ expect(SEED_RULES).toMatchObject({ caps: [], paths: [], crew: [] })
+ })
+
+ it('seeds the current dispatch lanes and numbers and accepts project replacements', () => {
+ const seed = projectRulesSchema.parse(SEED_RULES)
+ expect(seed.lanes).toEqual([
+ { name: 'backend', owns: ['backend/'] }, { name: 'CLI', owns: ['cli/'] },
+ { name: 'Desktop', owns: ['desktop/'] }, { name: 'mobile', owns: ['mobile/'] }, { name: 'docs', owns: ['docs/'] },
+ ])
+ expect(seed.dispatch).toEqual({ everyMs: 30_000, maxHanded: 3, nudgeAfterMs: 7_200_000, returnAfterMs: 10_800_000 })
+ const custom = { ...copy(), lanes: [{ name: 'firmware', owns: ['devices/'] }],
+ dispatch: { everyMs: 60_000, maxHanded: 1, nudgeAfterMs: 60_000, returnAfterMs: 120_000 } }
+ expect(projectRulesSchema.parse(custom)).toEqual(custom)
+ })
+
+ it('normalizes legacy empty lanes but preserves a new deliberately empty list', () => {
+ const { dispatch: _old, ...legacy } = copy()
+ expect(projectRulesSchema.parse({ ...legacy, lanes: [] }).lanes.map(l => l.name)).toEqual(['backend', 'CLI', 'Desktop', 'mobile', 'docs'])
+ expect(projectRulesSchema.parse({ ...copy(), lanes: [] }).lanes).toEqual([])
+ const custom = projectRulesSchema.parse({ ...legacy, lanes: [{ name: 'firmware', owns: ['devices/'] }] })
+ expect(custom.lanes).toEqual([{ name: 'firmware', owns: ['devices/'] }])
+ expect(custom.dispatch).toEqual({ everyMs: 30_000, maxHanded: 3, nudgeAfterMs: 7_200_000, returnAfterMs: 10_800_000 })
+ })
+
+ it('refuses unsafe dispatch bounds and ambiguous lane names', () => {
+ for (const dispatch of [
+ { everyMs: 29_999 }, { everyMs: 3_600_001 }, { maxHanded: 0 }, { maxHanded: 1001 },
+ { maxHanded: 1.5 }, { nudgeAfterMs: 59_999 }, { nudgeAfterMs: 604_800_001 },
+ { returnAfterMs: 1_209_600_001 }, { nudgeAfterMs: 120_000, returnAfterMs: 120_000 },
+ ]) expect(refused({ ...copy(), dispatch: { ...copy().dispatch, ...dispatch } }), JSON.stringify(dispatch)).toBe(true)
+ expect(refused({ ...copy(), lanes: [{ name: 'firmware', owns: [] }, { name: 'Firmware', owns: [] }] })).toBe(true)
+ expect(refused({ ...copy(), lanes: [{ name: '', owns: [] }] })).toBe(true)
})
it('holds caps, paths, the crew and lanes', () => {
diff --git a/backend/src/superTabs/policy.ts b/backend/src/superTabs/policy.ts
index f87ad0102..7862e1d20 100644
--- a/backend/src/superTabs/policy.ts
+++ b/backend/src/superTabs/policy.ts
@@ -35,7 +35,28 @@ const globs = z.array(glob).max(MAX_LIST)
const distinct = <T extends z.ZodTypeAny>(item: T, key: (entry: z.infer<T>) => string, what: string) =>
z.array(item).max(MAX_LIST).refine(list => new Set(list.map(e => key(e).toLowerCase())).size === list.length, `Each ${what} once.`)
-export const projectRulesSchema = z.object({
+/** Defaults for projects predating configurable dispatch (#3601); kept here with the rest of the project policy. */
+export const SEED_DISPATCH = deepFreeze({ everyMs: 30_000, maxHanded: 3, nudgeAfterMs: 7_200_000, returnAfterMs: 10_800_000 })
+export const SEED_LANES = deepFreeze([
+ { name: 'backend', owns: ['backend/'] }, { name: 'CLI', owns: ['cli/'] },
+ { name: 'Desktop', owns: ['desktop/'] }, { name: 'mobile', owns: ['mobile/'] }, { name: 'docs', owns: ['docs/'] },
+])
+const dispatchSchema = z.object({
+ everyMs: z.number().int().min(30_000).max(3_600_000),
+ maxHanded: z.number().int().min(1).max(1000),
+ nudgeAfterMs: z.number().int().min(60_000).max(604_800_000),
+ returnAfterMs: z.number().int().max(1_209_600_000),
+}).strict().refine(d => d.returnAfterMs > d.nudgeAfterMs, 'Return time is later than the nudge.')
+
+/** Old clients and stored revisions have no dispatch section; their unused empty lane table meant the fixed five lanes.
+ * An explicit dispatch section makes an empty list deliberate. No backfill or mutation of a saved revision. */
+const legacyDispatch = (value: unknown): unknown => {
+ if (!value || typeof value !== 'object' || Array.isArray(value) || 'dispatch' in value) return value
+ const old = value as Record<string, unknown>
+ return { ...old, dispatch: SEED_DISPATCH, ...Array.isArray(old.lanes) && old.lanes.length === 0 ? { lanes: SEED_LANES } : {} }
+}
+
+export const projectRulesSchema = z.preprocess(legacyDispatch, z.object({
/** When releases go out, in a local time of day; the end comes after the start, the same day. */
releaseWindow: z.object({ start: clock, end: clock, timeZone }).strict()
.refine(w => w.start < w.end, 'The release window ends after it starts, the same day.'),
@@ -60,6 +81,8 @@ export const projectRulesSchema = z.object({
paths: distinct(z.object({ name: line(80), path: line(400) }).strict(), entry => entry.name, 'path name'),
/** The crew roster: each role and who fills it. */
crew: distinct(z.object({ role: line(40), names: z.array(line(80)).max(20) }).strict(), entry => entry.role, 'role'),
+ /** Periodic dispatch cadence, handed-work cap and progress clocks. */
+ dispatch: dispatchSchema,
/** Lanes of work and the paths each owns. */
lanes: distinct(z.object({ name: line(80), owns: z.array(line(400)).max(MAX_LIST) }).strict(), lane => lane.name, 'lane'),
}).strict().refine(rules => Buffer.byteLength(JSON.stringify(rules)) <= MAX_RULES_BYTES,
@@ -68,7 +91,7 @@ export const projectRulesSchema = z.object({
.refine(rules => {
const pause = rules.releasePace.backendPause
return !pause || (pause.start >= rules.releaseWindow.start && pause.end <= rules.releaseWindow.end)
- }, 'The backend pause falls inside the release window.')
+ }, 'The backend pause falls inside the release window.'))
export type ProjectRules = z.infer<typeof projectRulesSchema>
@@ -138,7 +161,8 @@ export const SEED_RULES: ProjectRules = deepFreeze({
caps: [],
paths: [],
crew: [],
- lanes: [],
+ lanes: SEED_LANES,
+ dispatch: SEED_DISPATCH,
})
/** One change a save made: a leaf of an object section, or a whole list. */
diff --git a/backend/src/superTabs/policyStore.ts b/backend/src/superTabs/policyStore.ts
index 6e00149ca..0bd80f88e 100644
--- a/backend/src/superTabs/policyStore.ts
+++ b/backend/src/superTabs/policyStore.ts
@@ -3,7 +3,7 @@
* Every filter is an equality or a range on the indexed fields (tabId, projectId, revision): never `in` (hotFilters.test.ts).
*/
import type { Prisma } from '@prisma/client'
-import { stableId } from './model.js'
+import { fail, stableId } from './model.js'
import { MAX_RULES_REVISIONS, projectRulesSchema, SEED_RULES, type ProjectRules, type RulesChange, type RulesWrite } from './policy.js'
type Transaction = Prisma.TransactionClient
@@ -22,30 +22,33 @@ export interface RulesRevision {
at: Date
}
-/** The project's newest revision, or null when none is saved (the seed, revision 0). One indexed read. */
-export async function readRules(tx: Transaction, tabId: string, projectId: string): Promise<{ revision: number; rules: ProjectRules } | null> {
+/** The project's newest revision, or null when none is saved (the seed, revision 0). One indexed read.
+ * forEdit lets a rules save repair an invalid record; workers always require a valid one. */
+export async function readRules(tx: Transaction, tabId: string, projectId: string, forEdit = false): Promise<{ revision: number; rules: ProjectRules } | null> {
const row = await tx.superTabProjectRules.findFirst({ where: { tabId, projectId }, orderBy: { revision: 'desc' }, select: { revision: true, rules: true } })
- return row && { revision: row.revision, rules: row.rules as unknown as ProjectRules }
+ if (!row) return null
+ // Normalize legacy dispatch; only the repair path may read an invalid saved record.
+ const parsed = projectRulesSchema.safeParse(row.rules)
+ if (!parsed.success && !forEdit) fail('RULES_INVALID', `Project ${projectId} rules revision ${row.revision} does not pass the schema; repair the project rules by saving them again.`, 409)
+ return { revision: row.revision, rules: parsed.success ? parsed.data : row.rules as unknown as ProjectRules }
}
/** The record a project runs on now, for a server worker (the merge train, the release schedule): its newest revision, or
* the seed at revision 0. Takes the client or a transaction. */
export async function currentRules(tx: Transaction, tabId: string, projectId: string): Promise<{ revision: number; rules: ProjectRules }> {
- const saved = await readRules(tx, tabId, projectId)
- if (!saved) return { revision: 0, rules: SEED_RULES }
- // Checked again on the way out (SecAlder, review of #3250): a stored row the schema refuses (one with no read count, a
- // pattern from a looser past schema) would read as fewer reads. It throws, and the caller holds: never a partial record.
- const parsed = projectRulesSchema.safeParse(saved.rules)
- if (!parsed.success) throw new Error(`project rules revision ${saved.revision} does not pass the schema; save the rules again`)
- return { revision: saved.revision, rules: parsed.data }
+ return await readRules(tx, tabId, projectId) ?? { revision: 0, rules: SEED_RULES }
}
-/** Every kept revision, newest first: at most MAX_RULES_REVISIONS rows of the same index. */
+/** Every kept revision, newest first: at most MAX_RULES_REVISIONS rows of the same index.
+ * Invalid history stays readable for repair; no worker runs on it. */
export async function readRulesHistory(tx: Transaction, tabId: string, projectId: string): Promise<RulesRevision[]> {
const rows = await tx.superTabProjectRules.findMany({ where: { tabId, projectId }, orderBy: { revision: 'desc' }, take: MAX_RULES_REVISIONS })
- return rows.map(row => ({ revision: row.revision, rules: row.rules as unknown as ProjectRules, diff: row.diff as unknown as RulesChange[],
- summary: row.summary, writtenBy: { kind: row.writtenByKind, id: row.writtenBy }, askedBy: row.askedBy,
- askedIn: (row.askedIn ?? null) as RulesRevision['askedIn'], at: row.at }))
+ return rows.map(row => {
+ const parsed = projectRulesSchema.safeParse(row.rules)
+ return { revision: row.revision, rules: parsed.success ? parsed.data : row.rules as unknown as ProjectRules, diff: row.diff as unknown as RulesChange[],
+ summary: row.summary, writtenBy: { kind: row.writtenByKind, id: row.writtenBy }, askedBy: row.askedBy,
+ askedIn: (row.askedIn ?? null) as RulesRevision['askedIn'], at: row.at }
+ })
}
/** The new revision, created (never upserted: a second writer of the same revision meets the taken key and retries into
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 736875de2..860a7face 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -74,7 +74,7 @@ import { closedAgents, nextRemovalAt, removeClosedAgents, reopened, restoreRefus
import { sessionRows } from './memberRows.js'
import { RefusalMemory } from './dispatchRefusals.js'
import { tasksHoldingMoves } from './ruleGuard.js'
-import { candidatesFor, DISPATCH_RULES, dispatchPlan, freeCrew, laneCapacity, openTasks, pinBuilder, pullRequestPin, roundOf, type Skip } from './dispatch.js'
+import { candidatesFor, dispatchRules, DISPATCH_RULES, dispatchPlan, freeCrew, laneCapacity, openTasks, pinBuilder, pullRequestPin, roundOf, type DispatchLookup, type DispatchRules, type Skip } from './dispatch.js'
import { failRefusedStarts, judgedMachines, loseTasks, nextLossAt, recordTaskState, sweepForLead, sweepLiveness, SWEEP_EVERY_MS, unpurgedNotice } from './liveness.js'
import { endedReply, taskLineChats } from './taskLine.js'
import { owedAsk } from './timeChecks.js'
@@ -177,7 +177,7 @@ export const MAX_MERGE_READS = 20
/** The writes after which the crew dispatch runs (store.ts dispatchSoon): those that may free a member or open a task. A
* status only when it hands the task over or ends it; a progress note, the Swarm's most frequent write, frees nobody. */
const DISPATCH_TRIGGERS: ReadonlySet<string> = new Set(['work.cancel', 'conversation.create', 'work.define', 'work.priority',
- 'work.queue', 'work.lane', 'agent.release', 'crew.add'])
+ 'work.queue', 'work.lane', 'agent.release', 'crew.add', 'rules.set'])
const FREEING_STATUSES: ReadonlySet<string> = new Set(['done', 'review', 'stopped'])
const freesOrOpens = (command: Command): boolean =>
command.type === 'work.status' ? FREEING_STATUSES.has(command.status) : DISPATCH_TRIGGERS.has(command.type)
@@ -1925,7 +1925,15 @@ export class SuperTabStore {
}
if (command.type === 'note.add' || command.type === 'note.remove') context.notes = await readNotes(tx, tabId, command.projectId)
// A stale rules save is refused with the newest revision, to merge (policy.ts); null is the seed.
- if (command.type === 'rules.set') context.projectRules = await readRules(tx, tabId, command.projectId)
+ if (command.type === 'rules.set') context.projectRules = await readRules(tx, tabId, command.projectId, true)
+ if (command.type === 'crew.add' || command.type === 'work.lane' || command.type === 'work.define'
+ || (command.type === 'conversation.create' && !command.reviewOf && !command.audience)) {
+ authorizeCommandAccess(original, actor, command)
+ const projectId = command.type === 'crew.add' ? agentProjectId(original, agent(original, command.agentId))!
+ : command.type === 'conversation.create' ? readProject(original, actor, command.projectId ?? (actor.kind === 'agent' ? agentProjectId(original, agent(original, actor.agentId))! : 'lead')).id
+ : groupProject(original, conversation(original, command.conversationId)).id
+ context.projectRules = await currentRules(tx, tabId, projectId)
+ }
if ((command.type === 'rule.set' || command.type === 'rule.remove' || command.type === 'project.skills' || command.type === 'tab.tidy'
|| command.type === 'machine.engineResume' || command.type === 'machine.projects' || command.type === 'machine.ownAccountWork'
|| command.type === 'machine.access' || command.type === 'rules.set') && command.askedIn) {
@@ -2453,8 +2461,9 @@ export class SuperTabStore {
// The pick as this write's state has it: the worker still free, the task still its candidate (open, its
// day come, its lane or pin, not the one it just lost). What moved since the pass read is refused, and the next pass decides.
const assigned = command.type === 'work.assign' ? command.agentId : undefined
- const now = this.now(), member = freeCrew(state, project.id, DISPATCH_RULES, now).find(a => a.id === assigned)
- if (!member || !candidatesFor(state, member, DISPATCH_RULES, now).some(c => c.group.id === task.id)) {
+ const 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)) {
fail('DISPATCH_STALE', 'This task is no longer one to hand out to this member.', 409)
}
try {
@@ -2483,18 +2492,60 @@ export class SuperTabStore {
return !!leadId && this.waitingPms.refused(`${tabId}:${leadId}`, now)
}
- private readonly dispatchWaiting = new Map<string, ReturnType<typeof setTimeout>>()
+ // One last pass per project, bounded and expired after the schema's longest cadence (one hour).
+ private readonly dispatchTimes = new Map<string, number>()
+ private periodicDue(tabId: string, projectId: string, rules: DispatchRules, now: number): boolean {
+ const last = this.dispatchTimes.get(`${tabId}:${projectId}`)
+ return last === undefined || now >= last + rules.everyMs
+ }
+ private rememberDispatch(tabId: string, projectId: string, now: number): void {
+ for (const [key, at] of this.dispatchTimes) if (now - at >= 3_600_000) this.dispatchTimes.delete(key)
+ const key = `${tabId}:${projectId}`
+ this.dispatchTimes.delete(key)
+ while (this.dispatchTimes.size >= DISPATCH_REFUSALS_HELD) this.dispatchTimes.delete(this.dispatchTimes.keys().next().value!)
+ this.dispatchTimes.set(key, now)
+ }
+
+ /** A broken/unreadable policy holds its project only; never run it on seed defaults. */
+ private async dispatchPolicy(tx: Transaction, tabId: string, projectId: string): Promise<DispatchRules | null> {
+ try { return dispatchRules((await currentRules(tx, tabId, projectId)).rules) }
+ catch (error) {
+ logger.error('[swarm-dispatch] project policy unavailable; clocks and dispatch held until rules are repaired or readable',
+ error, { tabId, projectId })
+ return null
+ }
+ }
+
+ /** One indexed policy read per relevant project, reused by this pass's clocks and dispatch check. */
+ private async projectDispatch(tx: Transaction, state: SuperTabState, machineId?: string, dispatch = false): Promise<DispatchLookup> {
+ const workers = machineId ? new Set(state.agents.filter(a => a.machineId === machineId).map(a => a.id)) : null
+ const ids = new Set(state.conversations.filter(c => activeWork(c) && c.assignment && (!workers || workers.has(c.assignment.agentId)))
+ .map(c => groupProject(state, c).id))
+ if (dispatch) {
+ const pms = new Set(state.conversations.flatMap(c => c.leadId ? [c.leadId] : []))
+ for (const worker of state.agents) {
+ const projectId = !pms.has(worker.id) && !isBuddy(worker) && agentProjectId(state, worker)
+ if (projectId) ids.add(projectId)
+ }
+ }
+ const policies = new Map(await Promise.all([...ids].map(async id => [id, await this.dispatchPolicy(tx, state.id, id)] as const)))
+ return id => policies.has(id) ? policies.get(id)! : DISPATCH_RULES
+ }
+
+ private readonly dispatchWaiting = new Map<string, { timer: ReturnType<typeof setTimeout>; periodic: boolean }>()
/** Whether a write scheduled a dispatch pass for [tabId] that has not run yet (dispatchSoon). */
dispatchScheduled(tabId: string): boolean { return this.dispatchWaiting.has(tabId) }
- /** Runs the crew dispatch for [tabId] a second from now, once however many writes asked: on servers whose hooks turn it on. */
- private dispatchSoon(tabId: string): void {
- if (!this.hooks.dispatch || this.dispatchWaiting.has(tabId)) return
- const timer = setTimeout(() => {
+ /** Debounces on the existing host sweep; any work event upgrades a waiting periodic pass to immediate. */
+ private dispatchSoon(tabId: string, periodic = false): void {
+ if (!this.hooks.dispatch) return
+ const waiting = this.dispatchWaiting.get(tabId)
+ if (waiting) { waiting.periodic &&= periodic; return }
+ const pending = { periodic, timer: setTimeout(() => {
this.dispatchWaiting.delete(tabId)
- this.dispatchCrew(tabId).catch(error => logger.warn('[swarm-dispatch] pass failed', { tabId, error: error instanceof Error ? error.message : String(error) }))
- }, DISPATCH_DEBOUNCE_MS)
- timer.unref?.()
- this.dispatchWaiting.set(tabId, timer)
+ this.dispatchCrew(tabId, pending.periodic).catch(error => logger.warn('[swarm-dispatch] pass failed', { tabId, error: error instanceof Error ? error.message : String(error) }))
+ }, DISPATCH_DEBOUNCE_MS) }
+ pending.timer.unref?.()
+ this.dispatchWaiting.set(tabId, pending)
}
/**
@@ -2505,18 +2556,22 @@ export class SuperTabStore {
* replay one receipt or collide, and never assign twice. A refused pick is counted by code and the member's next task tried,
* up to DISPATCH_TRIES. A project with no PM, or no free crew, is left alone.
*/
- async dispatchCrew(tabId: string): Promise<{ assigned: number; skipped: Record<string, number> }> {
+ async dispatchCrew(tabId: string, periodic = false): Promise<{ assigned: number; skipped: Record<string, number> }> {
const out = { assigned: 0, skipped: {} as Record<string, number> }, started = performance.now()
const load: Record<string, { waiting: number; busy: number }> = {}
const skipCode = (code: string) => { out.skipped[code] = (out.skipped[code] ?? 0) + 1 }
const row = await this.db.superTab.findUnique({ where: { id: tabId }, select: { ...SWARM_ROW, autonomousEnv: true } })
if (!row || row.deletedAt || row.format !== 2) return out
const { state } = await loadRow(this.db, row)
- const now = this.now(), rules = DISPATCH_RULES
+ const now = this.now()
if (state.paused) return out
this.refusedPicks.prune(now)
this.waitingPms.prune(now)
projects: for (const project of projectsOf(state)) {
+ const rules = await this.dispatchPolicy(this.db, tabId, project.id)
+ if (!rules) { skipCode('RULES_INVALID'); continue }
+ if (periodic && !this.periodicDue(tabId, project.id, rules, now)) continue
+ this.rememberDispatch(tabId, project.id, now)
if (this.pmWaiting(tabId, state, project, now)) continue
const free = freeCrew(state, project.id, rules, now)
if (!free.length) continue
@@ -4274,14 +4329,18 @@ export class SuperTabStore {
// The Team facts are read only when a member needs another machine (review of #3229); sleeps and folders need none.
const crew = sweep && state.agents.some(isCrew)
? crewNeedsMachine(state, now) ? await this.crewDeps(tx, state, now) : { admits: () => false } : null
- const checked = [...failRefusedStarts(state, machineId, now), ...loseTasks(state, now, worker => worker.machineId === machineId),
- ...sweep ? sweepLiveness(state, now) : [], ...crew ? applyCrewKeep(state, now, crew) : [],
+ const rulesFor = await this.projectDispatch(tx, state, sweep ? undefined : machineId, !!sweep && !!this.hooks.dispatch)
+ const checked = [...failRefusedStarts(state, machineId, now), ...loseTasks(state, now, worker => worker.machineId === machineId, undefined, rulesFor),
+ ...sweep ? sweepLiveness(state, now, rulesFor) : [], ...crew ? applyCrewKeep(state, now, crew) : [],
// A woken crew member this reading shows running again: its wake's timing row (crewTimes.ts, task #3462).
...finishedWakes(state, now)]
// The 30-second sweep also hands out work when the Swarm, as loaded here, has a free crew member and a task for it.
- if (sweep && this.hooks.dispatch && projectsOf(state).some(p => !this.pmWaiting(tabId, state, p, now)
- && dispatchPlan(state, p.id, DISPATCH_RULES, now, this.refusedSkip(tabId, state, now)).length)) {
- afterCommit(tx, () => this.dispatchSoon(tabId))
+ if (sweep && this.hooks.dispatch && projectsOf(state).some(p => {
+ const rules = rulesFor(p.id)
+ return rules && !this.pmWaiting(tabId, state, p, now) && this.periodicDue(tabId, p.id, rules, now)
+ && dispatchPlan(state, p.id, rules, now, this.refusedSkip(tabId, state, now)).length
+ })) {
+ afterCommit(tx, () => this.dispatchSoon(tabId, true))
}
// Then the agents it shows closed leave, those with no active work left: the Lead is told of their tasks above (closedAgents.ts).
const closedOut = removeClosedAgents(state, state.agents.filter(a => closed.includes(a.id)), now).map(a => a.id)
@@ -5267,7 +5326,8 @@ export class SuperTabStore {
const chats = taskLineChats(loaded.state)
if (chats.length) loaded = await this.ensure(tx, loaded, { groupIds: chats })
const state = cloneData(loaded.state), now = this.now()
- const written = sweepForLead(state, now)
+ const rulesFor = await this.projectDispatch(tx, state)
+ const written = sweepForLead(state, now, rulesFor)
// What waits for each agent: an agent with a delivery open is not idle. Only loaded groups' active work keeps an agent
// from being idle (project instructions, phase 4).
const projects = projectsOf(state).filter(p => state.conversations.find(c => c.id === p.leadConversationId)?.leadId)
diff --git a/docs/plans/2026-11-06-project-crew-lanes-plan.md b/docs/plans/2026-11-06-project-crew-lanes-plan.md
new file mode 100644
index 000000000..c4cd76d56
--- /dev/null
+++ b/docs/plans/2026-11-06-project-crew-lanes-plan.md
@@ -0,0 +1,84 @@
+# Project crew lanes implementation plan
+
+> Implement task by task in this session, test first, followed by the required independent review.
+
+**Goal:** Let each project choose its crew lanes and dispatch numbers in its existing rules record.
+
+**Architecture:** Make policy.ts the source of seeded lanes and dispatch numbers. Existing indexed policy reads supply rules to command validation, task lane stamps, dispatch picks and liveness clocks; no policy transcript enters prompts or client state. Background dispatch honors each project's cadence, while work-change events still dispatch immediately.
+
+**Tech Stack:** Existing TypeScript, Zod, Prisma/MongoDB and Vitest; no dependency, collection or index.
+
+**Spec:** Task #3601; Dee 11-06: projects have different crews, including projects without mobile and projects with firmware.
+
+## Global Constraints
+
+- Seed lanes, in order: backend (backend/), CLI (cli/), Desktop (desktop/), mobile (mobile/), docs (docs/).
+- Seed dispatch: everyMs 30000, maxHanded 3, nudgeAfterMs 7200000, returnAfterMs 10800000.
+- crew.add and work.lane validate names case-insensitively against the target project's lanes; an empty new lane list disables named lanes. Existing access and Team boundaries hold.
+- Legacy records missing dispatch numbers gain seed numbers; legacy empty unused lane tables retain the old five-lane behavior. New records explicitly storing dispatch and an empty list keep it empty. No production backfill.
+- Commit failing tests before each implementation. Run affected checks only locally; full backend unit and integration suites belong to ready PR CI.
+- No real CLI sign-out, production writes, process-name stops or cli/src/core changes. Temporary files only in mktemp folders.
+
+## Design
+
+- **Growth:** Reuse the 16 KiB policy record and its 50-revision retention. Four scalar numbers and the existing bounded lane list; no new persistent state. Background cadence memory is bounded and expires.
+- **Concurrency:** Existing rules-revision transaction serializes saves. Automatic work.assign rereads the policy inside its assignment transaction, so a changed lane/cap cannot use a stale outside pick. A rules save refreshes loaded task lane stamps atomically with its record.
+- **Read cost:** Existing newest-policy index (tabId/projectId/revision), no query shape/index change. Rare lane/crew/task-definition commands read one project's policy. Worker clock passes read relevant project policies once per pass (at most 100 projects); pure functions consume that lookup. No read computes lane labels from a global fixed table after a new stamp.
+- **Scale:** Lists remain capped at 50 lanes/50 owned paths and 100 projects per Swarm. Validate bounds and measure indexed policy reads on loopback. The required read-only production environment is absent on this Team machine; production count/size/growth measurements are unavailable.
+- **Compatibility:** Lane strings remain strings; crew's existing lowercase values keep working. Missing additive dispatch fields normalize to today's behavior. Old clients may still submit their old record shape; no new mandatory wire field.
+- **Migration/rollback:** No schema migration or backfill; normalize old JSON on read/save. Rollback ignores numbers; old code resumes its fixed lanes. Saved custom lanes remain in the record for re-upgrade.
+- **Audience/identity:** Preserve rules-save ownership/person-message checks and crew/work access checks. Rules cannot cross project/account boundaries. Invalid saved policy fails visibly rather than silently dispatching with defaults.
+- **Failures/platforms:** Named unknown-lane refusals list that project's choices. Configured numbers appear in nudge/return text. Background cadence is checked on the existing 30-second host sweep (minimum 30 seconds); no new polling timer. Shared backend behavior for all platforms.
+
+## Review Focus
+
+- A second project must not inherit another project's lanes or dispatch numbers (Tasks 1/2).
+- Removing a lane must prevent both new crew marks and work.lane, including case variants; old marks cannot keep receiving removed-lane work (Task 2).
+- A lane/cap changed between planning and assignment must invalidate the pick (Task 2).
+- Legacy empty lane records must keep their old behavior while a new explicit empty list stays empty (Task 1).
+- Custom nudge/return times and periodic cadence must be used consistently; real waits and event-triggered dispatch retain their behavior (Task 3).
+
+### Task 1: Seed and normalize project dispatch policy
+
+**Files:** policy.ts, policyStore.ts, policy.test.ts; focused project-rules integration.
+**Interfaces:** ProjectRules.dispatch {everyMs, maxHanded, nudgeAfterMs, returnAfterMs}; existing lanes list. Bounds: everyMs 30000–3600000, maxHanded 1–1000, nudgeAfterMs 60000–604800000, returnAfterMs at most 1209600000 and greater than nudgeAfterMs. Missing dispatch uses seed values.
+
+- [x] Commit tests for exact seed behavior, custom firmware/no-mobile lists, duplicate/invalid names and invalid clock/cap ranges; old missing dispatch with empty lanes versus new explicit empty list.
+- [x] Run affected policy tests and see missing seed/numbers failures.
+- [x] Add schema/defaults and normalized indexed policy reads; keep history readable and size bounds intact.
+- [x] Run policy tests and focused rules persistence/index integration, commit and push.
+
+### Task 2: Validate and dispatch using each project's lanes
+
+**Files:** dispatch.ts, crew.ts, model.ts, commands.ts, store.ts, read/views.ts; crew/dispatch tests and integration/crewDispatch.test.ts.
+**Interfaces:** DispatchRules is the numeric policy plus lanes; stampLane(group, lanes), addCrew accepts string lanes validated against passed policy. CommandContext.projectRules carries the target project's current record. Store assignment revalidation reads currentRules in the transaction.
+
+- [x] Commit command/store regressions: firmware lane works and dispatches; removed mobile refused on crew.add and work.lane; other project keeps seeded mobile; stale lane/cap pick refused; rules saves update labels.
+- [x] Watch expected failures in affected tests.
+- [x] Replace global enum validation with project validation; read the policy for relevant commands, stamping and dispatch; preserve crew lowercase compatibility and all access checks.
+- [x] Run changed/importer tests, transactional dispatch integration and typecheck; commit and push.
+
+### Task 3: Use project clocks and periodic cadence
+
+**Files:** liveness.ts, dispatch.ts, store.ts; liveness/dispatch tests and integration/crewDispatch.test.ts.
+**Interfaces:** DispatchLookup(projectId) returns the pass's validated DispatchRules; liveness entrypoints accept it with seeded defaults for pure callers. dispatchCrew(tabId, periodic=false) applies bounded per-project cadence only on periodic passes. Debounced event requests upgrade a pending periodic pass to immediate.
+
+- [x] Commit tests for custom nudge/return thresholds and wording, two projects with different clocks, configured periodic interval, and event requests bypassing/upgrading periodic gating.
+- [x] Run focused tests and confirm fixed-number behavior fails.
+- [x] Load project policy once per pass, thread the lookup through clock decisions, and use bounded expiry memory for periodic dispatch; no extra timer.
+- [x] Run affected unit/integration/typecheck and query-plan checks. Record limits, red/green and timings; mark ready for CI and independent review.
+
+## Evidence
+
+- Task 1 red: `6f5666e84` fails 2 policy tests (25 pass) and the focused stored-legacy integration. Green: all 27 policy tests and all 6 project-rules integrations pass, including the existing indexed history query and explicit empty list. Backend typecheck clean. No new query/index or backfill.
+- Task 2 red: `deb068ac8` fails the custom crew test (8 pass) and all four new dispatch integrations (14 unrelated skipped). Green: 74 policy/crew/dispatch unit tests, 604 affected importer unit tests across seven files, all 18 crew-dispatch integrations and backend typecheck pass. Custom firmware, no mobile, updated stamps, old marks, and lane/cap changes between planning and transaction are covered.
+- Task 3 red: `1126bfd03` fails custom clock unit behavior (38 pass), both initial clock/cadence integrations, and the strengthened scheduled-pass case. Green: all 21 dispatch integrations, 99 dispatch/liveness tests and backend typecheck pass; commands remained green (427 tests). The two-project test keeps the other project’s seeded mobile lane and clock. The policy read uses IXSCAN and examines at most one row; the existing history plan stays indexed. Periodic cadence memory is per process, capped at 5000 project entries and pruned after an hour; existing work events upgrade pending periodic passes.
+- Self-review repair regression: `f6f7d01ef` fails when invalid stored rules make history unreadable. The fix keeps invalid records visible to the authorized repair path, while every worker and dispatch read still fails closed. All 7 project-rules integrations and typecheck pass; existing access checks precede the new command policy reads.
+
+### Review repair: isolate invalid policies and keep non-task paths independent
+
+- [x] Reproduce CI's saved-rules review-step failure: restamping tried to resolve the Swarm Buddy chat as a project. Restrict restamping to project work; the existing failing integration now passes (`90040faa7`).
+- [x] Commit/observe invalid-policy regressions before the isolation fix (`0e576e2d3`, fixture correction `41a0091b0`): dispatch, host reports and step creation each fail on the malformed saved record.
+- [x] Catch policy failures per project, log the tab/project, and hold its clocks/dispatch without seed fallback. Real host/session-loss checks still run. Resolve task creation's policy through the same project access lookup as its command; steps and private-chat requests do not read policy. Invalid task policy gets RULES_INVALID with a repair instruction.
+- [x] Verify the healthy project's dispatch, host nudge and timeout work while the broken project's clocks remain held beyond three hours. A review step still opens, and new work is refused visibly.
+- [x] Green: 35 affected real-store integrations (crewDispatch, superTabProjectRules, superTabReviewSteps); 553 dispatch/liveness/commands/policy unit tests; backend typecheck. Remaining review Minors are deferred as instructed; no new queries or indexes in this repair.