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.

The route applies the four machine rules from the project's rules (#3964) (#3436)

harness-for-autonomous[bot]e9e2d6b70846
diff --git a/backend/integration/crewDispatch.test.ts b/backend/integration/crewDispatch.test.ts
index b12bd20c1..1cc88d77b 100644
--- a/backend/integration/crewDispatch.test.ts
+++ b/backend/integration/crewDispatch.test.ts
@@ -257,6 +257,39 @@ describe('the crew dispatch pass', () => {
expect((await readGroup(s.tab, phone)).handOutLane).toBe('mobile')
})
+ // Task #3964: the store reads the project's machine rules for a start, an assignment and the dispatch pass.
+ it('follows the project\'s machine rules from its record in a start, an assignment and the dispatch pass', async () => {
+ const s = await swarm({ Ash: 'backend' }, { Api: 'backend/src/a.ts' })
+ await save(s, 0, { machines: [{ machineIds: ['owner-mac'], why: 'This Mac takes no new work for now', noEngines: ['claude'] }] })
+ expect(await s.store.dispatchCrew(s.tab)).toMatchObject({ assigned: 0 })
+ await expect(s.execute({ type: 'work.assign', conversationId: s.tasks.Api!, agentId: s.crew.Ash! }, s.pm))
+ .rejects.toMatchObject({ code: 'MACHINE_RULE', message: 'This Mac takes no new work for now' })
+ await s.execute({ type: 'machine.contribute', machineId: 'owner-mac', name: 'Owner Mac', cwd: '/swarm', scope: 'swarm', engines: ['claude', 'codex'], maxAgents: 4 })
+ const generation = (await poolRows(s.store, owner, 'owner-mac')).find(p => p.tabId === s.tab)!.machine.generation
+ await s.store.observeMachine(owner, s.tab, 'owner-mac', { generation, resources: { cpuPercent: 10, memoryTotalBytes: 64e9, memoryUsedBytes: 4e9,
+ diskFreeBytes: 120e9, diskTotalBytes: 500e9, projectDiskFreeBytes: 120e9, deviceType: 'Desktop', chip: 'Fixture', os: 'macOS', gpuPercent: null },
+ quotas: [], tools: { git: true }, runningHarnessIds: [], stoppedHarnessIds: [] })
+ const request = (engine: string) => ({ conversationId: s.tasks.Api!, machineId: 'owner-mac', engine, name: 'Builder', cwd: '/swarm/lead', worktree: false,
+ requirements: { memoryBytes: 1e9, diskBytes: 1e9, maxCpuPercent: 90, tools: [], devices: [], quotaRequired: false } })
+ await expect(s.execute({ type: 'agent.start', request: request('claude') })).rejects.toMatchObject({ code: 'MACHINE_RULE' })
+ expect((await s.execute({ type: 'agent.start', request: request('codex') })).result.startId).toBeTruthy()
+ // Cleared by the people who set it: the member takes the task again.
+ await save(s, 1, { machines: [] })
+ expect(await s.store.dispatchCrew(s.tab)).toMatchObject({ assigned: 1 })
+ expect(await s.holders()).toEqual({ Api: 'Ash' })
+ })
+
+ // Security review 1 of #3964: a record broken elsewhere still applies the machine rules it holds that pass.
+ it('applies the machine rules of a record that fails the schema elsewhere, to an assignment', async () => {
+ const s = await swarm({ Ash: 'backend' }, { Api: 'backend/src/a.ts' })
+ const rule = { machineIds: ['owner-mac'], why: 'This Mac takes no new work for now', noEngines: ['claude' as const] }
+ await save(s, 0, { machines: [rule] })
+ await db.superTabProjectRules.updateMany({ where: { tabId: s.tab, projectId: 'lead' },
+ data: { rules: { ...structuredClone(SEED_RULES), dispatch: { ...SEED_RULES.dispatch, maxHanded: 0 }, machines: [rule] } } })
+ await expect(s.execute({ type: 'work.assign', conversationId: s.tasks.Api!, agentId: s.crew.Ash! }, s.pm))
+ .rejects.toMatchObject({ code: 'MACHINE_RULE', message: 'This Mac takes no new work for now' })
+ })
+
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/superTabNotAvailable.test.ts b/backend/integration/superTabNotAvailable.test.ts
index 735dedd95..4c3e67ad0 100644
--- a/backend/integration/superTabNotAvailable.test.ts
+++ b/backend/integration/superTabNotAvailable.test.ts
@@ -123,6 +123,7 @@ function calls(tab: string, chat: string, project: string) {
json('GET', 'GET /api/super-tabs/:tabId/projects/:projectId/instructions/revisions', `${t}/projects/${project}/instructions/revisions`),
json('GET', 'GET /api/super-tabs/:tabId/projects/:projectId/instructions/revisions/:revision', `${t}/projects/${project}/instructions/revisions/1`),
json('GET', 'GET /api/super-tabs/:tabId/projects/:projectId/rules', `${t}/projects/${project}/rules`),
+ json('GET', 'GET /api/super-tabs/:tabId/projects/:projectId/machine-rules', `${t}/projects/${project}/machine-rules`),
json('POST', 'POST /api/super-tabs/:tabId/attachments/uploads', `${t}/attachments/uploads`, { conversationId: chat, name: 'notes.txt', mime: 'text/plain', size: 12_000_000 }),
json('POST', 'POST /api/super-tabs/:tabId/attachments/uploads/:uploadId/complete', `${t}/attachments/uploads/${MISSING}/complete`, {}),
json('POST', 'POST /api/super-tabs/:tabId/attachments/:attachmentId/voice', `${t}/attachments/${MISSING}/voice?lang=en`, {}),
diff --git a/backend/integration/superTabProjectRules.test.ts b/backend/integration/superTabProjectRules.test.ts
index 78e77f886..e97a4a43f 100644
--- a/backend/integration/superTabProjectRules.test.ts
+++ b/backend/integration/superTabProjectRules.test.ts
@@ -98,6 +98,36 @@ describe('a project\'s rules record', () => {
expect((await get(host, tab, lead)).json().data).toMatchObject({ revision: 1 })
})
+ // Task #3964: the route reads the project's machine rules alone, the newest revision by its index, never the history.
+ it('gives an agent of the project its machine rules from the newest revision, by one indexed read', async () => {
+ const { tab, lead } = await swarm()
+ const machines = (user: AuthUser, asAgentId?: string) => app.inject({ method: 'GET',
+ url: `/api/super-tabs/${tab}/projects/lead/machine-rules${asAgentId ? `?asAgentId=${asAgentId}` : ''}`, headers: { authorization: `Bearer ${user.sub}` } })
+ const seed = await machines(host, lead)
+ expect(seed.statusCode, seed.body).toBe(200)
+ expect(seed.json().data).toEqual({ projectId: 'lead', revision: 0, machines: [] })
+ const rule = { machineIds: ['test-host'], why: 'No Codex there', noEngines: ['codex' as const] }
+ await run(tab, set(0, { ...rules('10:00'), machines: [rule] }))
+ const entries = await profiled(db, async () => {
+ expect((await machines(host, lead)).json().data).toEqual({ projectId: 'lead', revision: 1, machines: [rule] })
+ })
+ const read = reads(entries, 'SuperTabProjectRules', ['tabId', 'projectId'])
+ expect(read).toHaveLength(1)
+ expect(read[0]!.planSummary).toMatch(/IXSCAN/)
+ expect(read[0]!.docsExamined).toBeLessThanOrEqual(1)
+ // A record broken elsewhere still gives the machine rules that pass, as the server applies them (security review 1).
+ await db.superTabProjectRules.updateMany({ where: { tabId: tab, projectId: 'lead' },
+ data: { rules: { ...rules('10:00'), dispatch: { ...SEED_RULES.dispatch, maxHanded: 0 }, machines: [rule, { machineIds: [], why: 'Bad' }] } } })
+ const broken = await machines(host, lead)
+ expect(broken.statusCode, broken.body).toBe(200)
+ expect(broken.json().data).toEqual({ projectId: 'lead', revision: 1, machines: [rule] })
+ // Who may read the project reads them; nobody else.
+ expect((await machines(peer)).statusCode).toBe(200)
+ const stranger = await store.create(peer, randomUUID(), 'Other')
+ expect((await app.inject({ method: 'GET', url: `/api/super-tabs/${stranger.id}/projects/lead/machine-rules`,
+ headers: { authorization: `Bearer ${owner.sub}` } })).statusCode).toBe(404)
+ })
+
// The merge train (#3402) and the release schedule (#3405) read a project's rules from their workers.
it('gives a worker the newest record, or the seed at revision 0', async () => {
const { tab } = await swarm()
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.ts
index 5617aa7a6..0cb23caf0 100644
--- a/backend/src/routes/superTabs.ts
+++ b/backend/src/routes/superTabs.ts
@@ -876,6 +876,10 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su
app.get<{ Params: z.infer<typeof projectParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/projects/:projectId/rules',
{ preHandler: [validateParams(projectParams), validateQuery(agentQuery)] },
(req, reply) => respond(reply, () => store.projectRules(req.user!, req.params.tabId, req.params.projectId, req.query.asAgentId)))
+ // Its machine rules alone, from the newest revision: what the route applies (task #3964).
+ app.get<{ Params: z.infer<typeof projectParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/projects/:projectId/machine-rules',
+ { preHandler: [validateParams(projectParams), validateQuery(agentQuery)] },
+ (req, reply) => respond(reply, () => store.projectMachineRules(req.user!, req.params.tabId, req.params.projectId, req.query.asAgentId)))
app.get<{ Params: z.infer<typeof decisionParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/route-decisions/:decisionId',
{ preHandler: [validateParams(decisionParams), validateQuery(agentQuery)] },
(req, reply) => respond(reply, () => store.routeDecision(req.user!, req.params.tabId, req.params.decisionId, req.query.asAgentId)))
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 3892d35c0..8493b8291 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -30,6 +30,7 @@ import { routeRecordSchema, routeTitle, startedAs, type KeptCandidate, type Rout
import { routingOverrideSaveSchema } from './routingPolicy.js'
import { askedInSchema, RULE_MESSAGE_MS, ruleSchema, ruleTextSchema } from './rules.js'
import { projectRulesSchema, rulesDiff, rulesEqual, SEED_RULES, type ProjectRules } from './policy.js'
+import { isReview, machineRuleRefusal } from './machineRules.js'
import { accessRefusal, changeAccess, expireAccess, taskAccess } from './machineAccess.js'
import { MAX_ATTACHMENTS, type Attachment } from './attachments.js'
import { agentsNamedIn, checkMentions, MAX_MENTIONS, namedIn, saysName, textTags, withTags, type MentionTarget } from './mentions.js'
@@ -1772,6 +1773,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
// A crew member on its way to another machine takes work once there; an asleep one wakes for it, in place (crewKeep.ts),
// so its session is not closed (assignTo wakes it).
if (worker.movedTo) fail('CREW_MOVING', `${worker.displayName ?? worker.name} is moving to another machine. Assign it once it has moved.`)
+ // The project's machine rules (machineRules.ts), for an assignment and for the review steps a Ready hands out alike.
+ refuseByMachineRules(context, { machineId: worker.machineId, engine: worker.configuration.engine, review: isReview(group) })
if (!worker.asleep && sessionClosed(state, worker, context.now)) {
fail('AGENT_CLOSED', `${worker.displayName ?? worker.name}'s session was closed. Start a new agent for this task.`)
}
@@ -2249,15 +2252,19 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
fail('RULES_STALE', `The project rules changed since revision ${command.baseRevision}. Merge your change into revision ${current.revision} and save again.`,
409, { revision: current.revision, rules: current.rules })
}
- if (rulesEqual(current.rules, command.rules)) {
+ // A writer that does not know machine rules (an older client) leaves them as they are; one that sends a list sets it.
+ const kept = command.rules.machines === undefined && current.rules.machines ? projectRulesSchema.safeParse({ ...command.rules, machines: current.rules.machines }) : null
+ if (kept && !kept.success) fail('RULES_INVALID', `The project's machine rules do not fit this record: ${kept.error.issues[0]?.message ?? 'invalid'}`, 400)
+ const rules = kept?.data ?? command.rules
+ if (rulesEqual(current.rules, rules)) {
Object.assign(result, { projectId: project.id, revision: current.revision, unchanged: true })
break
}
const revision = current.revision + 1
- effects.projectRules = { projectId: project.id, revision, rules: command.rules, diff: rulesDiff(current.rules, command.rules),
+ effects.projectRules = { projectId: project.id, revision, rules, diff: rulesDiff(current.rules, 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)
+ && (group.projectId ?? 'lead') === project.id) stampLane(group, rules.lanes)
Object.assign(result, { projectId: project.id, revision })
break
}
@@ -3121,6 +3128,10 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
written ? { ...moved, projectSettings: 'off' } : moved)
// Before it is queued: a machine that cannot get the app's token for it would fail it, and count that against its engine.
requireRepositoryReach(state, teamAccountPool(state.machines?.find(m => m.machineId === request.machineId)), grant.machineOwnerId, home, context.repositoryReach)
+ // The project's machine rules (machineRules.ts), on the machine named and the one the start lands on (a Mac's Team account).
+ for (const machineId of new Set([named.machineId, request.machineId])) {
+ refuseByMachineRules(context, { machineId, engine: request.engine, review: isReview(startGroup) })
+ }
const pool = admitMachineStart(state, request, context.now, undefined, context.teamMachines, context.otherWorkspaceMachines)
// Off the Machines list, a teammate's project never runs: nothing there shows a privacy check (machines.ts).
if (!pool) requireTeamWork(state, request.machineId, grant.contributorId, home, context.now, context.teamMachines, context.otherWorkspaceMachines)
@@ -4689,6 +4700,13 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
return effects
}
+/** Refuses [work] its project's machine rules refuse now, with the rule's own why. A command whose record was not read
+ * (none in its context) meets no rule. */
+function refuseByMachineRules(context: CommandContext, work: { machineId: string; engine: string; review: boolean }): void {
+ const why = machineRuleRefusal(context.projectRules?.rules.machines ?? [], work, context.now)
+ if (why) fail('MACHINE_RULE', why, 409)
+}
+
/** Reject an invalid command result before the store tries to write duplicate message keys. */
export function assertUniqueMessageIds(commandType: string, messages: Array<{ id: string }>): void {
const ids = new Set<string>()
diff --git a/backend/src/superTabs/crewKeep.test.ts b/backend/src/superTabs/crewKeep.test.ts
index 184efdb98..63815ac22 100644
--- a/backend/src/superTabs/crewKeep.test.ts
+++ b/backend/src/superTabs/crewKeep.test.ts
@@ -3,7 +3,7 @@ import { applyCommand } from './commands.js'
import { crewKeep, crewNeedsMachine, type CrewDeps } from './crewKeep.js'
import { config, fixture, GB, machine, NOW, person } from './crewKeep.test-support.js'
import * as crewRules from './crewRules.js'
-import type { MachineRule } from './crewRules.js'
+import type { MachineRule } from './policy.js'
import { FOLDER_ASLEEP_MS, MOVE_LOW_DISK_BYTES, MOVE_OFFLINE_MS, MOVE_QUOTA_OUT_MS, SLEEP_IDLE_MS, DISK_FLOOR_BYTES } from './crewRules.js'
import type { Agent, SuperTabState } from './model.js'
@@ -171,7 +171,8 @@ describe('crewKeep: machine rules apply to moves, read from the project rules re
{ machineIds: ['no-codex'], why: 'no Codex there', noEngines: ['codex'] },
{ machineIds: ['travels'], why: 'away', away: { days: [1, 2, 3, 4, 5], windows: [['07:30', '09:30'], ['18:00', '21:00']], timeZone: 'Asia/Ho_Chi_Minh' } },
]
- const withRules: CrewDeps = { admits: () => true, machineRules: rules }
+ // Each project's own rules (#3964): the member's project here is the Swarm's first.
+ const withRules: CrewDeps = { admits: () => true, machineRules: projectId => projectId === 'lead' ? rules : [] }
it('never moves a member to a machine whose rule refuses its engine; another engine may go there', () => {
const codex = fixture([machine('mac', { signedIn: false }), machine('no-codex'), machine('other', { resetIn: 6 * 86_400_000 })])
codex.ada.configuration = { ...codex.ada.configuration, engine: 'codex' }
@@ -193,6 +194,31 @@ describe('crewKeep: machine rules apply to moves, read from the project rules re
const onBack = fixture(pools()); onBack.state.machines!.forEach(p => { p.observation!.receivedAt = back - 5000 })
expect(crewKeep(onBack.state, back, withRules)).toEqual([expect.objectContaining({ kind: 'move', toMachineId: 'travels' })])
})
+ // Review of PR #3436 (SecAlder): a crew Reviewer is never moved onto a machine where no Reviewer runs.
+ it('never moves a Reviewer to a machine where no Reviewer runs; an Engineer may go there', () => {
+ const noReviews: CrewDeps = { admits: () => true, machineRules: () => [{ machineIds: ['local-codex'], why: 'Its Codex defaults to a local model', noReviews: true }] }
+ const pools = () => [machine('mac', { signedIn: false }), machine('local-codex'), machine('other', { resetIn: 6 * 86_400_000 })]
+ const reviewer = fixture(pools())
+ ;(reviewer.ada as Agent & { crew?: unknown }).crew = { role: 'Reviewer', at: 1, by: 'owner' }
+ expect(crewKeep(reviewer.state, NOW, noReviews)).toEqual([expect.objectContaining({ kind: 'move', toMachineId: 'other' })])
+ // Any role the review steps take as a Reviewer's (reviewerPick.ts), not only one starting with the word.
+ const security = fixture(pools())
+ ;(security.ada as Agent & { crew?: unknown }).crew = { role: 'Security reviewer', at: 1, by: 'owner' }
+ expect(crewKeep(security.state, NOW, noReviews)).toEqual([expect.objectContaining({ kind: 'move', toMachineId: 'other' })])
+ const engineer = fixture(pools())
+ expect(crewKeep(engineer.state, NOW, noReviews)).toEqual([expect.objectContaining({ kind: 'move', toMachineId: 'local-codex' })])
+ })
+ it('reads the member\'s own project\'s rules, never another project\'s', () => {
+ const codex = fixture([machine('mac', { signedIn: false }), machine('no-codex'), machine('other', { resetIn: 6 * 86_400_000 })])
+ codex.ada.configuration = { ...codex.ada.configuration, engine: 'codex' }
+ for (const pool of codex.state.machines!) {
+ pool.engines = ['claude', 'codex']
+ ;(pool.observation as { readiness: { engines: unknown[] } }).readiness.engines = [{ engine: 'codex', installed: true, signedIn: pool.machineId !== 'mac' }]
+ ;(pool.observation as { quotas: Array<{ engine: string }> }).quotas[0]!.engine = 'codex'
+ }
+ const elsewhere: CrewDeps = { admits: () => true, machineRules: projectId => projectId === 'lead' ? [] : rules }
+ expect(crewKeep(codex.state, NOW, elsewhere)).toEqual([expect.objectContaining({ kind: 'move', toMachineId: 'no-codex' })])
+ })
it('with no rules record, no machine rule applies', () => {
const f = fixture([machine('mac', { signedIn: false }), machine('travels'), machine('other', { resetIn: 6 * 86_400_000 })])
expect(crewKeep(f.state, at('2026-11-09T01:00:00Z') + 0 * NOW, { admits: () => true })).toBeDefined()
diff --git a/backend/src/superTabs/crewKeep.ts b/backend/src/superTabs/crewKeep.ts
index 3f2f780e5..d96533926 100644
--- a/backend/src/superTabs/crewKeep.ts
+++ b/backend/src/superTabs/crewKeep.ts
@@ -4,10 +4,12 @@
* route's order (project instructions, Order and quota); folders of long-asleep members, and of asleep members on a machine
* short of disk, are dropped. The numbers are in crewRules.ts. Applying the actions is liveness.ts's (sweepLiveness).
*/
-import type { MachineRule } from './crewRules.js'
+import { machineRuleRefusal } from './machineRules.js'
+import type { MachineRule } from './policy.js'
import { activeWork, actorKey, stableId, type Agent, type AgentStart, type AgentStartRequest, type CrewTrouble, type MessageDraft, type SuperTabState } from './model.js'
import { isBuddy } from './buddies.js'
import { isCrew } from './crew.js'
+import { roleNameOf } from './instructions.js'
import { AGENT_MEMORY_BYTES, projectFolder, type ContributedMachine } from './machines.js'
import { agentProjectId, groupProject, onTeamAccount, projectsOf, teamAccountPool } from './projects.js'
import { barredFromTeamWritten, teamWrittenTask } from './teamWritten.js'
@@ -26,8 +28,8 @@ export type CrewAction =
* admitMachineStart, with the store's Team-account facts). */
export interface CrewDeps {
admits(machineId: string, agent: Agent): boolean
- /** The project's machine rules from its rules record (Ledger's task); none until that is on main (River, 11-05). */
- machineRules?: readonly MachineRule[]
+ /** A project's machine rules, from its rules record (policy.ts machines). */
+ machineRules?(projectId: string): readonly MachineRule[]
}
/** Whether [agent] is crew (#3397's `crew` record), read without its type until that change lands. */
@@ -40,23 +42,6 @@ function standingPool(state: SuperTabState, machineId: string): ContributedMachi
return pool && contributor && contributor.role !== 'viewer' && contributor.generation === pool.membershipGeneration ? pool : undefined
}
-/** Why [machineId] takes no crew member of [engine] at [now] by the project's machine rules ([rules], from the project rules
- * record), or null. */
-export function machineRuleRefusal(rules: readonly MachineRule[], machineId: string, engine: string, now: number): string | null {
- for (const rule of rules) {
- if (!rule.machineIds.includes(machineId)) continue
- if (rule.noEngines?.includes(engine)) return rule.why
- if (rule.away) {
- const parts = Object.fromEntries(new Intl.DateTimeFormat('en-US', { timeZone: rule.away.timeZone, weekday: 'short', hour: '2-digit',
- minute: '2-digit', hourCycle: 'h23' }).formatToParts(new Date(now)).map(p => [p.type, p.value]))
- const day = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].indexOf(parts.weekday ?? '')
- const time = `${parts.hour}:${parts.minute}`
- if (rule.away.days.includes(day) && rule.away.windows.some(([from, to]) => time >= from && time < to)) return rule.why
- }
- }
- return null
-}
-
/** The task [agent] holds: its active one, or one its machine took from it within HELD_TASK_MS and not handed on since. */
function heldTasks(state: SuperTabState, agent: Agent, now: number) {
const lost = agent.lostTask && now - agent.lostTask.at < HELD_TASK_MS ? agent.lostTask : undefined
@@ -110,6 +95,11 @@ export function fallbacks(state: SuperTabState, agent: Agent, now: number, deps:
const from = standingPool(state, agent.machineId)
const team = teamOnly(state, agent), kind = onTeamAccount(state, agent)
const engine = agent.configuration.engine
+ // A crew Reviewer goes nowhere a no-Reviewer rule refuses its reviews (review of #3964): any role the review steps take as a
+ // Reviewer's (reviewerPick.ts), its crew role or else its role name.
+ const reviews = /review/i.test(agent.crew?.role ?? roleNameOf(state, agent))
+ const projectId = agentProjectId(state, agent)
+ const rules = projectId ? deps.machineRules?.(projectId) ?? [] : []
const weekly = (pool: ContributedMachine) => quotaOf(state, pool, engine, now)?.windows.find(w => w.name === 'weekly')
const working = (pool: ContributedMachine) => state.agents.filter(a => a.machineId === pool.machineId && hasWork(state, a)).length
const key = (pool: ContributedMachine): Array<number | string> => {
@@ -122,7 +112,7 @@ export function fallbacks(state: SuperTabState, agent: Agent, now: number, deps:
// member never brings its own-account work into one. A machine that just refused its start waits.
.filter(pool => pool.machineId !== agent.machineId && !pool.buddyOnly && standingPool(state, pool.machineId) && (!team || teamAccountPool(pool))
&& teamAccountPool(pool) === kind && !(agent.crewMoveRefused?.machineId === pool.machineId && now - agent.crewMoveRefused.at < MOVE_REFUSED_WAIT_MS)
- && !machineRuleRefusal(deps.machineRules ?? [], pool.machineId, engine, now) && !crewTrouble(state, pool, engine, now) && deps.admits(pool.machineId, agent))
+ && !machineRuleRefusal(rules, { machineId: pool.machineId, engine, review: reviews }, now) && !crewTrouble(state, pool, engine, now) && deps.admits(pool.machineId, agent))
.map(pool => ({ pool, key: key(pool) }))
.sort((a, b) => { for (let i = 0; i < a.key.length; i++) if (a.key[i] !== b.key[i]) return a.key[i]! < b.key[i]! ? -1 : 1; return 0 })
.map(entry => entry.pool)
diff --git a/backend/src/superTabs/crewRules.ts b/backend/src/superTabs/crewRules.ts
index f96195795..c1b5e8f20 100644
--- a/backend/src/superTabs/crewRules.ts
+++ b/backend/src/superTabs/crewRules.ts
@@ -19,17 +19,5 @@ export const DISK_FLOOR_BYTES = 10 * GB
/** A machine that refused a member's move start (no token, no room) is not picked for that member again this long. */
export const MOVE_REFUSED_WAIT_MS = HOUR
-/** A machine rule the project's owners gave, as the project rules record holds it (Ledger's task): by machine id, each
- * machine of a Mac and its Harness Team account. Never written in source: people's machines and hours stay out of this
- * public repository (River, 11-05). Until the record is on main, no machine rule applies to moves. */
-export interface MachineRule {
- machineIds: string[]
- /** Why, in the words the project chat shows. */
- why: string
- /** Engines no crew member is moved there with. */
- noEngines?: string[]
- /** When it is away: on these weekdays (0 Sunday … 6 Saturday), between these local times, in its owner's time zone. */
- away?: { days: number[]; windows: Array<[string, string]>; timeZone: string }
-}
/** How long after losing its task to its machine a crew member still counts as holding it, so it moves with it. */
export const HELD_TASK_MS = HOUR
diff --git a/backend/src/superTabs/dispatch.ts b/backend/src/superTabs/dispatch.ts
index 1a3c61675..094ed0a93 100644
--- a/backend/src/superTabs/dispatch.ts
+++ b/backend/src/superTabs/dispatch.ts
@@ -4,7 +4,8 @@
* 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 { SEED_RULES, type MachineRule, type ProjectRules } from './policy.js'
+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'
@@ -26,8 +27,8 @@ const HOUR_MS = 3_600_000
export interface Lane { name: string; owns: readonly string[] }
/** 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 })
+export interface DispatchRules extends Readonly<ProjectRules['dispatch']> { readonly lanes: readonly Lane[]; readonly machines: readonly MachineRule[] }
+export const dispatchRules = (rules: ProjectRules): DispatchRules => ({ ...rules.dispatch, lanes: rules.lanes, machines: rules.machines ?? [] })
/** 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))
@@ -170,7 +171,10 @@ export function candidatesFor(state: SuperTabState, member: Agent, rules: Dispat
const pinned = open.filter(g => pinOf(g)?.agentId === member.id).sort((a, b) => pinOf(a)!.at - pinOf(b)!.at)
const members = new Set(state.agents.filter(a => a.workDecision !== 'stop' && !moving(a)).map(a => a.id))
const acceptsLane = takes(state, member, rules)
- const steps = open.filter(g => g.reviewOf && !lostByIt(g)).filter(step => {
+ // The project's machine rules (machineRules.ts): what its machine refuses now, it is not handed, pinned or not.
+ const refused = (review: boolean) => !!machineRuleRefusal(rules.machines, { machineId: member.machineId, engine: member.configuration.engine, review }, now)
+ const refusesWork = refused(false), refusesReview = refused(true)
+ const steps = open.filter(g => g.reviewOf && !lostByIt(g) && !(refusesReview && isReview(g))).filter(step => {
const task = state.conversations.find(g => g.id === step.reviewOf)!
const kind = /test/i.test(stepName(step)) ? 'test' : /security/i.test(stepName(step)) ? 'security' : 'review'
const latest = task.pullRequestUrls?.at(-1)
@@ -182,7 +186,7 @@ export function candidatesFor(state: SuperTabState, member: Agent, rules: Dispat
&& (member.crew || (g.assignment?.status === 'lost' && g.lostAttempt))
&& acceptsLane(laneOf(g, rules.lanes)) && (!needsStrongModel(g) || onStrongModel(member)))
// Team-written code goes to Team accounts only (teamWritten.ts); a pick refused this round is not sent again (store.ts).
- const allowed = (group: Conversation) => (!group.reviewOf || steps.includes(group)) && !barredFromTeamWritten(state, group, member) && !skip(group.id, member.id)
+ const allowed = (group: Conversation) => (group.reviewOf ? steps.includes(group) : !refusesWork) && !barredFromTeamWritten(state, group, member) && !skip(group.id, member.id)
return [...pinned.filter(allowed).map(group => ({ group, why: 'pin' as const })),
...[...steps.filter(g => !pinned.includes(g)), ...lane].filter(allowed).map(group => ({ group, why: 'lane' as const }))]
}
@@ -206,8 +210,16 @@ export interface DispatchPick { conversationId: string; agentId: string; why: 'p
export function dispatchPlan(state: SuperTabState, projectId: string, rules: DispatchRules, now: number, skip: Skip = () => false): DispatchPick[] {
if (state.paused) return []
const open = openTasks(state, projectId, now), taken = new Set<string>(), picks: DispatchPick[] = []
- for (const member of freeCrew(state, projectId, rules, now)) {
- const next = candidatesFor(state, member, rules, now, open, skip).find(c => !taken.has(c.group.id))
+ const free = freeCrew(state, projectId, rules, now)
+ const candidates = new Map(free.map(member => [member.id, candidatesFor(state, member, rules, now, open, skip)]))
+ // A lane's work goes first to its machines (machineRules.ts firstMachines): a task a free member there could take waits for
+ // it; a member elsewhere takes it only when none there can.
+ const heldFor = new Map<string, string[]>()
+ for (const member of free) for (const { group, why } of candidates.get(member.id)!) {
+ if (why === 'lane' && firstMachines(rules.machines, laneOf(group, rules.lanes)).includes(member.machineId)) heldFor.set(group.id, [...heldFor.get(group.id) ?? [], member.id])
+ }
+ for (const member of free) {
+ const next = candidates.get(member.id)!.find(c => !taken.has(c.group.id) && (c.why === 'pin' || !heldFor.has(c.group.id) || heldFor.get(c.group.id)!.includes(member.id)))
if (!next) continue
taken.add(next.group.id)
picks.push({ conversationId: next.group.id, agentId: member.id, why: next.why, lane: laneOf(next.group, rules.lanes) })
diff --git a/backend/src/superTabs/machineRules.cases.json b/backend/src/superTabs/machineRules.cases.json
new file mode 100644
index 000000000..ae01ecabc
--- /dev/null
+++ b/backend/src/superTabs/machineRules.cases.json
@@ -0,0 +1,30 @@
+{
+ "about": "Shared cases for the project's machine rules (task #3964): backend superTabs/machineRules.ts decides, cli/src/superTabs/machineRules.ts filters the route early; both specs read this file so the two cannot drift. Generic machines and hours only.",
+ "rules": [
+ { "machineIds": ["travels", "travels-team"], "why": "Away while its owner travels", "away": { "days": [1, 2, 3, 4, 5], "windows": [["07:30", "09:30"], ["18:00", "21:00"]], "timeZone": "Asia/Ho_Chi_Minh" } },
+ { "machineIds": ["phone-mac"], "why": "The phone setup is there", "first": { "lanes": ["mobile"] } },
+ { "machineIds": ["no-codex"], "why": "No Codex there", "noEngines": ["codex"] },
+ { "machineIds": ["local-codex"], "why": "Its Codex defaults to a local model", "noReviews": true }
+ ],
+ "refusals": [
+ { "at": "2026-11-09T01:00:00Z", "machineId": "travels", "engine": "claude", "review": false, "why": "Away while its owner travels" },
+ { "at": "2026-11-09T00:30:00Z", "machineId": "travels", "engine": "claude", "review": false, "why": "Away while its owner travels" },
+ { "at": "2026-11-09T02:29:00Z", "machineId": "travels", "engine": "claude", "review": false, "why": "Away while its owner travels" },
+ { "at": "2026-11-09T02:30:00Z", "machineId": "travels", "engine": "claude", "review": false, "why": null },
+ { "at": "2026-11-09T00:29:00Z", "machineId": "travels", "engine": "claude", "review": false, "why": null },
+ { "at": "2026-11-09T11:30:00Z", "machineId": "travels-team", "engine": "codex", "review": true, "why": "Away while its owner travels" },
+ { "at": "2026-11-14T01:00:00Z", "machineId": "travels", "engine": "claude", "review": false, "why": null },
+ { "at": "2026-11-08T17:30:00Z", "machineId": "travels", "engine": "claude", "review": false, "why": null },
+ { "at": "2026-11-09T01:00:00Z", "machineId": "no-codex", "engine": "codex", "review": false, "why": "No Codex there" },
+ { "at": "2026-11-09T01:00:00Z", "machineId": "no-codex", "engine": "claude", "review": true, "why": null },
+ { "at": "2026-11-09T01:00:00Z", "machineId": "local-codex", "engine": "claude", "review": true, "why": "Its Codex defaults to a local model" },
+ { "at": "2026-11-09T01:00:00Z", "machineId": "local-codex", "engine": "codex", "review": false, "why": null },
+ { "at": "2026-11-09T01:00:00Z", "machineId": "other", "engine": "codex", "review": true, "why": null }
+ ],
+ "first": [
+ { "lane": "mobile", "machines": ["phone-mac"] },
+ { "lane": "Mobile", "machines": ["phone-mac"] },
+ { "lane": "backend", "machines": [] },
+ { "lane": null, "machines": [] }
+ ]
+}
diff --git a/backend/src/superTabs/machineRules.commands.test.ts b/backend/src/superTabs/machineRules.commands.test.ts
new file mode 100644
index 000000000..6dbd1934b
--- /dev/null
+++ b/backend/src/superTabs/machineRules.commands.test.ts
@@ -0,0 +1,126 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, commandSchema, type Command, type CommandContext } from './commands.js'
+import { DISPATCH_RULES, dispatchPlan, dispatchRules } from './dispatch.js'
+import { createSuperTab, type Actor, type AgentConfiguration } from './model.js'
+import { SEED_RULES, type MachineRule, type ProjectRules } from './policy.js'
+
+// Task #3964: starts, assignments and the lane dispatch follow the project's machine rules. Generic machines and hours.
+const RULES: MachineRule[] = [
+ { machineIds: ['travels'], why: 'Away while its owner travels', away: { days: [1, 2, 3, 4, 5], windows: [['07:30', '09:30']], timeZone: 'Asia/Ho_Chi_Minh' } },
+ { machineIds: ['phone-mac'], why: 'The phone setup is there', first: { lanes: ['mobile'] } },
+ { machineIds: ['no-codex'], why: 'No Codex there', noEngines: ['codex'] },
+ { machineIds: ['local-codex'], why: 'Its Codex defaults to a local model', noReviews: true },
+]
+const RECORD: ProjectRules = { ...structuredClone(SEED_RULES), machines: RULES }
+// Monday 2026-11-09 08:00 in Vietnam, inside the away window; 10:00 there, outside it.
+const AWAY = Date.parse('2026-11-09T01:00:00Z'), BACK = Date.parse('2026-11-09T03:00:00Z')
+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
+const config = (engine = 'claude'): AgentConfiguration => ({ engine, model: 'test-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' })
+const contribution = { machineOwnerId: 'host-owner', contributorId: 'owner' }
+
+function swarm() {
+ let state = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')
+ let sequence = 0
+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {
+ const effects = applyCommand(state, actor, commandSchema.parse(command), { now: BACK, operationId: `op-${++sequence}`, contribution,
+ projectRules: { revision: 1, rules: RECORD }, ...context })
+ state = effects.state
+ return effects
+ }
+ const add = (name: string, machineId: string, engine = 'claude', lead = false) => run({ type: 'agent.add', conversationId: 'lead', machineId,
+ harnessId: name, name, configuration: config(engine), lead }).result.agentId as string
+ const pm = add('PM', 'host', 'claude', true)
+ const as = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'host-owner' })
+ const task = (title: string, owns: string[]) => run({ type: 'conversation.create', title,
+ task: { goal: `${title}.`, changes: 'The change.', constraints: 'None.', owns }, checks: [] } as Command).result.conversationId as string
+ const review = (of: string) => run({ type: 'conversation.create', title: 'Review', brief: 'Review it.', reviewOf: of, step: 'Review', checks: [] }).result.conversationId as string
+ return { run, add, pm, as, task, review, get state() { return state } }
+}
+const refusal = (run: () => unknown) => { try { run(); return null } catch (error) { return { code: (error as { code?: string }).code, message: (error as Error).message } } }
+
+describe('a start follows the machine rules', () => {
+ const start = (s: ReturnType<typeof swarm>, group: string, machineId: string, engine: string, now = BACK) => s.run({ type: 'agent.start',
+ request: { conversationId: group, machineId, engine, name: 'Worker', cwd: '/repo', worktree: true,
+ requirements: { memoryBytes: 100, diskBytes: 200, maxCpuPercent: 80, tools: [], devices: [], quotaRequired: false } } }, s.as(s.pm), { now })
+
+ it('refuses an engine a machine refuses, a Reviewer where none runs, and anything while the machine is away, with the why', () => {
+ const s = swarm()
+ for (const [name, machine] of [['A', 'no-codex'], ['B', 'local-codex'], ['C', 'travels']]) s.add(name!, machine!)
+ const work = s.task('Server', ['backend/src/a.ts']), step = s.review(work)
+ expect(refusal(() => start(s, work, 'no-codex', 'codex'))).toEqual({ code: 'MACHINE_RULE', message: 'No Codex there' })
+ expect(refusal(() => start(s, work, 'no-codex', 'claude'))).toBeNull()
+ expect(refusal(() => start(s, step, 'local-codex', 'codex'))).toEqual({ code: 'MACHINE_RULE', message: 'Its Codex defaults to a local model' })
+ expect(refusal(() => start(s, work, 'local-codex', 'codex'))).toBeNull()
+ expect(refusal(() => start(s, work, 'travels', 'claude', AWAY))).toEqual({ code: 'MACHINE_RULE', message: 'Away while its owner travels' })
+ expect(refusal(() => start(s, work, 'travels', 'claude', BACK))).toBeNull()
+ })
+
+ it('refuses nothing in a project whose record has no machine rules', () => {
+ const s = swarm()
+ s.add('A', 'no-codex')
+ const work = s.task('Server', ['backend/src/a.ts'])
+ expect(refusal(() => s.run({ type: 'agent.start', request: { conversationId: work, machineId: 'no-codex', engine: 'codex', name: 'Worker', cwd: '/repo',
+ worktree: true, requirements: { memoryBytes: 100, diskBytes: 200, maxCpuPercent: 80, tools: [], devices: [], quotaRequired: false } } },
+ s.as(s.pm), { projectRules: { revision: 0, rules: SEED_RULES } }))).toBeNull()
+ })
+})
+
+describe('an assignment follows the machine rules', () => {
+ it('refuses a review to an agent where no Reviewer runs, and any work while its machine is away, with the why', () => {
+ const s = swarm()
+ const local = s.add('Local', 'local-codex', 'codex'), traveller = s.add('Traveller', 'travels')
+ const work = s.task('Server', ['backend/src/a.ts']), step = s.review(work)
+ expect(refusal(() => s.run({ type: 'work.assign', conversationId: step, agentId: local }, s.as(s.pm))))
+ .toEqual({ code: 'MACHINE_RULE', message: 'Its Codex defaults to a local model' })
+ expect(refusal(() => s.run({ type: 'work.assign', conversationId: work, agentId: traveller }, s.as(s.pm), { now: AWAY })))
+ .toEqual({ code: 'MACHINE_RULE', message: 'Away while its owner travels' })
+ expect(refusal(() => s.run({ type: 'work.assign', conversationId: work, agentId: local }, s.as(s.pm)))).toBeNull()
+ })
+
+ it('lets a Tester run where no Reviewer runs: a test step is not a review', () => {
+ const s = swarm()
+ const local = s.add('Local', 'local-codex', 'codex')
+ const work = s.task('Server', ['backend/src/a.ts'])
+ const test = s.run({ type: 'conversation.create', title: 'Test', brief: 'Test it.', reviewOf: work, step: 'Test', checks: [] }).result.conversationId as string
+ expect(refusal(() => s.run({ type: 'work.assign', conversationId: test, agentId: local }, s.as(s.pm)))).toBeNull()
+ })
+})
+
+describe('the lane dispatch follows the machine rules', () => {
+ /** Engineers [names] on their machines, crew with no lane. */
+ function crew(members: Array<[string, string, string?]>) {
+ const s = swarm()
+ const ids = Object.fromEntries(members.map(([name, machine, engine]) => [name, s.add(name, machine, engine)]))
+ for (const id of Object.values(ids)) s.state.agents.find(a => a.id === id)!.crew = { role: 'Engineer', at: 1000, by: 'owner' }
+ const picks = (now = BACK) => dispatchPlan(s.state, 'lead', dispatchRules(RECORD), now)
+ .map(p => [s.state.agents.find(a => a.id === p.agentId)!.name, s.state.conversations.find(c => c.id === p.conversationId)!.title])
+ return { ...s, ids, picks }
+ }
+
+ it('hands nothing to a member while its machine is away, and work again after', () => {
+ const s = crew([['Traveller', 'travels']])
+ s.task('Server', ['backend/src/a.ts'])
+ expect(s.picks(AWAY)).toEqual([])
+ expect(s.picks(BACK)).toEqual([['Traveller', 'Server']])
+ })
+
+ it('hands a member no work its machine refuses its engine for', () => {
+ const s = crew([['Codex', 'no-codex', 'codex']])
+ s.task('Server', ['backend/src/a.ts'])
+ expect(s.picks()).toEqual([])
+ })
+
+ it('leaves phone work to a free member on the phone machine, and to another only when none is free there', () => {
+ const s = crew([['Elsewhere', 'other'], ['Phone', 'phone-mac']])
+ s.task('App', ['mobile/lib/a.dart'])
+ expect(s.picks()).toEqual([['Phone', 'App']])
+ const alone = crew([['Elsewhere', 'other']])
+ alone.task('App', ['mobile/lib/a.dart'])
+ expect(alone.picks()).toEqual([['Elsewhere', 'App']])
+ })
+
+ it('reads no machine rule from a record without them', () => {
+ expect(dispatchRules(SEED_RULES).machines).toEqual([])
+ expect(DISPATCH_RULES.machines).toEqual([])
+ })
+})
diff --git a/backend/src/superTabs/machineRules.test.ts b/backend/src/superTabs/machineRules.test.ts
new file mode 100644
index 000000000..9bc7af438
--- /dev/null
+++ b/backend/src/superTabs/machineRules.test.ts
@@ -0,0 +1,76 @@
+import { readFileSync } from 'node:fs'
+import { describe, expect, it } from 'vitest'
+import { firstMachines, machineRuleRefusal } from './machineRules.js'
+import { projectRulesSchema, SEED_RULES, validMachineRules, type MachineRule } from './policy.js'
+
+// Task #3964: the four Machines rules of the Routing instructions, as the project rules record holds them. Generic machines
+// and hours: never a person's real ones in source (River, 11-05).
+const RULES: MachineRule[] = [
+ { machineIds: ['travels', 'travels-team'], why: 'Away while its owner travels', away: { days: [1, 2, 3, 4, 5], windows: [['07:30', '09:30'], ['18:00', '21:00']], timeZone: 'Asia/Ho_Chi_Minh' } },
+ { machineIds: ['phone-mac'], why: 'The phone setup is there', first: { lanes: ['mobile'] } },
+ { machineIds: ['no-codex'], why: 'No Codex there', noEngines: ['codex'] },
+ { machineIds: ['local-codex'], why: 'Its Codex defaults to a local model', noReviews: true },
+]
+// Monday 2026-11-09 in Vietnam (UTC+7): 08:00 there is 01:00 UTC, 10:00 there 03:00 UTC, 18:30 there 11:30 UTC.
+const MONDAY_8 = Date.parse('2026-11-09T01:00:00Z'), MONDAY_10 = Date.parse('2026-11-09T03:00:00Z'), MONDAY_1830 = Date.parse('2026-11-09T11:30:00Z')
+// Saturday 2026-11-14 08:00 there.
+const SATURDAY_8 = Date.parse('2026-11-14T01:00:00Z')
+const work = (machineId: string, engine = 'claude', review = false) => ({ machineId, engine, review })
+
+describe('machineRuleRefusal', () => {
+ it('refuses a machine inside its away window, on its days, in its own time zone, for each of its ids', () => {
+ expect(machineRuleRefusal(RULES, work('travels'), MONDAY_8)).toBe('Away while its owner travels')
+ expect(machineRuleRefusal(RULES, work('travels-team'), MONDAY_1830)).toBe('Away while its owner travels')
+ expect(machineRuleRefusal(RULES, work('travels'), MONDAY_10)).toBeNull()
+ expect(machineRuleRefusal(RULES, work('travels'), SATURDAY_8)).toBeNull()
+ })
+
+ it('refuses an engine where a rule says no agent of it runs, and only that engine', () => {
+ expect(machineRuleRefusal(RULES, work('no-codex', 'codex'), MONDAY_8)).toBe('No Codex there')
+ expect(machineRuleRefusal(RULES, work('no-codex', 'claude'), MONDAY_8)).toBeNull()
+ })
+
+ it('refuses a review where a rule says no Reviewer runs, and nothing else there', () => {
+ expect(machineRuleRefusal(RULES, work('local-codex', 'claude', true), MONDAY_8)).toBe('Its Codex defaults to a local model')
+ expect(machineRuleRefusal(RULES, work('local-codex', 'codex', false), MONDAY_8)).toBeNull()
+ })
+
+ it('refuses nothing on a machine no rule names, or with no rules', () => {
+ expect(machineRuleRefusal(RULES, work('other', 'codex', true), MONDAY_8)).toBeNull()
+ expect(machineRuleRefusal([], work('travels', 'codex', true), MONDAY_8)).toBeNull()
+ })
+})
+
+describe('firstMachines', () => {
+ it('names the machines a lane goes to first, in any case, and none for another lane', () => {
+ expect(firstMachines(RULES, 'mobile')).toEqual(['phone-mac'])
+ expect(firstMachines(RULES, 'Mobile')).toEqual(['phone-mac'])
+ expect(firstMachines(RULES, 'backend')).toEqual([])
+ expect(firstMachines(RULES, null)).toEqual([])
+ })
+})
+
+// The CLI route's early filter reads the same cases (cli/src/superTabs/machineRules.spec.ts): the two cannot drift (security review 1).
+describe('the shared machine rule cases', () => {
+ const cases = JSON.parse(readFileSync(new URL('./machineRules.cases.json', import.meta.url), 'utf8')) as {
+ rules: MachineRule[]; refusals: Array<{ at: string; machineId: string; engine: string; review: boolean; why: string | null }>
+ first: Array<{ lane: string | null; machines: string[] }> }
+ it('are rules the record holds', () => {
+ expect(projectRulesSchema.parse({ ...structuredClone(SEED_RULES), machines: cases.rules }).machines).toEqual(cases.rules)
+ })
+ it('refuse and place as each case says', () => {
+ for (const c of cases.refusals) expect(machineRuleRefusal(cases.rules, c, Date.parse(c.at)), JSON.stringify(c)).toBe(c.why)
+ for (const c of cases.first) expect(firstMachines(cases.rules, c.lane)).toEqual(c.machines)
+ })
+})
+
+// Security review 1 of #3964: a record that fails the schema elsewhere still applies its machine rules that pass.
+describe('validMachineRules', () => {
+ it('keeps each machine rule that passes, from a record that may not', () => {
+ const broken = { ...structuredClone(SEED_RULES), dispatch: { maxHanded: 0 }, machines: [RULES[2], { machineIds: [], why: 'Bad' }, RULES[3], 'junk'] }
+ expect(projectRulesSchema.safeParse(broken).success).toBe(false)
+ expect(validMachineRules(broken)).toEqual([RULES[2], RULES[3]])
+ expect(validMachineRules({ machines: 'none' })).toEqual([])
+ expect(validMachineRules(null)).toEqual([])
+ })
+})
diff --git a/backend/src/superTabs/machineRules.ts b/backend/src/superTabs/machineRules.ts
new file mode 100644
index 000000000..ca835884a
--- /dev/null
+++ b/backend/src/superTabs/machineRules.ts
@@ -0,0 +1,38 @@
+/**
+ * The project's machine rules (project instructions, Routing › Machines; task #3964), as its rules record holds them
+ * (policy.ts): why a machine refuses a piece of work now, and which machines a lane's work goes to first. Pure, so the
+ * start, the assignment, the dispatch and the crew keeper all read a rule alike.
+ */
+import type { Conversation } from './model.js'
+import type { MachineRule } from './policy.js'
+import { stepName } from './steps.js'
+
+const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
+
+/** Whether [rule]'s machine is away at [now]: on one of its weekdays, inside one of its windows, in its own time zone. */
+function away(rule: MachineRule, now: number): boolean {
+ if (!rule.away) return false
+ const parts = Object.fromEntries(new Intl.DateTimeFormat('en-US', { timeZone: rule.away.timeZone, weekday: 'short', hour: '2-digit',
+ minute: '2-digit', hourCycle: 'h23' }).formatToParts(new Date(now)).map(p => [p.type, p.value]))
+ const time = `${parts.hour}:${parts.minute}`
+ return rule.away.days.includes(WEEKDAYS.indexOf(parts.weekday ?? '')) && rule.away.windows.some(([from, to]) => time >= from && time < to)
+}
+
+/** Why [work] (an agent of [engine] on [machineId], reviewing or not) may not run there at [now] by [rules], or null. */
+export function machineRuleRefusal(rules: readonly MachineRule[], work: { machineId: string; engine: string; review: boolean }, now: number): string | null {
+ for (const rule of rules) {
+ if (!rule.machineIds.includes(work.machineId)) continue
+ if (rule.noEngines?.includes(work.engine as 'claude' | 'codex') || (rule.noReviews && work.review) || away(rule, now)) return rule.why
+ }
+ return null
+}
+
+/** Whether [group] is a review, which a no-Reviewer rule refuses: a step that is not a test (as dispatch.ts sorts steps). */
+export const isReview = (group: Conversation): boolean => !!group.reviewOf && !/test/i.test(stepName(group))
+
+/** The machines [lane]'s work goes to first, by [rules]; none for no lane. */
+export function firstMachines(rules: readonly MachineRule[], lane: string | null): string[] {
+ if (!lane) return []
+ const name = lane.toLowerCase()
+ return rules.filter(rule => rule.first?.lanes.some(l => l.toLowerCase() === name)).flatMap(rule => rule.machineIds)
+}
diff --git a/backend/src/superTabs/policy.test.ts b/backend/src/superTabs/policy.test.ts
index 4982d8835..e2f12553f 100644
--- a/backend/src/superTabs/policy.test.ts
+++ b/backend/src/superTabs/policy.test.ts
@@ -453,3 +453,41 @@ describe('who changes the rules', () => {
expect(code(() => f.run(set(0, later(), asked(task)), as(buddy), context))).toBe('BUDDY_FORBIDDEN')
})
})
+
+// Task #3964 (part 2 of #3576): the four Machines rules of the Routing instructions, as project data by machine id.
+describe('machine rules in the record', () => {
+ const RULES = [
+ { machineIds: ['ken-mbp'], why: 'Ken travels then', away: { days: [1, 2, 3, 4, 5], windows: [['07:30', '09:30'], ['18:00', '21:00']], timeZone: 'Asia/Ho_Chi_Minh' } },
+ { machineIds: ['tony-mac'], why: 'Tony\'s Mac has the phone setup', first: { lanes: ['mobile'] } },
+ { machineIds: ['diego-mac'], why: 'Diego runs no Codex', noEngines: ['codex'] },
+ { machineIds: ['local-codex'], why: 'Its Codex defaults to a local model', noReviews: true },
+ ]
+ const withMachines = (machines: unknown): ProjectRules => ({ ...copy(), machines } as ProjectRules)
+
+ it('holds each of the four kinds, and refuses a rule that is wrong or says nothing', () => {
+ expect(projectRulesSchema.parse(withMachines(RULES)).machines).toEqual(RULES)
+ const away = RULES[0]!.away
+ expect(refused(withMachines([{ ...RULES[0], away: { ...away, windows: [['09:30', '07:30']] } }]))).toBe(true)
+ expect(refused(withMachines([{ ...RULES[0], away: { ...away, days: [7] } }]))).toBe(true)
+ expect(refused(withMachines([{ ...RULES[0], away: { ...away, timeZone: 'Mars/Olympus' } }]))).toBe(true)
+ expect(refused(withMachines([{ ...RULES[2], noEngines: ['gemini'] }]))).toBe(true)
+ // A lane the record does not have: the rule would never apply.
+ expect(refused(withMachines([{ ...RULES[1], first: { lanes: ['firmware'] } }]))).toBe(true)
+ expect(refused(withMachines([{ machineIds: ['m'], why: 'Nothing' }]))).toBe(true)
+ expect(refused(withMachines([{ ...RULES[3], machineIds: [] }]))).toBe(true)
+ // A record from before has none.
+ expect(projectRulesSchema.parse(copy()).machines).toBeUndefined()
+ })
+
+ it('keeps the current machine rules when a save leaves them out, and clears them only when it says so', () => {
+ const f = fixture()
+ const current = { revision: 1, rules: withMachines(RULES) }
+ const kept = f.run(set(1, later()), owner, { projectRules: current })
+ expect(kept.projectRules?.rules.machines).toEqual(RULES)
+ expect(kept.projectRules?.diff).toEqual([{ path: 'releaseWindow.start', before: '09:00', after: '08:00' }])
+ const cleared = f.run(set(1, { ...later(), machines: [] } as ProjectRules), owner, { projectRules: current })
+ expect(cleared.projectRules?.rules.machines).toEqual([])
+ // An old client renaming the phone lane cannot keep a rule naming a lane that is gone.
+ expect(code(() => f.run(set(1, { ...copy(), lanes: [{ name: 'phone', owns: ['mobile/'] }] }), owner, { projectRules: current }))).toBe('RULES_INVALID')
+ })
+})
diff --git a/backend/src/superTabs/policy.ts b/backend/src/superTabs/policy.ts
index 7862e1d20..464b6c0a8 100644
--- a/backend/src/superTabs/policy.ts
+++ b/backend/src/superTabs/policy.ts
@@ -56,6 +56,28 @@ const legacyDispatch = (value: unknown): unknown => {
return { ...old, dispatch: SEED_DISPATCH, ...Array.isArray(old.lanes) && old.lanes.length === 0 ? { lanes: SEED_LANES } : {} }
}
+/** A machine by its id, as the Swarm's Machines list names it: a Mac and its Harness Team account are two ids. */
+const machineId = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/, 'A machine id.')
+/** A machine rule its owners gave (project instructions, Routing › Machines; task #3964): kept here by machine id, never in
+ * source, since people's machines and hours stay out of this public repository (River, 11-05). Each says why, in the words
+ * people read, and at least one of: when the machine is away, the engines no agent runs there with, that no Reviewer runs
+ * there, or the lanes whose work goes there first. machineRules.ts applies them. */
+const machineRuleSchema = z.object({
+ machineIds: z.array(machineId).min(1).max(20),
+ why: line(200),
+ /** On these weekdays (0 Sunday … 6 Saturday), between these local times, in its owner's time zone: nothing starts there. */
+ away: z.object({
+ days: z.array(z.number().int().min(0).max(6)).min(1).max(7),
+ windows: z.array(z.tuple([clock, clock]).refine(([from, to]) => from < to, 'An away window ends after it starts, the same day.')).min(1).max(6),
+ timeZone,
+ }).strict().optional(),
+ noEngines: z.array(z.enum(['claude', 'codex'])).min(1).max(2).optional(),
+ noReviews: z.literal(true).optional(),
+ /** Work of these lanes goes to this machine first, while an agent there takes it. */
+ first: z.object({ lanes: z.array(line(80)).min(1).max(MAX_LIST) }).strict().optional(),
+}).strict().refine(rule => !!(rule.away || rule.noEngines || rule.noReviews || rule.first),
+ 'A machine rule says when the machine is away, which engines or Reviewers it refuses, or which lanes go there first.')
+
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()
@@ -85,8 +107,13 @@ export const projectRulesSchema = z.preprocess(legacyDispatch, z.object({
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'),
+ /** The project's machine rules. Absent on a record from before them: none apply. */
+ machines: z.array(machineRuleSchema).max(MAX_LIST).optional(),
}).strict().refine(rules => Buffer.byteLength(JSON.stringify(rules)) <= MAX_RULES_BYTES,
`Project rules are at most ${MAX_RULES_BYTES / 1024} KB.`)
+ // A lane a machine rule names is one the record has, or the rule would never apply.
+ .refine(rules => (rules.machines ?? []).every(rule => (rule.first?.lanes ?? []).every(name =>
+ rules.lanes.some(lane => lane.name.toLowerCase() === name.toLowerCase()))), 'A machine rule names a lane this record has.')
// The backend pause is a part of the release window (review of #3216): outside it, there is no release to pause.
.refine(rules => {
const pause = rules.releasePace.backendPause
@@ -94,6 +121,13 @@ export const projectRulesSchema = z.preprocess(legacyDispatch, z.object({
}, 'The backend pause falls inside the release window.'))
export type ProjectRules = z.infer<typeof projectRulesSchema>
+export type MachineRule = z.infer<typeof machineRuleSchema>
+/** The machine rules of a stored [record] that pass, whether or not the rest of it does (security review 1 of #3964): a record
+ * broken elsewhere still keeps a machine its owner's rule refuses work, rather than failing open while it is repaired. */
+export function validMachineRules(record: unknown): MachineRule[] {
+ const machines = record && typeof record === 'object' ? (record as { machines?: unknown }).machines : undefined
+ return Array.isArray(machines) ? machines.flatMap(rule => { const parsed = machineRuleSchema.safeParse(rule); return parsed.success ? [parsed.data] : [] }) : []
+}
/** [value] frozen all the way down: the seed is shared, so no reader may change it. */
function deepFreeze<T>(value: T): T {
diff --git a/backend/src/superTabs/reviewSteps.test.ts b/backend/src/superTabs/reviewSteps.test.ts
index 9bdc0360b..9b778a59c 100644
--- a/backend/src/superTabs/reviewSteps.test.ts
+++ b/backend/src/superTabs/reviewSteps.test.ts
@@ -33,6 +33,21 @@ function fixture() {
}
describe('a handed task opens its review steps', () => {
+ // Task #3964 (review of PR #3436): the Ready that hands out review steps follows the project's machine rules too.
+ it('hands no review step to a Reviewer on a machine where no Reviewer runs, and gives it to one elsewhere', () => {
+ const rules = { projectRules: { revision: 1, rules: { ...SEED_RULES, machines: [{ machineIds: ['host'], why: 'Its Codex defaults to a local model', noReviews: true as const }] } } }
+ const alone = fixture()
+ alone.add('rev-local', alone.task, 'Reviewer')
+ alone.ready(['docs/a.md'], 'abc1234', true, rules)
+ expect(alone.steps()).toEqual([{ name: 'Review', agent: null, status: null }])
+ const f = fixture()
+ f.add('rev-local', f.task, 'Reviewer')
+ const elsewhere = f.run({ type: 'agent.add', conversationId: f.task, machineId: 'other', harnessId: 'rev-other', name: 'rev-other', configuration: opus,
+ lead: false, roleName: 'Reviewer' } as Command, owner, { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }).result.agentId as string
+ f.ready(['docs/a.md'], 'abc1234', true, rules)
+ expect(f.steps()).toEqual([{ name: 'Review', agent: elsewhere, status: 'working' }])
+ })
+
it('a pull request touching sign-in code opens two security reviews, each to a different free Reviewer, never the Engineer', () => {
const f = fixture()
const a = f.add('rev-a', f.task, 'Reviewer'), b = f.add('rev-b', f.task, 'Reviewer')
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 6aa485971..645a0122b 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -67,7 +67,7 @@ import { lostReasonWithoutMachine } from './lostReason.js'
import { LEAD_NAME } from './leadStart.js'
import { deleteInstructions, instructionsId, readNotes, revisionId, writeInstructions, writeNotes } from './instructionsStore.js'
import { currentRules, deleteRules, readRules, readRulesHistory, writeRules } from './policyStore.js'
-import { SEED_RULES } from './policy.js'
+import { SEED_RULES, validMachineRules, type MachineRule } from './policy.js'
import { coordinatorNameOf, FIRST_INSTRUCTIONS, FIRST_SUMMARY, liveNotes, MAX_REVISIONS } from './instructions.js'
import { INSTRUCTIONS_TEMPLATE } from './instructionsTemplate.js'
import { confidentialSessions, otherRegistrations, recordConfidential } from './confidential.js'
@@ -708,6 +708,16 @@ async function outsiderRefusal(state: SuperTabState, userId: string, check: () =
}
}
+/** [projectId]'s machine rules from its newest revision, one indexed read: those that pass, whether or not the rest of the
+ * record does (policy.ts validMachineRules). A rule dropped for failing its schema is logged. */
+async function machineRulesOf(tx: Transaction, tabId: string, projectId: string): Promise<MachineRule[]> {
+ const read = await readRules(tx, tabId, projectId, true)
+ const rules = validMachineRules(read?.rules)
+ const stored = read?.rules.machines
+ if (Array.isArray(stored) && stored.length !== rules.length) logger.warn('[swarm-machine-rules] a rule failed its schema and is not applied', { tabId, projectId })
+ return rules
+}
+
export class SuperTabStore {
/** Where lag-tolerant reads go (SuperTabStoreHooks.replica); the store's own client without one. */
readonly replica: PrismaClient
@@ -2019,6 +2029,12 @@ 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, true)
+ // A start or an assignment meets its project's machine rules (machineRules.ts): one indexed read of the newest revision.
+ // Only the machine rules are read here, so a record broken elsewhere still applies those that pass (security review 1).
+ if (command.type === 'agent.start' || command.type === 'work.assign') {
+ const group = original.conversations.find(c => c.id === (command.type === 'agent.start' ? command.request.conversationId : command.conversationId))
+ if (group) context.projectRules = { revision: 0, rules: { ...SEED_RULES, machines: await machineRulesOf(tx, tabId, groupProject(original, group).id) } }
+ }
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)
@@ -3363,6 +3379,17 @@ export class SuperTabStore {
})
}
+ /** A project's machine rules alone, from its newest revision (policy.ts machines), for the route (task #3964): one
+ * indexed read, never the history, and those that pass even when the rest of the record does not. Who reads the project
+ * reads them, as its record. */
+ async projectMachineRules(user: AuthUser, tabId: string, projectId: string, asAgentId?: string) {
+ return this.instructionHistory(user, tabId, projectId, asAgentId, async tx => {
+ // The rules that pass, from a record that may not, as the server applies them (machineRulesOf).
+ const read = await readRules(tx, tabId, projectId, true)
+ return { projectId, revision: read?.revision ?? 0, machines: validMachineRules(read?.rules) }
+ })
+ }
+
private async instructionHistory<T>(user: AuthUser, tabId: string, projectId: string, asAgentId: string | undefined, read: (tx: Transaction) => Promise<T>) {
return transaction(this.db, async tx => {
const { state } = await this.load(tx, user, tabId)
@@ -4164,8 +4191,13 @@ export class SuperTabStore {
* under the same checks an agent.start meets, Team-account facts read once per sweep. */
private async crewDeps(tx: Transaction, state: SuperTabState, now: number): Promise<CrewDeps> {
const teamMachines = await this.teamMachines(tx, state), otherWorkspaceMachines = await this.otherWorkspaceMachines(tx, state)
- // No machine rules until the project rules record is on main (River, 11-05): then they come from it, never from source.
- return { machineRules: [], admits: (machineId, agent) => {
+ // Each crew project's machine rules from its record (machineRules.ts): one indexed read per project with crew (at most
+ // the Swarm's 100), only in a sweep where a member needs a machine.
+ const rules = new Map<string, readonly MachineRule[]>()
+ for (const projectId of new Set(state.agents.filter(a => a.crew).map(a => agentProjectId(state, a)).filter(id => id !== undefined))) {
+ rules.set(projectId, await machineRulesOf(tx, state.id, projectId))
+ }
+ return { machineRules: projectId => rules.get(projectId) ?? [], admits: (machineId, agent) => {
const pool = state.machines?.find(m => m.machineId === machineId)
const request = pool && crewMoveRequest(state, agent, pool)
if (!request) return false
diff --git a/cli/src/superTabs/machineRules.spec.ts b/cli/src/superTabs/machineRules.spec.ts
new file mode 100644
index 000000000..c72b75eac
--- /dev/null
+++ b/cli/src/superTabs/machineRules.spec.ts
@@ -0,0 +1,19 @@
+import { readFileSync } from 'node:fs'
+import { fileURLToPath } from 'node:url'
+import { describe, expect, it } from 'vitest'
+import { firstMachines, machineRuleRefusal } from './machineRules.js'
+
+// The backend's own cases (backend superTabs/machineRules.cases.json): the route's early filter decides as the server does
+// (security review 1 of #3964).
+const cases = JSON.parse(readFileSync(fileURLToPath(new URL('../../../backend/src/superTabs/machineRules.cases.json', import.meta.url)), 'utf8')) as {
+ rules: Array<Record<string, unknown>>; refusals: Array<{ at: string; machineId: string; engine: string; review: boolean; why: string | null }>
+ first: Array<{ lane: string | null; machines: string[] }> }
+
+describe('the route\'s machine rules', () => {
+ it('refuse as the server does, for each shared case', () => {
+ for (const c of cases.refusals) expect(machineRuleRefusal(cases.rules, c, Date.parse(c.at)), JSON.stringify(c)).toBe(c.why)
+ })
+ it('place a lane\'s work as the server does, for each shared case', () => {
+ for (const c of cases.first) expect([...firstMachines(cases.rules, c.lane)?.machines ?? []]).toEqual(c.machines)
+ })
+})
diff --git a/cli/src/superTabs/machineRules.ts b/cli/src/superTabs/machineRules.ts
new file mode 100644
index 000000000..3ed841b2d
--- /dev/null
+++ b/cli/src/superTabs/machineRules.ts
@@ -0,0 +1,42 @@
+/**
+ * The project's machine rules as the route reads them (task #3964): the record's `machines` list (backend superTabs/policy.ts),
+ * applied as the backend applies them (backend superTabs/machineRules.ts), which refuses the same starts and assignments.
+ * The route only leaves out early what the server would refuse, and ranks a lane's first machine first.
+ */
+type Json = Record<string, unknown>
+
+const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
+const strings = (value: unknown): string[] => Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : []
+const object = (value: unknown): Json => value && typeof value === 'object' && !Array.isArray(value) ? value as Json : {}
+
+/** Whether [rule]'s machine is away at [now]: on one of its weekdays, inside one of its windows, in its own time zone. */
+function away(rule: Json, now: number): boolean {
+ const when = object(rule.away)
+ if (typeof when.timeZone !== 'string' || !Array.isArray(when.days) || !Array.isArray(when.windows)) return false
+ let parts: Record<string, string>
+ try {
+ parts = Object.fromEntries(new Intl.DateTimeFormat('en-US', { timeZone: when.timeZone, weekday: 'short', hour: '2-digit', minute: '2-digit',
+ hourCycle: 'h23' }).formatToParts(new Date(now)).map(p => [p.type, p.value]))
+ } catch { return false }
+ const time = `${parts.hour}:${parts.minute}`
+ return when.days.includes(WEEKDAYS.indexOf(parts.weekday ?? '')) && when.windows.some(w => {
+ const [from, to] = strings(w)
+ return !!from && !!to && time >= from && time < to
+ })
+}
+
+/** Why [work] may not run on its machine at [now] by [rules], or null. */
+export function machineRuleRefusal(rules: readonly Json[], work: { machineId: string; engine: string; review: boolean }, now: number): string | null {
+ for (const rule of rules) {
+ if (!strings(rule.machineIds).includes(work.machineId) || typeof rule.why !== 'string') continue
+ if (strings(rule.noEngines).includes(work.engine) || (rule.noReviews === true && work.review) || away(rule, now)) return rule.why
+ }
+ return null
+}
+
+/** The machines [lane]'s work goes to first by [rules], and the first such rule's why; null for none. */
+export function firstMachines(rules: readonly Json[], lane: string | null): { machines: Set<string>; why: string } | null {
+ if (!lane) return null
+ const named = rules.filter(rule => typeof rule.why === 'string' && strings(object(rule.first).lanes).some(l => l.toLowerCase() === lane.toLowerCase()))
+ return named.length ? { machines: new Set(named.flatMap(rule => strings(rule.machineIds))), why: String(named[0]!.why) } : null
+}
diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.ts
index 1d5be3694..a165c588b 100644
--- a/cli/src/superTabs/routeCommand.spec.ts
+++ b/cli/src/superTabs/routeCommand.spec.ts
@@ -57,8 +57,9 @@ async function withBlocked(os: string, body: () => Promise<void>) {
blocked.push(os)
try { await body() } finally { blocked.splice(blocked.indexOf(os), 1) }
}
-function scoped(answers: { record?: Answer; tab?: unknown; context?: Answer; history?: Answer; instructions?: Answer; historyHangs?: boolean; recordThrows?: boolean; policy?: typeof policy } = {}) {
+function scoped(answers: { record?: Answer; tab?: unknown; context?: Answer; history?: Answer; instructions?: Answer; historyHangs?: boolean; recordThrows?: boolean; policy?: typeof policy; machineRules?: Answer } = {}) {
return vi.fn(async (payload: Record<string, any>): Promise<Record<string, unknown>> => {
+ if (payload.action === 'machineRules') return answers.machineRules ?? { ok: true, value: { projectId: payload.projectId, revision: 0, machines: [] } }
if (payload.action === 'routeContext') return answers.context ?? { ok: true, value: { agentId: 'lead', tab: answers.tab ?? tab(), policy: { policy: answers.policy ?? policy, warnings: ['w'] }, machines: [{ machineId: 'm1', name: 'remote-1' }, { machineId: 'm2', name: 'mac' }] } }
if (payload.action === 'routeHistory') return answers.historyHangs ? new Promise(() => {}) : answers.history ?? { ok: true, value: { decisions: [], attempts: [] } }
if (payload.action === 'instructions') return answers.instructions ?? { ok: true, value: { projectId: 'p1', revision: 2, hash: 'h', text: 'Work by this.', template: false, coordinatorName: 'Ana', notes: [{ id: 'n1', text: 'Be quick', askedBy: 'Ken', at: 't', expiresAt: null }] } }
@@ -113,7 +114,7 @@ describe('routeTask', () => {
const s = scoped()
const result = await routeTask(input, s, where as never, opener(), () => 'op')
expect(result).toMatchObject({ ok: true, routeDecisionId: 'd1', via: 'order', p: null, candidates: expect.arrayContaining([expect.objectContaining({ id: 'c0' })]), warnings: ['w'] })
- expect(s.mock.calls.map(c => c[0].action)).toEqual(['routeContext', 'routeHistory', 'instructions', 'command'])
+ expect(s.mock.calls.map(c => c[0].action)).toEqual(['routeContext', 'routeHistory', 'instructions', 'machineRules', 'command'])
expect(recorded(s).command.decision).not.toHaveProperty('context')
const record = recorded(s)
expect(record).toMatchObject({ operationId: 'route-op', command: { type: 'route.record', conversationId: 'g1' } })
@@ -938,8 +939,8 @@ describe('route answers with the pick (task #3576, after #2901)', () => {
expect(hint).not.toHaveProperty('overrideReason')
expect(next).toContain(`the pick (${(answer.pick as { id: string }).id})`)
expect(next).toMatch(/another candidate.*overrideReason/)
- // Until the machine rules are in the rules record, the pick does not apply them: the instructions' Machines section still does (review 2 of #3296).
- expect(next).toMatch(/Machines rules.*still apply.*pick that breaks one.*overrideReason/s)
+ // The pick applies the project's machine rules from its record (#3964): no line asks the PM to apply them by hand.
+ expect(next).not.toMatch(/still apply/)
})
})
@@ -2498,3 +2499,67 @@ describe('the route answer an agent reads (task #3294)', () => {
})
})
+
+// Task #3964 (part 2 of #3576): the route applies the project's machine rules from its rules record, by machine id.
+describe('the project\'s machine rules in the route', () => {
+ const weekly = { providers: [{ provider: 'claude', outcome: 'answered', httpStatus: 200, account: 'acct', body: {
+ five_hour: { utilization: 40, resets_at: new Date(Date.now() + 3 * 3_600_000).toISOString() },
+ seven_day: { utilization: 25, resets_at: new Date(Date.now() + 4 * 86_400_000).toISOString() } } }] }
+ const open = () => opener(id => daemon(id, { agents: id === 'm1' ? ['h1'] : [], usage: weekly }))
+ type Row = { id: string; machineId: string; title: string }
+ const rulesAnswer = (machines: unknown[]) => ({ ok: true, value: { projectId: 'lead', revision: 1, machines } })
+ const route = async (machines: unknown[] | null, more: { assessment?: Record<string, unknown>; tab?: unknown } = {}) => {
+ const s = scoped({ machineRules: machines ? rulesAnswer(machines) : { error: 'SWARM_BUSY', detail: 'Busy' }, ...more.tab ? { tab: more.tab } : {} })
+ const answer = await routeTask({ ...input, assessment: { ...input.assessment, ...more.assessment } }, s, where as never, open(), () => 'op')
+ return { answer, s, rows: answer.candidates as Row[], machinesOf: () => new Set((answer.candidates as Row[]).map(r => r.machineId)) }
+ }
+ // Every day, all day: the rule holds whenever the spec runs.
+ const always = { days: [0, 1, 2, 3, 4, 5, 6], windows: [['00:00', '23:59']], timeZone: 'UTC' }
+
+ it('reads the rules of the task\'s own project', async () => {
+ const { s } = await route([])
+ expect(s.mock.calls.find(c => c[0].action === 'machineRules')![0]).toMatchObject({ projectId: 'lead' })
+ })
+
+ it('leaves out a machine while it is away, with the rule\'s why', async () => {
+ const before = await route([])
+ expect(before.machinesOf()).toEqual(new Set(['m1', 'm2']))
+ const { answer, machinesOf } = await route([{ machineIds: ['m2'], why: 'Away while its owner travels', away: always }])
+ expect(machinesOf()).toEqual(new Set(['m1']))
+ expect(answer.leftOut).toEqual(expect.arrayContaining([{ machine: 'mac', reasons: expect.arrayContaining([expect.stringContaining('Away while its owner travels')]) }]))
+ })
+
+ it('leaves out an engine a machine refuses, and keeps the others there', async () => {
+ const { rows } = await route([{ machineIds: ['m1'], why: 'No Claude there', noEngines: ['claude'] }])
+ expect(rows.filter(r => r.machineId === 'm1')).toEqual([])
+ expect(rows.some(r => r.machineId === 'm2')).toBe(true)
+ })
+
+ it('leaves out a machine where no Reviewer runs for a review, and only for a review', async () => {
+ const rule = [{ machineIds: ['m1'], why: 'Its Codex defaults to a local model', noReviews: true }]
+ expect((await route(rule, { assessment: { kind: 'review' } })).machinesOf().has('m1')).toBe(false)
+ expect((await route(rule, { assessment: { kind: 'test' } })).machinesOf().has('m1')).toBe(true)
+ expect((await route(rule)).machinesOf().has('m1')).toBe(true)
+ })
+
+ it('picks a lane\'s first machine over an equal other, and says so', async () => {
+ const plain = await route([])
+ const picked = (a: Answer) => (a.candidates as Row[]).find(r => r.id === (a.pick as { id: string }).id)!.machineId
+ const other = picked(plain.answer) === 'm1' ? 'm2' : 'm1'
+ const phone = { revision: 3, state: { id: 'tab', agents, conversations: conversations().map(c => c.id === 'g1' ? { ...c, handOutLane: 'mobile' } : c) } }
+ const { answer } = await route([{ machineIds: [other], why: 'The phone setup is there', first: { lanes: ['mobile'] } }], { tab: phone })
+ expect(picked(answer)).toBe(other)
+ expect((answer.reasons as string[])[0]).toContain('The phone setup is there')
+ // Another lane's task is not moved.
+ expect(picked((await route([{ machineIds: [other], why: 'The phone setup is there', first: { lanes: ['mobile'] } }])).answer)).toBe(picked(plain.answer))
+ })
+
+ it('says the instructions\' Machines rules still apply when the rules cannot be read, and no longer when they are', async () => {
+ const unread = await route(null)
+ expect(unread.machinesOf()).toEqual(new Set(['m1', 'm2']))
+ expect(unread.answer.warnings).toEqual(expect.arrayContaining([expect.stringMatching(/machine rules could not be read.*Machines rules.*still apply/)]))
+ expect(String(unread.answer.next)).toMatch(/Machines rules.*still apply/s)
+ const read = await route([])
+ expect(String(read.answer.next)).not.toMatch(/still apply/)
+ })
+})
diff --git a/cli/src/superTabs/routeCommand.ts b/cli/src/superTabs/routeCommand.ts
index 7f796730e..566a22d39 100644
--- a/cli/src/superTabs/routeCommand.ts
+++ b/cli/src/superTabs/routeCommand.ts
@@ -12,6 +12,7 @@ import { ENDED_WORK, object, within } from './wire.js'
import { withPmAccounts } from './pmAccounts.js'
import { accountOf, API_BUILDERS, bytes, machineBrief, catalogFrom, catalogRow, choose, decideByOrder, gridStrength, parseAssessment, OLD_RECORD_MAX, quotaBrief, quotaLine, quotaOf2, recentStartNotes, UNRATED, recordOf, repoMatch, repositoryKey, type Assessment, type Catalog, type CatalogModel, type RecordShape, type Commitment, type Excluded, type Shown, type HeldModel, type MemberFrame, type Probe, type TaskFolder } from './route.js'
import { pickByOrder } from './routePick.js'
+import { firstMachines, machineRuleRefusal } from './machineRules.js'
import { makePlugins, ROUTE_PLUGIN_MAKERS, type PluginMaker } from './routePlugins.js'
import { CI_HOLD_OPENING, CI_RETRY_MINUTES, heavyOfStart, MACHINE_FIT_MAKER } from './machineFit.js'
import { stat } from 'node:fs/promises'
@@ -24,6 +25,8 @@ const ENGINES = ['claude', 'codex']
const TRANSPORT = new Set(['AGENT_UNAVAILABLE', 'SUPER_TAB_UNAVAILABLE', 'BACKEND_UNAVAILABLE', 'BACKEND_TIMEOUT', 'BACKEND_UNREACHABLE'])
const MACHINES_UNREADABLE = "The account's machine list could not be read; only known machines were considered."
/** An unreadable catalog reads as an empty one (route.ts catalogFrom), which offers no new agent: said, never silent (final review). */
+/** The project's machine rules could not be read (task #3964): the route applies none, so the PM still does. */
+export const MACHINE_RULES_UNREAD = 'The project\'s machine rules could not be read: the instructions\' Machines rules still apply, and a pick that breaks one is not used.'
export const CATALOG_UNREADABLE = 'The model catalog could not be read, or lists no models: no new agent on Claude Code or Codex is offered, only agents already in the Swarm and models served on its grid.'
const DISK_UNVERIFIED = 'Project disk space could not be verified.'
const NO_PROJECT_FOLDER = 'This machine does not have the project folder. Add it to the Swarm so it can clone the project.'
@@ -448,7 +451,7 @@ export async function routeTask(input: { tabId: string; conversationId: string;
// member is in the task's repository, what it did before) is joined afterwards.
// The plug-ins' makers start here too: each piece's outside read runs beside the probes, and they share the history read.
const historyRead = within(scoped({ action: 'routeHistory', conversationId: input.conversationId }))
- const [probed, read, history, instructed, made] = await Promise.all([
+ const [probed, read, history, instructed, made, ruleRead] = await Promise.all([
Promise.all([...machines].map(([machineId, machine]) =>
probeMachine(machineId, machine, members.filter(m => m.machineId === machineId), rows, catalog, assessment, where, open))),
cwd ? within(readFolder(cwd, reader)) : null,
@@ -456,7 +459,10 @@ export async function routeTask(input: { tabId: string; conversationId: string;
// The project's instructions ride on the answer: the agent routes by them. A backend without them is an unreadable read.
within(scoped({ action: 'instructions', projectId })),
makePlugins(makers, { conversationId: input.conversationId, assessment, read: value, catalog, history: historyRead, request: scoped }),
+ // The project's machine rules from its record (task #3964); unreadable, the route says the instructions' still apply.
+ within(scoped({ action: 'machineRules', projectId })),
])
+ const machineRules = ruleRead?.ok === true && Array.isArray(object(ruleRead.value).machines) ? list(object(ruleRead.value).machines) : null
const written = object(instructed?.ok === true ? instructed.value : {})
const instructions = typeof written.text === 'string' ? { revision: written.revision, text: written.text, notes: Array.isArray(written.notes) ? written.notes : [] } : null
const folder: TaskFolder | null = !cwd ? null : read ?? { cwd, kind: 'unknown', name: null, root: null, remote: null }
@@ -514,8 +520,18 @@ export async function routeTask(input: { tabId: string; conversationId: string;
// A model a host now offline served is left out with that reason, and a person naming it gets no stand-in (route.ts choose).
const offline = offlineModels(state)
const now = Date.now()
+ // What the server refuses by the project's machine rules is left out with the rule's why, on the machine named or its Mac.
+ const review = /(^|-)review(-|$)/.test(assessment.kind ?? '')
+ for (const [i, p] of probes.entries()) {
+ const why = [p.machineId, macOf.get(p.machineId)].flatMap(machineId => machineId ? [machineRuleRefusal(machineRules ?? [], { machineId, engine: p.engine, review }, now)] : [])
+ .find(w => w !== null)
+ if (why) probes[i] = { ...p, refusals: [...p.refusals, why] }
+ }
+ // A lane's work goes first to its machines: the task's own lane, or a step's task's.
+ const ownTask = group.reviewOf ? conversations.find(c => c.id === group.reviewOf) : group
+ const first = firstMachines(machineRules ?? [], text(group.handOutLane) ?? text(ownTask?.handOutLane) ?? null)
const choice = choose(probes, catalog, { ...assessment, ended: endedAttempts(group, attempts) }, now, working, heldLocalModels(state), offline, made.plugins)
- const skipped = [...made.warnings, ...(choice.warnings ?? [])]
+ const skipped = [...made.warnings, ...(choice.warnings ?? []), ...(machineRules ? [] : [MACHINE_RULES_UNREAD])]
choice.excluded.push(...offline, ...(catalog.models.length ? [] : [{ title: 'New agents', reason: CATALOG_UNREADABLE }]))
// The task stays in the agent's queue rather than going where it cannot be done.
// Work that starts heavy CI while the account is at its limit waits, and says when to route it again (machineFit.ts), so the
@@ -526,7 +542,7 @@ export async function routeTask(input: { tabId: string; conversationId: string;
...ciHeld ? { waiting: true, retryAfterMinutes: CI_RETRY_MINUTES, detail: ciHeld.reason.slice(MACHINE_FIT_MAKER.name.length + 2) } : {} }
// The pick by the project's Routing order (routePick.ts, task #3576): the recorded candidate that start or assignment follows.
const verdict = decideByOrder(choice, pickByOrder({ shown: choice.shown, catalog, assessment: { ...assessment, ended: endedAttempts(group, attempts) }, now,
- conversationId: input.conversationId }))
+ conversationId: input.conversationId, ...first ? { first: { machines: new Set([...first.machines, ...[...macOf].filter(([, mac]) => first.machines.has(mac)).map(([id]) => id)]), why: first.why } } : {} }))
const operationId = `route-${newId()}`
// The rows recorded are the rows offered: the agent choosing assigns by a recorded candidate.
let offered = choice.shown
@@ -576,20 +592,22 @@ export async function routeTask(input: { tabId: string; conversationId: string;
...(catalog.models.length ? [] : [CATALOG_UNREADABLE]),
...(choice.shown.some(p => p.kind === 'member' && p.terminalUnverified) ? ["A member's terminal could not be verified from its machine's snapshot. Check it before assignment."] : []),
...(choice.short ? [choice.short] : []), ...skipped],
- next: nextOf(shownRows, input.conversationId, typeof routeDecisionId === 'string' ? routeDecisionId : undefined, !!instructions, assessment.needs, verdict.pick),
+ next: nextOf(shownRows, input.conversationId, typeof routeDecisionId === 'string' ? routeDecisionId : undefined, !!instructions, assessment.needs, verdict.pick, !!machineRules),
}
}
/** How to act on the route: the candidates are in no order of merit (task #2901), so it names none. A member is assigned, a new
* agent started, each with the chosen row's own fields; RULE is the Routing rule that chose it, which the backend asks for
* with a decision that has no pick, and the start or assignment records the candidate it matches. */
-function nextOf(rows: Shown[], conversationId: string, routeDecisionId: string | undefined, instructions: boolean, needs: Assessment['needs'], pick?: string): string {
+function nextOf(rows: Shown[], conversationId: string, routeDecisionId: string | undefined, instructions: boolean, needs: Assessment['needs'], pick?: string,
+ machineRulesRead = false): string {
// Said once and short (task #3294): it rode on every route, 467 a day in one PM's context.
const choose = pick
? `Use the pick (${pick}), chosen by the project's Routing order: start or assign it as listed, with no overrideReason. `
- + 'The pick does not apply the instructions\' Machines rules (hours a machine is off, phone work on the phone Mac, no Codex on a named Mac, no reviewing on a local-model Codex): '
- + 'they still apply, and a pick that breaks one is not used; choose another candidate and give that rule as overrideReason. '
- + 'For any other candidate, give the reason as overrideReason (urgency, context, a machine the work needs; "idle" is not one).'
+ // The pick applies the machine rules from the project's record (task #3964); unread, the instructions' still apply.
+ + (machineRulesRead ? '' : 'The project\'s machine rules could not be read, so the pick does not apply them: the instructions\' Machines rules '
+ + 'still apply, and a pick that breaks one is not used; choose another candidate and give that rule as overrideReason. ')
+ + 'For another candidate, give the reason as overrideReason (urgency, context, a machine the work needs; "idle" is not one).'
: 'Not ranked: listed by machine name. Choose one by the project\'s Routing instructions (Order and quota), and give the rule that chose it as overrideReason.'
const decided = routeDecisionId ? pick ? { routeDecisionId } : { routeDecisionId, overrideReason: 'RULE' } : {}
const assign = `Assign a member: command OPERATION_ID ${JSON.stringify({ type: 'work.assign', conversationId, agentId: 'AGENT', ...decided })}`
diff --git a/cli/src/superTabs/routePick.ts b/cli/src/superTabs/routePick.ts
index 5986dc653..d71a1c713 100644
--- a/cli/src/superTabs/routePick.ts
+++ b/cli/src/superTabs/routePick.ts
@@ -23,7 +23,9 @@ export const PM_RESERVE = 20
/** Efforts below high, which no agent runs at. */
const BELOW_HIGH = new Set(['minimal', 'low', 'medium'])
-export interface PickInput { shown: readonly Shown[]; catalog: Catalog; assessment: Assessment; now: number; conversationId: string }
+/** `first`: the machines the task's lane goes to first by the project's machine rules (machineRules.ts), and why. */
+export interface PickInput { shown: readonly Shown[]; catalog: Catalog; assessment: Assessment; now: number; conversationId: string
+ first?: { machines: ReadonlySet<string>; why: string } }
export interface Picked { id: string; reasons: string[] }
const kindIs = (a: Assessment, word: string) => new RegExp(`(^|-)${word}(-|$)`).test(a.kind ?? '')
@@ -32,7 +34,7 @@ const span = (ms: number) => ms >= D ? `${Math.round(ms / D)}d` : `${Math.max(1,
interface Ranked { p: Shown; need: number; left: number | null; resetsAt: number | null; follows: boolean }
-export function pickByOrder({ shown, catalog, assessment: a, now, conversationId }: PickInput): Picked | null {
+export function pickByOrder({ shown, catalog, assessment: a, now, conversationId, first }: PickInput): Picked | null {
const tier: Tier | null = tierOf(a)
const review = kindIs(a, 'review'), test = kindIs(a, 'test')
const named = !!a.model || !!a.local
@@ -66,8 +68,11 @@ export function pickByOrder({ shown, catalog, assessment: a, now, conversationId
return r.left >= needs && !(runsPm(r.p) && r.left < PM_RESERVE)
})
if (!usable.length) return null
- const best = Math.min(...usable.map(r => r.need))
- const pool = usable.filter(r => r.need === best)
+ // The machine the work needs: a lane's first machine, while one there can take it (project's machine rules, task #3964).
+ const there = first ? usable.filter(r => first.machines.has(r.p.machineId)) : []
+ const placed = there.length ? there : usable
+ const best = Math.min(...placed.map(r => r.need))
+ const pool = placed.filter(r => r.need === best)
const unread = (r: Ranked) => r.left === null ? 1 : 0
const byAccount = (x: Ranked, y: Ranked) => unread(x) - unread(y) || (x.resetsAt ?? Infinity) - (y.resetsAt ?? Infinity) || (y.left ?? 0) - (x.left ?? 0)
@@ -81,7 +86,7 @@ export function pickByOrder({ shown, catalog, assessment: a, now, conversationId
const reasons = [
`1. Need: ${win.p.title} ${win.p.gridModel ? 'is a grid model, free, for small work' : tier === null ? 'runs the work (no size given)'
: win.need === 0 ? `is the ${tier === 'strong' ? (review ? 'strong model a review needs' : 'strong model for big, hard or risky work') : 'model for small work'}`
- : 'is the closest fit to the model the work needs'}.`,
+ : 'is the closest fit to the model the work needs'}.${there.length ? ` On ${win.p.machineName}, where this lane's work goes first: ${first!.why}.` : ''}`,
win.p.gridModel || win.p.quota.metered ? '2. Quota: it uses no subscription.'
: win.left === null ? `2. Quota: weekly unknown; no account with a reading has the ${pct(needs)} the work needs.`
: `2. Quota: weekly ${pct(win.left)} left${win.resetsAt === null ? '' : `, resets in ${span(Math.max(0, win.resetsAt - now))}`}`
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index 1decd64d9..95b4fe20f 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -769,6 +769,11 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
throw error
}
}
+ // The project's machine rules alone, for the route (backend machine-rules read, task #3964).
+ if (payload.action === 'machineRules') {
+ if (!identifier(payload.projectId)) return { error: 'INVALID_REQUEST' }
+ return { ok: true, value: await backend(core, 'GET', `${path}/projects/${encodeURIComponent(String(payload.projectId))}/machine-rules?${identity}`) }
+ }
if (payload.action === 'decisions' && (payload.state === 'open' || payload.state === 'answered')) {
return { ok: true, value: await backend(core, 'GET', `${path}/decisions?state=${payload.state}&${identity}`) }
}
diff --git a/cli/src/superTabs/serviceReads.spec.ts b/cli/src/superTabs/serviceReads.spec.ts
index 440cbcd1a..03abfb2e0 100644
--- a/cli/src/superTabs/serviceReads.spec.ts
+++ b/cli/src/superTabs/serviceReads.spec.ts
@@ -173,6 +173,17 @@ describe('decisions', () => {
})
})
+describe('machineRules', () => {
+ // Task #3964: the route reads the project's machine rules alone, as that agent.
+ it('reads the project\'s machine rules as the agent, and refuses a project that is not an id', async () => {
+ const read = { projectId: FIXTURE.projectId, revision: 2, machines: [{ machineIds: ['m1'], why: 'No Codex there', noEngines: ['codex'] }] }
+ const s = swarm((method, path) => path.startsWith(`/api/super-tabs/${T}/projects/${FIXTURE.projectId}/machine-rules?`) ? ok(read) : undefined)
+ expect(await s.ask({ action: 'machineRules', tabId: T, agentId: FIXTURE.leadId, projectId: FIXTURE.projectId }, owner)).toEqual({ ok: true, value: read })
+ expect(s.call).toHaveBeenCalledWith('GET', `/api/super-tabs/${T}/projects/${FIXTURE.projectId}/machine-rules?asAgentId=${FIXTURE.leadId}`, undefined)
+ expect(await s.ask({ action: 'machineRules', tabId: T, agentId: FIXTURE.leadId, projectId: '../x' }, owner)).toMatchObject({ error: 'INVALID_REQUEST' })
+ })
+})
+
describe('instructions', () => {
const document = { projectId: FIXTURE.projectId, revision: 3, hash: 'h', text: 'Work by this.', template: false, coordinatorName: 'Ana', notesRevision: 1, notes: [] }
const instructionsPath = (projectId: string, agentId: string) => `/api/super-tabs/${T}/projects/${projectId}/instructions?asAgentId=${agentId}`
diff --git a/docs/plans/2026-11-06-machine-rules-plan.md b/docs/plans/2026-11-06-machine-rules-plan.md
new file mode 100644
index 000000000..ca17d1146
--- /dev/null
+++ b/docs/plans/2026-11-06-machine-rules-plan.md
@@ -0,0 +1,99 @@
+# The route applies the four machine rules from the project's rules: 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:** The four Machines rules of the project's Routing instructions run as code from the project's rules record, not
+from text the PM applies by hand (task #3964, part 2 of #3576, requested by ken15 through Harness):
+
+1. a machine is away on some weekdays between some local times: nothing starts or is handed work there then;
+2. phone app work runs on a named machine first (its "at most 4 agents there" is that machine's own agent limit,
+ which the Swarm already keeps: no second way);
+3. no agent of a named engine runs on a named machine;
+4. no Reviewer runs on a named machine.
+
+**Builds on:** #3296 (the route's pick by the Routing order), on its branch until it merges.
+
+**Architecture:** The record (policy.ts `ProjectRules`) gains `machines`, a list of machine rules by machine id, written by
+the people who write the rest of it (rules.set, unchanged rights). Machine ids and hours are project data, never source
+(River, 11-05). One pure module, `machineRules.ts`, says why a machine refuses a piece of work now
+(`machineRuleRefusal`, replacing crewKeep.ts's) and which machines a lane's work goes to first (`firstMachines`). The backend
+applies it where it hands out work:
+
+- `agent.start` refuses a new agent a rule forbids (`MACHINE_RULE`, with the rule's why);
+- `work.assign` refuses work a rule forbids for that agent's machine (a review step on a no-Reviewer machine, anything on an
+ away machine);
+- lane dispatch (dispatch.ts `candidatesFor`) skips what a rule refuses, and leaves a first-machine lane's task to a free
+ member there while one takes it;
+- the crew keeper's moves (crewKeep.ts) read each crew project's rules, as their comment waited for;
+- the route (cli/src/superTabs/routeCommand.ts) reads the rules alone (`GET …/projects/:id/machine-rules`, new: the newest
+ revision by one indexed read, never the 50-revision history), leaves out each candidate a rule refuses with its why, and
+ ranks a lane's first machine first in step 1 of the order (routePick.ts). A no-Reviewer rule refuses reviews only: a Test
+ step is not a review.
+
+**Tech Stack:** TypeScript backend and CLI, vitest.
+
+## Global Constraints
+
+- No change to who may set the rules. Old clients keep working: a save without `machines` keeps the current ones; a record
+ without them has no machine rule.
+- The server enforces the rules; the route only shows them.
+- Swarm code stays out of cli/src/core. Temp files only in `mktemp -d` folders.
+
+## Design
+
+- growth: at most 50 machine rules per project, inside the record's 16 KB, kept with its 50 revisions (policyStore.ts).
+- concurrency: rules.set's revision check, as today; starts and assignments read the current revision in their transaction.
+- read cost: `agent.start` and `work.assign` add one indexed read of the newest revision (as `conversation.create` does);
+ dispatch reads it once per project per pass, as today; the crew sweep one per crew project, only when a member needs a
+ machine; the route one indexed read of the newest revision, beside its other reads.
+- scale: 10x starts is 10x one indexed row read; the warn line is the start's p95.
+- compatibility: the backend ships first. An older CLI route does not read the rules and still lists a refused candidate;
+ the server refuses its start with the why. An older client saving the record without `machines` keeps them. This CLI
+ against an older backend gets a 404 for the rules read: it says the instructions' Machines rules still apply.
+- migration + rollback: none; a record without `machines` has none. Rolled back after a save with `machines`, the older
+ strict schema reads that revision as invalid (`RULES_INVALID`) until someone saves the rules again without them (its repair
+ path): so nobody saves machine rules until this backend has stayed out a day. Stated in the PR.
+- audience: the record is read by who reads the project today; machine ids are already in the Swarm read.
+- identity: N/A because nothing runs as anyone new.
+- failure: every refusal names the rule's why; a rules read that fails keeps the route's candidates and says so.
+- platforms: backend; the CLI route on macOS, Linux and Windows.
+
+## Review Focus
+
+- A record without `machines`, and an old client's save, behave exactly as before.
+- Away hours in the rule's time zone, on its weekdays only.
+- No path hands out work a rule refuses: start, assign, dispatch.
+
+## Task 1: the record holds machine rules
+
+**Files:** backend/src/superTabs/{policy.ts, crewRules.ts, commands.ts}, policy.test.ts, commands.test.ts
+
+- [x] Test: the record accepts each of the four kinds and refuses a bad one (time, zone, engine); a save without `machines`
+ keeps the current ones; one with `[]` clears them.
+- [x] Watch it fail; commit. Code; watch it pass; commit.
+
+## Task 2: why a machine refuses work, and where a lane goes first
+
+**Files:** backend/src/superTabs/{machineRules.ts, crewKeep.ts}, machineRules.test.ts
+
+- [x] Test per rule: away inside and outside its window and day, in its zone; an engine refused; a review refused; a lane's
+ first machines.
+- [x] Watch it fail; commit. Code; watch it pass; commit.
+
+## Task 3: starts, assignments and dispatch follow the rules
+
+**Files:** backend/src/superTabs/{commands.ts, store.ts, dispatch.ts}, machineRules.commands.test.ts, dispatch.test.ts
+
+- [x] Test: each rule refuses the start or assignment it names, with its why; dispatch skips it; a phone task waits for the
+ phone machine's free member and goes to another only when none is free.
+- [x] Watch it fail; commit. Code; watch it pass; commit.
+
+## Task 4: the route's candidates follow the rules (CLI; the PM kept it in this task, 11-06)
+
+**Files:** backend/src/{routes/superTabs.ts, superTabs/store.ts} (the machine-rules read), integration/superTabProjectRules.test.ts;
+cli/src/superTabs/{machineRules.ts, service.ts, routeCommand.ts, routePick.ts}, routeCommand.spec.ts, serviceReads.spec.ts
+
+- [x] Test: each rule leaves out the candidate it refuses, with its why; the lane's first machine is picked over an equal
+ other; a rules read that fails leaves the candidates as before and says so.
+- [x] Watch it fail; commit. Code; watch it pass; commit.