The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Merge batch 11-06 k0450: #3267 #3273 (#3280)
0xken1598d59fcfeb54
diff --git a/backend/integration/superTabInstructions.test.ts b/backend/integration/superTabInstructions.test.tsindex 6572ea7ba..d5f56e967 100644--- a/backend/integration/superTabInstructions.test.ts+++ b/backend/integration/superTabInstructions.test.ts@@ -9,6 +9,7 @@ import { PrismaClient } from '@prisma/client'import Fastify, { type FastifyInstance } from 'fastify'import type { AuthUser } from '../src/lib/ssoAuth.js'import { SuperTabStore } from '../src/superTabs/store.js'+import { noteChange, swarmTransaction } from '../src/superTabs/cache.js'import { superTabRoutes } from '../src/routes/superTabs.js'import { errorHandler } from '../src/middlewares/errorHandler.js'import type { Command } from '../src/superTabs/commands.js'@@ -519,30 +520,81 @@ describe('the migration job', () => {})// Task #3392 (anh Dee, 11-05, decision 5): a person's rule may move into a code task, its line staying until that task merges.-// A merged task goes quiet after a day, out of the Swarm a command loads: the save names it, and the store loads it.-describe('a rule moved into a code task that went quiet', () => {- it('counts once the save names the merged task, and not before', async () => {+// Task #3463 (review of #3220): merged as GitHub itself dates it, after the rule went into the task, read by the store at the+// save, so it works with tidying off; a merged task gone quiet counts once the save names it.+describe('a rule moved into a code task', () => {+ const PR = 'https://github.com/acme/app/pull/7'+ const leo = 'A bug that reaches stable ships its fix the same day (peer, 2026-11-04).'+ const doc = (...rules: string[]) => ['# Project instructions', '', '## Rules', '', ...rules.map(r => `- ${r}`)].join('\n')+ /** A Swarm whose project's repository is acme/app, tidying off, its instructions keeping peer's rule; a store whose GitHub+ * says what [merges] holds; and a code task carrying the rule, linking PR. */+ async function moved(carried = leo, repositoryUrl = 'https://github.com/acme/app') {+ const merges: Record<string, number | null> = {}, read: string[][] = []+ const github = new SuperTabStore(db, () => now, null, { pullRequestMerges: async (_env, _tab, _project, urls) => {+ read.push(urls)+ return Object.fromEntries(urls.filter(url => url in merges).map(url => [url, merges[url]!]))+ } })const { tab, lead } = await withLead()- const quiet = 'No releases between 18:00 and 09:00 Vietnam time (owner, 2026-11-02).'- const doc = (...rules: string[]) => ['# Project instructions', '', '## Rules', '', ...rules.map(r => `- ${r}`)].join('\n')- await run(tab, save(1, doc(quiet, 'Tests run first.')))- const task = (await run(tab, { type: 'conversation.create', title: 'Release guard', brief: `Goal:\nBlock night releases.\n\nChanges:\n- ${quiet}`,+ await invite(tab)+ await swarmTransaction(db, async tx => {+ const head = await tx.swarmHead.findUniqueOrThrow({ where: { id: `${tab}:head` } }), data = head.data as { projects?: Array<{ id: string }> }+ const repository = { machineId: 'test-host', cwd: '/repo', repositoryUrl }+ await tx.swarmHead.update({ where: { id: head.id }, data: { version: head.version + 1, data: (data.projects+ ? { ...data, projects: data.projects.map(p => p.id === 'lead' ? { ...p, repository } : p) } : { ...data, project: repository }) as object } })+ noteChange(tx, tab, 'main')+ })+ await run(tab, { type: 'tab.tidy', enabled: false })+ await run(tab, save(1, doc(leo, 'Tests run first.')))+ const task = (await run(tab, { type: 'conversation.create', title: 'Stable fixes', brief: `Goal:\nSame-day fixes.\n\nChanges:\n- ${carried}`,checks: [] })).result.conversationId as string- const drop = (tasks?: string[]) => run(tab, { type: 'instructions.save', projectId: 'lead', baseRevision: 2, text: doc('Tests run first.'),- summary: 'Moved the release rule to its task', askedBy: owner.sub, ...tasks ? { tasks } : {} }, host, lead)- // Open: the line stays until the task merges.- await expect(drop()).rejects.toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED', details: { dropped: [{ why: 'waiting' }] } })- // Its own merge record is no merge (River, review of #3220): only what the Swarm read on GitHub is.- const part = await db.swarmGroup.findFirstOrThrow({ where: { tabId: tab, key: task } })- const data = part.data as { ledger?: object }- await db.swarmGroup.update({ where: { id: part.id }, data: { version: { increment: 1 },- data: { ...data, ledger: { ...data.ledger, mergedAt: now, shippedAt: now } } } })- await expect(drop()).rejects.toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED', details: { dropped: [{ why: 'waiting' }] } })- // Seen merged on GitHub (store.ts archiveFinished), then quiet: out of the command's load unless the save names it.- const seen = await db.swarmGroup.findFirstOrThrow({ where: { tabId: tab, key: task } })- await db.swarmGroup.update({ where: { id: seen.id }, data: { dormant: true, version: { increment: 1 },- data: { ...seen.data as object, dormant: true, mergeSeen: { 'https://github.com/acme/app/pull/7': now } } } })- await expect(drop()).rejects.toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED', details: { dropped: [{ why: 'removed' }] } })- expect((await drop([task])).result).toMatchObject({ revision: 3 })+ // The PM records the merge with a link: its word alone frees nothing (River, review of #3220).+ await run(tab, { type: 'conversation.merged', conversationId: task, pullRequestUrl: PR }, host, lead)+ const briefAt = (await db.swarmGroup.findFirstOrThrow({ where: { tabId: tab, key: task } })).data as { briefAt?: number }+ const drop = (tasks?: string[]) => github.execute(owner, tab, { operationId: randomUUID(), command: { type: 'instructions.save', projectId: 'lead',+ baseRevision: 2, text: doc('Tests run first.'), summary: 'Moved the stable rule to its task', ...tasks ? { tasks } : {} } })+ return { tab, task, merges, read, drop, briefAt: briefAt.briefAt! }+ }++ it('leaves, with tidying off, once GitHub says the task merged after the move, and not for an older merge', async () => {+ const m = await moved()+ expect(m.briefAt).toBe(now)+ // GitHub: not merged. The line stays, naming the task.+ m.merges[PR] = null+ await expect(m.drop()).rejects.toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED', details: { dropped: [{ why: 'waiting' }] } })+ expect(m.read.at(-1)).toEqual([PR])+ // Merged, but before the rule went into the task: it never carried it.+ m.merges[PR] = m.briefAt - 60_000+ await expect(m.drop()).rejects.toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED', details: { dropped: [{ why: 'waiting' }] } })+ // Merged after: the person's save drops the line, though no archive pass ever ran.+ m.merges[PR] = m.briefAt + 60_000+ expect((await m.drop()).result).toMatchObject({ revision: 3 })+ })++ // Review 2 of #3273: a project whose repository is not on GitHub has no GitHub merge of its own; a GitHub link frees nothing.+ it('frees nothing for a project whose repository is not on GitHub, whatever a linked GitHub pull request did', async () => {+ const m = await moved(leo, 'https://gitlab.com/acme/app')+ m.merges[PR] = m.briefAt + 60_000+ await expect(m.drop()).rejects.toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED', details: { dropped: [{ why: 'waiting' }] } })+ expect(m.read).toEqual([])+ })++ // Review 1 of #3273: the brief wraps the rule as the instructions wrap theirs, at 120 columns.+ it('reads the merge of a task that carries the rule across wrapped lines', async () => {+ const m = await moved('A bug that reaches stable ships its fix\n the same day (peer, 2026-11-04).')+ m.merges[PR] = m.briefAt + 60_000+ expect((await m.drop()).result).toMatchObject({ revision: 3 })+ expect(m.read.at(-1)).toEqual([PR])+ })++ it('counts a merged task that went quiet once the save names it', async () => {+ const m = await moved()+ m.merges[PR] = m.briefAt + 60_000+ const part = await db.swarmGroup.findFirstOrThrow({ where: { tabId: m.tab, key: m.task } })+ await swarmTransaction(db, async tx => {+ await tx.swarmGroup.update({ where: { id: part.id }, data: { dormant: true, version: part.version + 1, data: { ...part.data as object, dormant: true } } })+ noteChange(tx, m.tab, 'main')+ })+ await expect(m.drop()).rejects.toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED', details: { dropped: [{ why: 'removed' }] } })+ expect((await m.drop([m.task])).result).toMatchObject({ revision: 3 })})})diff --git a/backend/integration/superTabReleases.test.ts b/backend/integration/superTabReleases.test.tsindex 8bfffec1e..3d81c35c5 100644--- a/backend/integration/superTabReleases.test.ts+++ b/backend/integration/superTabReleases.test.ts@@ -70,12 +70,14 @@ describe('releases scheduled by the Swarm', () => {const url = 'https://github.com/example/app/pull/41'await s.run({ type: 'conversation.merged', conversationId: shipIt, pullRequestUrl: url, mergedAt: new Date(T - 30 * MINUTE).toISOString() }, host, s.lead)expect((await s.ledger())!.pending).toEqual([{ groupId: shipIt, url, mergedAt: T - 30 * MINUTE }])+ expect((await s.group(shipIt)).releasing).toEqual([])// After 18:00: the release shipped it, and no step opens.s.clock.set(T + 8 * 60 * MINUTE)const outcome = await s.store.settleReleases(s.tab, 'lead', { resolved: [{ groupId: shipIt, url, components: ['desktop'], sha: 'm41' }],releases: { desktop: { tag: 'v1.3.78_desktop', sha: 'd1', at: T - 5 * MINUTE, carries: [pendingKey({ groupId: shipIt, url })] } } })expect(outcome).toMatchObject({ shipped: [shipIt], opened: null })expect((await s.group(shipIt)).released).toEqual({ at: T - 5 * MINUTE, tags: ['v1.3.78_desktop'] })+ expect(await s.group(shipIt)).not.toHaveProperty('releasing')expect((await s.ledger())!.pending).toEqual([])})diff --git a/backend/integration/superTabTidy.test.ts b/backend/integration/superTabTidy.test.tsindex c9ab72344..f53c4e71c 100644--- a/backend/integration/superTabTidy.test.ts+++ b/backend/integration/superTabTidy.test.ts@@ -292,20 +292,6 @@ describe('a finished group', () => {}const isArchived = async (f: Awaited<ReturnType<typeof swarm>>, key: string) => (await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key } })).archived- // Task #3392 (River, review of #3220): a person's rule moved into a code task may leave the instructions once that task- // merged, and only the Swarm's own read of GitHub says so: what the archive read merged in the project's repository.- it('records which of its pull requests GitHub says merged in its project\'s repository, and no other', async () => {- const f = await swarm()- const task = await cancelledIn(f, 'Shipped in the batch')- const ours = 'https://github.com/acme/app/pull/41', closed = 'https://github.com/acme/app/pull/42', theirs = 'https://github.com/other/app/pull/43'- await f.execute({ type: 'message.send', conversationId: task, text: `Pull requests: ${ours} ${closed} ${theirs}`, replyTo: null, recipientIds: [] })- f.clock.now += 40 * MINUTE- await archiveFinishedGroups(db, f.timed, github({ [ours]: 'merged', [closed]: 'closed', [theirs]: 'merged' }), f.clock.now)- const data = (await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: task } })).data as { archived: boolean; mergeSeen?: Record<string, number> }- expect(data.archived).toBe(true)- expect(data.mergeSeen).toEqual({ [ours]: f.clock.now })- })-// Diego, 11-04 (#2602): another repository's number, read in this one, kept the task open forever.it('waits on no "PR #N" another repository\'s name sits next to', async () => {const f = await swarm()diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex 81a8b4e6e..720aeaac4 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -1,3 +1,4 @@+import { appPullRequestMerges } from '../superTabs/ruleMoves.js'import { declaredHttpClient } from '../superTabs/refusalLog.js'import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'import { z, ZodError } from 'zod'@@ -273,6 +274,8 @@ async function productionStore(github: GitHubTokens | null, approvals: Approvals// A team account has no git login of its own: without the app it takes no teammates' work.teamAccountsIdle: !github,...(github ? { pushOrigin: projectPushOrigin(github.app), branchPushOrigin: projectBranchOrigin(github.app) } : {}),+ // When a moved rule's task merged, as GitHub dates it, read at the instructions save (superTabs/ruleMoves.ts, task #3463).+ ...(github ? { pullRequestMerges: (_env: string, _tab: string, _project: string, urls: string[]) => appPullRequestMerges(github.app)(urls) } : {}),// A task's Ready reads the files its pull requests change, and the server opens its review steps from them (task #3401)....(github ? { pullRequestFiles: projectPullRequestFiles(github.app) } : {}),// A start or assignment its account cannot reach the repository from is refused at once, by the read Project detailsdiff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.tsindex f2c825641..a173f5591 100644--- a/backend/src/superTabs/commands.test.ts+++ b/backend/src/superTabs/commands.test.ts@@ -5029,6 +5029,7 @@ describe('linked tasks', () => {const list = () => groupProject(f.state, f.state.conversations.find(c => c.id === R)!).releases?.pendingf.run({ type: 'conversation.merged', conversationId: R, pullRequestUrl: url, mergedAt: new Date(900).toISOString() }, E)expect(list()).toEqual([{ groupId: R, url, mergedAt: 900 }])+ expect(f.state.conversations.find(c => c.id === R)!.releasing).toEqual([])f.run({ type: 'conversation.merged', conversationId: R, pullRequestUrl: url, mergedAt: new Date(900).toISOString() }, E)expect(list()).toHaveLength(1)})diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 74dee5ce8..39b8ad49f 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -595,6 +595,9 @@ export interface CommandContext {shown?: string[] }/** For `instructions.save`: the project's stored document, read by the store, which a stale save hands back to merge. */instructions?: { revision: number; text: string; at?: number } | null+ /** For an instructions.save: when GitHub says each pull request linked to a task the save may move a rule into merged+ * (ms), null when it did not; one GitHub could not answer for is absent (store.ts pullRequestMergesFor, #3463). */+ pullRequestMerges?: Readonly<Record<string, number | null>>/** For `instructions.save`: the messages it names as approvals, loaded by id in this tab by the store (ruleGuard.ts). */approvals?: ApprovalRow[]/** For `rules.set`, and for a task's Ready whose pull request files were read (its review table plans the steps, #3401):@@ -2066,7 +2069,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,refuseOverBudget(before, command.text)// A person's rule, or who gave it, is dropped only by that person or with their own message approving it (#3151).const { told, rules } = allowedDrops(state, project, before, command.text, sender, command.approvals ?? [], context.approvals ?? [],- context.instructions?.at ?? 0)+ context.instructions?.at ?? 0, context.pullRequestMerges ?? {})// Every line it dropped, with its kind and who gave it, kept with the revision for the History (River, 11-05).saveInstructions(project, current, command.text, command.summary, askedBy, droppedLines(before, command.text, command.dropped ?? [], rules))// The coordinator's save that says it is the tidy is that tidy done (pmSchedule.ts tidyRequest); a correction it saves@@ -2564,7 +2567,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,// A task lists its steps from its start (#3394): only a task from before lists none, which its PR watch looks up once....(!command.reviewOf && !command.audience ? { stepIds: [] } : {}),number, title: command.title, leadId, agentIds: [...leadId ? [leadId] : [], ...creator],- archived: false, brief, ...(command.task ? { task: command.task } : {}), ...(command.reviewOf ? { reviewOf: command.reviewOf } : {}),+ archived: false, brief, ...(brief ? { briefAt: context.now } : {}), ...(command.task ? { task: command.task } : {}), ...(command.reviewOf ? { reviewOf: command.reviewOf } : {}),// A step keeps its task's mark (teamWritten.ts, audit H2). Opening a task writes none of its code (#3304)....(command.reviewOf ? stepMark(state, conversation(state, command.reviewOf)) : {}),...(command.step ? { step: command.step } : {}),@@ -4008,6 +4011,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,group.brief = command.task ? renderWorkTask(command.task) : command.brief!if (command.task) group.task = command.taskelse delete group.task+ group.briefAt = context.nowstampLane(group)group.checks = storedChecks(command.checks, operationId)message(group.id, group.brief, [], null, SYSTEM_ROW)diff --git a/backend/src/superTabs/instructions.test.ts b/backend/src/superTabs/instructions.test.tsindex 10fa8e9d4..fdff74ea8 100644--- a/backend/src/superTabs/instructions.test.ts+++ b/backend/src/superTabs/instructions.test.ts@@ -5,6 +5,8 @@ import { appendRouting, instructionsHash, legacyRoleName, MAX_INSTRUCTIONS_BYTESimport type { SwarmProject } from './projects.js'import { INSTRUCTIONS_TEMPLATE, TEMPLATE_WORKFLOW } from './instructionsTemplate.js'import { budgetParts, INSTRUCTIONS_BUDGET } from './instructionsDiff.js'+import { tasksHoldingMoves } from './ruleGuard.js'+import { projectsOf } from './projects.js'import { hostTab } from './read/hostRows.js'import { FIRST_INSTRUCTIONS } from './instructions.js'@@ -780,15 +782,16 @@ describe('an instructions save may move a person\'s rule', () => {return { f, lead }}const PR = 'https://github.com/acme/app/pull/7'- /** A code task of the project whose brief carries [line]; [merged]: GitHub, read by the Swarm itself, saw its pull request- * merge (store.ts archiveFinished), as no command can say. */- function codeTask(f: ReturnType<typeof fixture>, line: string, merged: boolean) {+ /** A code task of the project whose brief carries [line], set at 1000 (the fixture's clock), linking [PR]. */+ function codeTask(f: ReturnType<typeof fixture>, line: string) {const id = f.run({ type: 'conversation.create', title: 'Release guard', brief: `Goal:\nBlock releases at night.\n\nChanges:\n- ${line}`, checks: [] }).result.conversationId as stringconst group = f.state.conversations.find(c => c.id === id)!- if (merged) group.mergeSeen = { [PR]: 900 }+ group.pullRequestUrls = [PR]return group}+ /** What the store read of GitHub before the save (store.ts pullRequestMergesFor): [PR] merged at [at]. */+ const mergedAt = (at: number) => ({ pullRequestMerges: { [PR]: at } })it('lets a rule move word for word into people notes', () => {const { f, lead } = pm()@@ -805,26 +808,76 @@ describe('an instructions save may move a person\'s rule', () => {it('lets a rule move into a code task once it merged, and keeps the line while the task is open, naming it', () => {const { f, lead } = pm()- const open = codeTask(f, quiet, false)+ const open = codeTask(f, quiet)const refused = refusal(() => f.run(save(1, doc(leo)), as(lead), stored()))expect(refused).toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED', details: { dropped: [{ rule: quiet, people: ['owner'], why: 'waiting',movedTo: `task #${open.number}` }] } })expect(refused.message).toContain(`task #${open.number}`)expect(refused.message).toContain('until it merges')- open.mergeSeen = { [PR]: 900 }- expect(f.run(save(1, doc(leo)), as(lead), stored()).result.revision).toBe(2)+ expect(f.run(save(1, doc(leo)), as(lead), { ...stored(), ...mergedAt(1500) }).result.revision).toBe(2)+ })++ // Task #3463 (review of #3220): only work merged after the rule went into the task frees it, as GitHub itself dates the merge.+ it('keeps the line for a pull request of the task that merged before the rule went into it', () => {+ const { f, lead } = pm()+ const task = codeTask(f, quiet)+ expect(task.briefAt).toBe(1000)+ expect(refusal(() => f.run(save(1, doc(leo)), as(lead), { ...stored(), ...mergedAt(900) })))+ .toMatchObject({ details: { dropped: [{ rule: quiet, why: 'waiting', movedTo: `task #${task.number}` }] } })+ // Defined again later, carrying the rule: a merge between the two briefs is older than the move too.+ f.run({ type: 'work.define', conversationId: task.id, brief: `Changes:\n- ${quiet}`, checks: [] }, owner, { now: 2000 })+ expect(f.state.conversations.find(c => c.id === task.id)!.briefAt).toBe(2000)+ expect(refusal(() => f.run(save(1, doc(leo)), as(lead), { ...stored(), ...mergedAt(1500) }))).toMatchObject({ details: { dropped: [{ why: 'waiting' }] } })+ expect(f.run(save(1, doc(leo)), as(lead), { ...stored(), ...mergedAt(2500) }).result.revision).toBe(2)+ })++ // Review 1 of #3273: the save reads the merges of the tasks the guard's own matcher finds a dropped rule in, not only those+ // whose brief holds the line's text as written.+ it('names the tasks a dropped rule moved into as the guard reads them: across wrapped lines, and one rule of a line of two', () => {+ const { f } = pm()+ const wrapped = codeTask(f, 'No releases between 18:00 and 09:00\n Vietnam time (owner, 2026-11-02).')+ const other = codeTask(f, 'Something else entirely (owner, 2026-11-01).')+ const project = projectsOf(f.state)[0]!+ expect(tasksHoldingMoves(f.state, project, doc(leo, quiet), doc(leo)).map(t => t.id)).toEqual([wrapped.id])+ // A line of two people's rules, of which only peer's moves into the task.+ const pair = `${quiet} ${leo}`+ const moved = codeTask(f, leo)+ expect(tasksHoldingMoves(f.state, project, doc(pair), doc(quiet)).map(t => t.id)).toEqual([moved.id])+ expect(tasksHoldingMoves(f.state, project, doc(leo, quiet), doc(leo, quiet))).toEqual([])+ // The unrelated task is never named.+ expect(tasksHoldingMoves(f.state, project, doc(leo, quiet), doc(leo)).map(t => t.id)).not.toContain(other.id)+ })++ // Review 2 of #3273: the first look reads words as the guard does, whatever their case or the formatting around them.+ it('names a task that carries the rule in other capitals or with emphasis', () => {+ const { f } = pm()+ const shouted = codeTask(f, 'NO releases between 18:00 and 09:00 Vietnam time (owner, 2026-11-02).')+ const emphasised = codeTask(f, '**No releases** between 18:00 and 09:00 Vietnam time (owner, 2026-11-02).')+ const project = projectsOf(f.state)[0]!+ expect(tasksHoldingMoves(f.state, project, doc(leo, quiet), doc(leo)).map(t => t.id).sort()).toEqual([shouted.id, emphasised.id].sort())+ })++ // Review 2 of #3273, round 3: whatever the guard accepts as the moved rule (filler words, word endings), the save reads.+ it('names a task the guard reads the rule in through filler words and word endings', () => {+ const { f } = pm()+ const project = projectsOf(f.state)[0]!+ const windowRule = 'The release window closes at 18:00 Vietnam time (owner, 2026-11-02).'+ const noFiller = codeTask(f, 'Release window closes at 18:00 Vietnam time (owner, 2026-11-02).')+ expect(tasksHoldingMoves(f.state, project, doc(leo, windowRule), doc(leo)).map(t => t.id)).toEqual([noFiller.id])+ const singular = codeTask(f, 'No release between 18:00 and 09:00 Vietnam time (owner, 2026-11-02).')+ expect(tasksHoldingMoves(f.state, project, doc(leo, quiet), doc(leo)).map(t => t.id)).toContain(singular.id)})// River, 11-05 (review of #3220): a task's own merge record is any agent's word, with any pull request link. Only the// Swarm's own read of GitHub makes a moved rule's task merged.it('takes no task\'s merge record for a merge: a forged one keeps the line', () => {const { f, lead } = pm()- const task = codeTask(f, quiet, false)+ const task = codeTask(f, quiet)f.run({ type: 'conversation.merged', conversationId: task.id, pullRequestUrl: PR }, as(lead))expect(f.state.conversations.find(c => c.id === task.id)!.ledger?.mergedAt).toBeDefined()expect(refusal(() => f.run(save(1, doc(leo)), as(lead), stored()))).toMatchObject({ details: { dropped: [{ rule: quiet, why: 'waiting' }] } })- // Nor can any command write what the Swarm saw.- expect(() => f.run({ type: 'conversation.create', title: 'Forged', brief: `Changes:\n- ${quiet}`, checks: [], mergeSeen: { [PR]: 1 } } as never, as(lead))).toThrow()+ // Nor can any command write when a brief was set.+ expect(() => f.run({ type: 'conversation.create', title: 'Forged', brief: `Changes:\n- ${quiet}`, checks: [], briefAt: 1 } as never, as(lead))).toThrow()})it('still refuses a real drop, a move without who gave it, and a move into a cancelled task, saying how a rule may move', () => {@@ -834,9 +887,9 @@ describe('an instructions save may move a person\'s rule', () => {expect(refused.message).toContain('people notes')expect(refused.message).toContain('rules record')expect(refused.message).toContain('code task')- codeTask(f, 'No releases between 18:00 and 09:00 Vietnam time.', true)- expect(refusal(() => f.run(save(1, doc(leo)), as(lead), stored()))).toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED' })- const cancelled = codeTask(f, quiet, false)+ codeTask(f, 'No releases between 18:00 and 09:00 Vietnam time.')+ expect(refusal(() => f.run(save(1, doc(leo)), as(lead), { ...stored(), ...mergedAt(1500) }))).toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED' })+ const cancelled = codeTask(f, quiet)cancelled.assignment = { status: 'cancelled' } as neverexpect(refusal(() => f.run(save(1, doc(leo)), as(lead), stored()))).toMatchObject({ details: { dropped: [{ why: 'removed' }] } })})diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex 27090fe50..dfa411ed5 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -420,10 +420,10 @@ export interface Conversation {heardAt?: number/** Linked GitHub pull requests, including links older than the latest message page. Absent in older snapshots. */pullRequestUrls?: string[]- /** Its pull requests the Swarm itself read as merged on GitHub in its project's repository, by link: when it read them- * (store.ts archiveFinished). Unlike the merge record (conversation.merged, any agent's word), no command writes it; it- * is what makes a person's rule moved into this task leave the instructions (ruleGuard.ts, #3392). */- mergeSeen?: Record<string, number>+ /** When its brief was last set (conversation.create, work.define): a person's rule moved into this task leaves the+ * instructions only for a pull request GitHub says merged after it (ruleGuard.ts rulePlaces, #3463). No command writes+ * it otherwise. Absent on a task from before. */+ briefAt?: number/** What its Engineer was already told of each linked pull request, newest first (pullRequestEvents.ts): absent until read. */pullRequestEvents?: Record<string, string[]>/** Each linked pull request's head and patch id as the PR watch last read them (#3394): what check verdicts count against.@@ -467,6 +467,9 @@ export interface Conversation {/** When a verified release carried its last recorded merge to people, and the release tags that did (releases.ts, task #3405):* the board's Shipped. Absent while a release it needs has not gone out, and on work merged before the server recorded it. */released?: { at: number; tags: string[] }+ /** While it is on its project's release list (releases.ts): the parts it still waits for, as `desktop` or `cli`; empty until+ * its pull request's files are read. Absent otherwise, and cleared once it is released or leaves the list (River, 11-05). */+ releasing?: import('./releases.js').ReleaseComponentId[]/** Whether its task is moving, waiting on purpose or stuck, as the time checks last found it (liveness.ts recordTaskStates). */liveness?: TaskLiveness/** Its last step up from a cheaper model: written when a grid attempt's first review fails (commands.ts reviewFailed, goalsdiff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.tsindex 9bc5ffb1e..f785e8573 100644--- a/backend/src/superTabs/parts/light.test.ts+++ b/backend/src/superTabs/parts/light.test.ts@@ -35,6 +35,7 @@ const conversation: Required<Conversation> = {assignment,audience: { people: [] },brief: '',+ briefAt: 1,buddyDownTold: true,buddyName: 'Sparky',buddySessions: [],@@ -56,7 +57,6 @@ const conversation: Required<Conversation> = {ledger: {},liveness: { state: 'quiet', why: 'silent', since: 1 },lostAttempt: { id: 'w', agentId: 'a' },- mergeSeen: {},messageSeq: 0,notBefore: '2026-12-04',number: 1,@@ -72,6 +72,7 @@ const conversation: Required<Conversation> = {queueRank: 1.5,reactionSeq: 0,released: { at: 1, tags: [] },+ releasing: ['cli'],reportSeq: 0,requesterId: 'p',reviewOf: 'r',diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.tsindex ba1729ca2..25aaecc57 100644--- a/backend/src/superTabs/parts/light.ts+++ b/backend/src/superTabs/parts/light.ts@@ -64,6 +64,7 @@ export const GROUP_FIELDS = {'assignment.toldEngineerAt','assignment.verdicts','brief',+ 'briefAt','buddyDownTold','buddyName','buddySessions',@@ -81,7 +82,6 @@ export const GROUP_FIELDS = {'ledger','liveness','lostAttempt',- 'mergeSeen','messageSeq','notBefore','number',@@ -95,6 +95,7 @@ export const GROUP_FIELDS = {'queueRank','reactionSeq','released',+ 'releasing','reportSeq','requesterId','reviewStamp',diff --git a/backend/src/superTabs/releaseWatch.test.ts b/backend/src/superTabs/releaseWatch.test.tsindex e2ab41525..a270d94e2 100644--- a/backend/src/superTabs/releaseWatch.test.ts+++ b/backend/src/superTabs/releaseWatch.test.ts@@ -162,6 +162,10 @@ describe('watchReleases', () => {const s = scene({ pending: [], steps: { cli: { groupId: 's', at: T } } })await watchReleases(s.db, s.store, s.fake, T, { warn: () => {}, info: () => {} })expect(s.read).toEqual(['latest cli', 'done'])+ // A list whose only work is clearing tasks the cap pushed off still settles, with nothing to read from GitHub.+ const leaving = scene({ pending: [], leaving: ['g9'] })+ await watchReleases(leaving.db, leaving.store, leaving.fake, T, { warn: () => {}, info: () => {} })+ expect(leaving.settled.map(x => x.projectId)).toEqual(['p1'])const quiet = scene({ pending: [] })await watchReleases(quiet.db, quiet.store, quiet.fake, T, { warn: () => {}, info: () => {} })expect(quiet.settled).toEqual([])diff --git a/backend/src/superTabs/releaseWatch.ts b/backend/src/superTabs/releaseWatch.tsindex 6ecb761bc..e4b420a51 100644--- a/backend/src/superTabs/releaseWatch.ts+++ b/backend/src/superTabs/releaseWatch.ts@@ -182,7 +182,7 @@ export async function watchReleases(db: PrismaClient, store: Pick<SuperTabStore,for (const project of projectsOf(head.data as unknown as SuperTabState).filter(p => projectIds.includes(p.id))) {const ledger = project.releasesconst repository = githubRepository(project.repository?.repositoryUrl)- if (!ledger || !repository || (!ledger.pending.length && !Object.keys(ledger.steps ?? {}).length)) continue+ if (!ledger || !repository || (!ledger.pending.length && !Object.keys(ledger.steps ?? {}).length && !ledger.leaving?.length)) continuetry {const facts: ReleaseFacts = { resolved: [], releases: {} }let unread = 0diff --git a/backend/src/superTabs/releases.test.ts b/backend/src/superTabs/releases.test.tsindex 9e47c8fe9..b8db637a8 100644--- a/backend/src/superTabs/releases.test.ts+++ b/backend/src/superTabs/releases.test.ts@@ -3,7 +3,7 @@ import type { Agent, Conversation, SuperTabState } from './model.js'import type { SwarmProject } from './projects.js'import { missingContract } from './taskContract.js'import { backendPaused, compareTags, componentsOf, inReleaseWindow, isReleaseTag, notePendingRelease, PENDING_MAX, RELEASE_COMPONENTS, RELEASE_RULES,- pendingKey, releaseDue, settleReleases, PENDING_MS, shipped, waitingFor, type PendingRelease, type ReleaseLedger } from './releases.js'+ ledgerGroupIds, pendingKey, releaseDue, settleReleases, PENDING_MS, shipped, waitingFor, type PendingRelease, type ReleaseLedger } from './releases.js'/** A time in Vietnam (UTC+7, no daylight saving) on 6 November 2026. */const vn = (hour: number, minute = 0) => Date.UTC(2026, 10, 6, hour - 7, minute)@@ -112,6 +112,12 @@ describe('shipping', () => {describe('notePendingRelease', () => {const project = () => ({ id: 'p1' }) as SwarmProject+ it('marks the task releasing, its parts not known yet', () => {+ const p = project(), group = { id: 'a' } as Conversation+ notePendingRelease(p, group, 'https://github.com/o/r/pull/1', vn(10))+ expect(group.releasing).toEqual([])+ })+it('adds a merge once, oldest first', () => {const p = project()notePendingRelease(p, { id: 'b' }, 'https://github.com/o/r/pull/2', vn(11))@@ -126,6 +132,16 @@ describe('notePendingRelease', () => {const dropped = notePendingRelease(p, { id: 'late' }, 'https://github.com/o/r/pull/999', vn(12))expect(dropped.map(e => e.groupId)).toEqual(['g0'])expect(p.releases!.pending).toHaveLength(PENDING_MAX)+ // Review of #3267: the merge's write may not hold the task it pushed out, so the next settle clears its releasing.+ expect(p.releases!.leaving).toEqual(['g0'])+ })++ it('names no task as leaving while another of its merges is still on the list', () => {+ const p = project()+ notePendingRelease(p, { id: 'g0' }, 'https://github.com/o/r/pull/1', vn(9))+ for (let i = 1; i < PENDING_MAX; i++) notePendingRelease(p, { id: i === 1 ? 'g0' : `g${i}` }, `https://github.com/o/r/pull/${i + 1}`, vn(10) + i)+ notePendingRelease(p, { id: 'late' }, 'https://github.com/o/r/pull/999', vn(12))+ expect(p.releases!.leaving).toBeUndefined()})})@@ -156,11 +172,17 @@ describe('settleReleases', () => {it('marks a task released once every release it needs carries it, and takes it off the list', () => {const state = swarm([entry({ groupId: 'g12', mergedAt: T - 20 * MINUTE, components: ['desktop', 'web'] })])+ const group = () => state.conversations.find(c => c.id === 'g12')!+ settleReleases(state, 'p1', { resolved: [], releases: {} }, vn(20))+ // River, 11-05: while on the list a task says which parts it still waits for, for the board's "merged, releasing".+ expect(group().releasing).toEqual(['desktop', 'web'])const first = settleReleases(state, 'p1', { resolved: [], releases: { desktop: desktopRelease() } }, T)expect(first.shipped).toEqual([])+ expect(group().releasing).toEqual(['web'])expect(ledgerOf(state).pending[0]!.shippedIn).toEqual({ desktop: 'v1.3.78_desktop' })const second = settleReleases(state, 'p1', { resolved: [], releases: { desktop: desktopRelease(), web: webRelease } }, T)expect(second.shipped).toEqual(['g12'])+ expect(group()).not.toHaveProperty('releasing')expect(state.conversations.find(c => c.id === 'g12')!.released).toEqual({ at: T - 5 * MINUTE, tags: ['v1.3.78_desktop', 'v1.3.98_web'] })expect(ledgerOf(state).pending).toEqual([])})@@ -175,9 +197,11 @@ describe('settleReleases', () => {it('ships work that changed no released part at its merge', () => {const state = swarm([entry({ groupId: 'g13', url: 'https://github.com/o/r/pull/13', mergedAt: T - MINUTE, components: undefined })])+ state.conversations.find(c => c.id === 'g13')!.releasing = []const outcome = settleReleases(state, 'p1', { resolved: [{ groupId: 'g13', url: 'https://github.com/o/r/pull/13', components: [] }], releases: {} }, vn(20))expect(outcome.shipped).toEqual(['g13'])expect(state.conversations.find(c => c.id === 'g13')!.released).toEqual({ at: T - MINUTE, tags: [] })+ expect(state.conversations.find(c => c.id === 'g13')).not.toHaveProperty('releasing')})it('opens one release step for the Integrator inside the window, and no second one while it is open', () => {@@ -244,9 +268,20 @@ describe('settleReleases', () => {expect(ledgerOf(state).last!.desktop!.tag).toBe('v1.3.78_desktop')})+ it('loads and clears the tasks the cap pushed off the list', () => {+ const state = swarm([], { leaving: ['g12'] })+ state.conversations.find(c => c.id === 'g12')!.releasing = ['desktop']+ expect(ledgerGroupIds(ledgerOf(state))).toEqual(['g12'])+ settleReleases(state, 'p1', noFacts, vn(20))+ expect(state.conversations.find(c => c.id === 'g12')).not.toHaveProperty('releasing')+ expect(ledgerOf(state)).not.toHaveProperty('leaving')+ })+it('drops a merge no release carried in 14 days', () => {const state = swarm([entry({ groupId: 'g12', mergedAt: T - PENDING_MS - 1, components: ['desktop'] })])+ state.conversations.find(c => c.id === 'g12')!.releasing = ['desktop']expect(settleReleases(state, 'p1', noFacts, vn(20)).dropped.map(e => e.groupId)).toEqual(['g12'])+ expect(state.conversations.find(c => c.id === 'g12')).not.toHaveProperty('releasing')expect(ledgerOf(state).pending).toEqual([])})})diff --git a/backend/src/superTabs/releases.ts b/backend/src/superTabs/releases.tsindex e291e24ec..045ab2f31 100644--- a/backend/src/superTabs/releases.ts+++ b/backend/src/superTabs/releases.ts@@ -78,7 +78,14 @@ export function compareTags(a: string, b: string): number {* release (done, cancelled or archived: the release may still be running). */export interface ReleaseStep { groupId: string; at: number; endedAt?: number }/** A project's release list (SwarmProject.releases). The server alone writes it; readers never get it. */-export interface ReleaseLedger { pending: PendingRelease[]; last?: Partial<Record<ReleaseComponentId, VerifiedRelease>>; steps?: Partial<Record<ReleaseComponentId, ReleaseStep>> }+export interface ReleaseLedger { pending: PendingRelease[]; last?: Partial<Record<ReleaseComponentId, VerifiedRelease>>; steps?: Partial<Record<ReleaseComponentId, ReleaseStep>>+ /** Tasks the cap pushed off the list with no other merge left on it: the merge's write may not hold them, so the next settle+ * loads them and clears their `releasing` (review of #3267). */+ leaving?: string[] }++/** The groups a settle of [ledger] loads: the tasks waiting, the open release steps, the tasks leaving. */+export const ledgerGroupIds = (ledger: ReleaseLedger): string[] =>+ [...new Set([...ledger.pending.map(e => e.groupId), ...Object.values(ledger.steps ?? {}).map(s => s!.groupId), ...ledger.leaving ?? []])]/** At most this many tasks wait on a project's list; the oldest leaves first, with a warning. */export const PENDING_MAX = 100@@ -105,12 +112,18 @@ export const shipped = (entry: PendingRelease): boolean => !!entry.components &&/** Puts [group]'s merge of [url] at [mergedAt] on [project]'s release list, in the merge record's own write. The same merge* recorded again adds nothing; a later merge of the same task waits on its own. Returns the entries the cap pushed out. */-export function notePendingRelease(project: SwarmProject, group: Pick<Conversation, 'id'>, url: string, mergedAt: number): PendingRelease[] {+export function notePendingRelease(project: SwarmProject, group: Pick<Conversation, 'id' | 'releasing'>, url: string, mergedAt: number): PendingRelease[] {const ledger = project.releases ??= { pending: [] }if (ledger.pending.some(e => e.groupId === group.id && e.url === url)) return []+ // Releasing from its merge on; its parts are known once the worker reads its pull request's files.+ group.releasing ??= []ledger.pending.push({ groupId: group.id, url, mergedAt })ledger.pending.sort((a, b) => a.mergedAt - b.mergedAt)- return ledger.pending.length > PENDING_MAX ? ledger.pending.splice(0, ledger.pending.length - PENDING_MAX) : []+ const dropped = ledger.pending.length > PENDING_MAX ? ledger.pending.splice(0, ledger.pending.length - PENDING_MAX) : []+ for (const { groupId } of dropped) {+ if (!ledger.pending.some(e => e.groupId === groupId) && !ledger.leaving?.includes(groupId)) (ledger.leaving ??= []).push(groupId)+ }+ return dropped}/** How long a step that ended without a verified release still holds its component: a release workflow that is still@@ -175,6 +188,8 @@ export function settleReleases(state: SuperTabState, projectId: string, facts: Rconst fresh = ledger.pending.filter(e => e.mergedAt > now - PENDING_MS)outcome.dropped = ledger.pending.filter(e => !fresh.includes(e))ledger.pending = fresh+ const left = new Set<string>([...outcome.dropped.map(e => e.groupId), ...ledger.leaving ?? []])+ delete ledger.leavingfor (const component of RELEASE_COMPONENTS) {const read = facts.releases[component.id]@@ -206,8 +221,23 @@ export function settleReleases(state: SuperTabState, projectId: string, facts: Rgroup.released = { at, tags }outcome.shipped.push(group.id)}+ left.add(entry.groupId)return false})+ // What each task still waits for, across its merges still on the list; none left, and it is releasing no more.+ const waits = new Map<string, Set<ReleaseComponentId>>()+ for (const entry of ledger.pending) {+ const parts = waits.get(entry.groupId) ?? new Set<ReleaseComponentId>()+ for (const c of entry.components ?? []) if (!entry.shippedIn?.[c]) parts.add(c)+ waits.set(entry.groupId, parts)+ }+ for (const groupId of new Set([...left, ...waits.keys()])) {+ const group = state.conversations.find(c => c.id === groupId)+ const parts = waits.get(groupId)+ if (!group) continue+ if (parts) group.releasing = RELEASE_COMPONENTS.filter(c => parts.has(c.id)).map(c => c.id)+ else delete group.releasing+ }for (const component of RELEASE_COMPONENTS) {const step = ledger.steps?.[component.id]diff --git a/backend/src/superTabs/ruleGuard.ts b/backend/src/superTabs/ruleGuard.tsindex 69cc31460..ee043e449 100644--- a/backend/src/superTabs/ruleGuard.ts+++ b/backend/src/superTabs/ruleGuard.ts@@ -45,17 +45,45 @@ const WHY: Record<DroppedRule['why'], string> = {* request merged on GitHub. A task that went* quiet is in the state only when the save names it (tasks), which loads it.*/-function rulePlaces(state: SuperTabState, project: SwarmProject): RulePlace[] {- // Merged only as the Swarm itself read it on GitHub (Conversation.mergeSeen), never by the task's own merge record, which- // any agent of the project writes with any link (River, review of #3220).- const seenMerged = (c: Conversation) => Object.keys(c.mergeSeen ?? {}).length > 0+function rulePlaces(state: SuperTabState, project: SwarmProject, merges: Readonly<Record<string, number | null>>): RulePlace[] {+ // Merged only as GitHub itself says, read by the store before this save ([merges]), never by the task's own merge record,+ // which any agent of the project writes with any link (River, review of #3220); and only after the rule went into its brief+ // (briefAt): an older merge never carried it (#3463). A task from before briefAt counts any merge, as it did.+ const seenMerged = (c: Conversation) => (c.pullRequestUrls ?? []).some(url => {+ const at = merges[url]+ return typeof at === 'number' && (c.briefAt === undefined || at > c.briefAt)+ })const records = projectRules(state, project.id).map(r => ({ text: r.text, people: [r.askedBy], where: 'the rules record', open: false }))- const tasks = state.conversations.filter(c => (c.projectId ?? 'lead') === project.id && c.id !== project.leadConversationId && !c.kind- && !c.reviewOf && !c.step && !c.audience && c.brief && (seenMerged(c) || c.assignment?.status !== 'cancelled'))+ const tasks = codeTasks(state, project).filter(c => seenMerged(c) || c.assignment?.status !== 'cancelled').map(c => ({ text: c.brief, people: [], where: c.number ? `task #${c.number}` : `task "${c.title}"`, open: !seenMerged(c) }))return [...records, ...tasks]}+/** The project's code tasks: its tasks with a brief, not a step, a chat or a private chat (rulePlaces, tasksHoldingMoves). */+const codeTasks = (state: SuperTabState, project: SwarmProject): Conversation[] => state.conversations.filter(c => (c.projectId ?? 'lead') === project.id+ && c.id !== project.leadConversationId && !c.kind && !c.reviewOf && !c.step && !c.audience && !!c.brief)++/** How the guard tells people apart in this Swarm: a written name as the members it is, so "0xken15" and "Ken" are one. */+function identifier(state: SuperTabState): (name: string) => string {+ const membersOf = new Map<string, string[]>()+ return name => (membersOf.get(name) ?? membersOf.set(name, membersNamed(state, name)).get(name)!).slice().sort().join(',') || `?${personKey(name)}`+}++/**+ * The project's code tasks a save from [before] to [after] would move a person's rule into, as the guard itself reads a move+ * (droppedRules): each task alone, counted open, that holds a rule the save drops, across wrapped lines or as one rule of a+ * line of several, with the guard's own words (filler words, word endings: review 2 of #3273). The store reads their pull+ * requests' merges before the save (store.ts pullRequestMergesFor, #3463). It runs only for a save that drops a person's rule,+ * once per code task: a few dozen in a project.+ */+export function tasksHoldingMoves(state: SuperTabState, project: SwarmProject, before: string, after: string): Conversation[] {+ const identify = identifier(state)+ const lost = droppedRules(before, after, identify)+ if (!lost.length) return []+ return codeTasks(state, project).filter(task =>+ droppedRules(before, after, identify, [{ text: task.brief, people: [], where: task.id, open: true }]).some(rule => rule.movedTo === task.id))+}+/*** The rules [after] drops from [before] that their people allowed, by the person to tell, and those rules: refused with the* list when any is not allowed. A person allows their rule by making the save themselves (no notice: they know) or by a@@ -64,12 +92,11 @@ function rulePlaces(state: SuperTabState, project: SwarmProject): RulePlace[] {* several people needs each of them. A name that is no member is the project owner's to allow.*/export function allowedDrops(state: SuperTabState, project: SwarmProject, before: string, after: string, sender: { kind: Author['kind']; id: string },- named: readonly string[], approvals: readonly ApprovalRow[], since: number): { told: Map<string, DroppedRule[]>; rules: DroppedRule[] } {+ named: readonly string[], approvals: readonly ApprovalRow[], since: number, merges: Readonly<Record<string, number | null>> = {}): { told: Map<string, DroppedRule[]>; rules: DroppedRule[] } {const told = new Map<string, DroppedRule[]>()const membersOf = new Map<string, string[]>()const members = (name: string) => membersOf.get(name) ?? membersOf.set(name, membersNamed(state, name)).get(name)!- // One written person for comparing revisions: the members they are, so "0xken15" and "Ken" are one.- const dropped = droppedRules(before, after, name => members(name).sort().join(',') || `?${personKey(name)}`, rulePlaces(state, project))+ const dropped = droppedRules(before, after, identifier(state), rulePlaces(state, project, merges))if (!dropped.length) return { told, rules: [] }const saver = sender.kind === 'person' ? sender.id : undefined// Written after the revision this save replaces, in a conversation of this project: an old "thanks" approves nothing (reviewdiff --git a/backend/src/superTabs/ruleMoves.test.ts b/backend/src/superTabs/ruleMoves.test.tsnew file mode 100644index 000000000..8b891c074--- /dev/null+++ b/backend/src/superTabs/ruleMoves.test.ts@@ -0,0 +1,75 @@+import { describe, expect, it, vi } from 'vitest'+import { appPullRequestMerges, pullRequestMerges, type PullGet } from './ruleMoves.js'+import { logger } from '../utils/logger.js'++// Task #3463: when a moved rule's task merged is GitHub's own date, read by the server (ruleMoves.ts).+describe('the merge times read on GitHub for a moved rule', () => {+ const answers: Record<string, { status: number; body: unknown }> = {+ 'acme/app#7': { status: 200, body: { state: 'closed', merged_at: '2026-11-06T03:00:00Z' } },+ 'acme/app#8': { status: 200, body: { state: 'closed', merged_at: null } },+ 'acme/app#9': { status: 200, body: { state: 'open', merged_at: null } },+ 'acme/app#10': { status: 502, body: null },+ }+ const asked: string[] = []+ const get: PullGet = async (repository, number) => {+ asked.push(`${repository.fullName}#${number}`)+ return answers[`${repository.fullName}#${number}`] ?? { status: 404, body: { message: 'Not Found' } }+ }++ it('takes GitHub\'s merge date, says not merged for a closed or open one, and leaves out what GitHub could not answer', async () => {+ const pr = (n: number) => `https://github.com/acme/app/pull/${n}`+ expect(await pullRequestMerges([pr(7), pr(8), pr(9), pr(10), pr(11), 'https://github.com/acme/app/issues/3'], get)).toEqual({+ [pr(7)]: Date.parse('2026-11-06T03:00:00Z'), [pr(8)]: null, [pr(9)]: null,+ })+ // A link that is no pull request is never asked about.+ expect(asked).not.toContain('acme/app#3')+ })+})++describe('the GitHub App reader of merge times', () => {+ it('uses one read-only token per repository, revokes it even when a read fails, and logs every read it could not make', async () => {+ const warn = vi.spyOn(logger, 'warn').mockImplementation(() => logger)+ const app = {+ installation: vi.fn(async (repository: { fullName: string }) => repository.fullName === 'acme/app' ? 11 : null),+ createToken: vi.fn(async () => ({ token: 'secret-token' })),+ get: vi.fn(async (path: string) => {+ if (path.endsWith('/pulls/7')) return { status: 200, body: { merged_at: '2026-11-06T03:00:00Z' } }+ if (path.endsWith('/pulls/9')) return { status: 502, body: null }+ throw new Error('socket hang up')+ }),+ revoke: vi.fn(async () => {}),+ }+ const read = await appPullRequestMerges(app as never)(['https://github.com/acme/app/pull/7', 'https://github.com/acme/app/pull/8',+ 'https://github.com/acme/app/pull/9', 'https://github.com/other/app/pull/1'])+ expect(read).toEqual({ 'https://github.com/acme/app/pull/7': Date.parse('2026-11-06T03:00:00Z') })+ expect(app.createToken).toHaveBeenCalledTimes(1)+ // Read-only: pull requests and metadata, nothing else.+ expect(app.createToken).toHaveBeenCalledWith(11, expect.objectContaining({ fullName: 'acme/app' }), { pull_requests: 'read', metadata: 'read' })+ expect(app.revoke).toHaveBeenCalledTimes(1)+ expect(app.revoke).toHaveBeenCalledWith('secret-token')+ // Each read it could not make says so, by repository, number and status, never with the token.+ const lines = warn.mock.calls.map(call => JSON.stringify(call))+ expect(lines.filter(line => line.includes('merge time not read'))).toHaveLength(3)+ expect(lines.some(line => line.includes('acme/app') && line.includes('"number":9') && line.includes('"status":502'))).toBe(true)+ expect(lines.some(line => line.includes('other/app') && line.includes('"number":1'))).toBe(true)+ expect(lines.some(line => line.includes('secret-token'))).toBe(false)+ warn.mockRestore()+ })+})++describe('a token the reader could not revoke', () => {+ it('says so, by repository, without the token', async () => {+ const warn = vi.spyOn(logger, 'warn').mockImplementation(() => logger)+ const app = {+ installation: vi.fn(async () => 11),+ createToken: vi.fn(async () => ({ token: 'secret-token' })),+ get: vi.fn(async () => ({ status: 200, body: { merged_at: null } })),+ revoke: vi.fn(async () => { throw new Error('GitHub 500') }),+ }+ expect(await appPullRequestMerges(app as never)(['https://github.com/acme/app/pull/7'])).toEqual({ 'https://github.com/acme/app/pull/7': null })+ const lines = warn.mock.calls.map(call => JSON.stringify(call))+ expect(lines.some(line => line.includes('not revoked') && line.includes('acme/app'))).toBe(true)+ expect(lines.some(line => line.includes('secret-token'))).toBe(false)+ warn.mockRestore()+ })+})diff --git a/backend/src/superTabs/ruleMoves.ts b/backend/src/superTabs/ruleMoves.tsnew file mode 100644index 000000000..2346c9e2e--- /dev/null+++ b/backend/src/superTabs/ruleMoves.ts@@ -0,0 +1,61 @@+/**+ * When GitHub says the pull requests a person's moved rule waits on merged (task #3463, review of #3220): read by the store+ * before an instructions save that may drop a line kept in a code task (store.ts pullRequestMergesFor), with the Harness+ * GitHub App's read-only token, so it needs no archive pass and works with tidying off. The store caps what it asks for+ * (store.ts MAX_MERGE_READS). The guard counts a task merged only+ * for a merge after its brief was set (ruleGuard.ts rulePlaces).+ */+import { githubRepository, type GitHubRepository } from '../github/repository.js'+import { PULL_READ_PERMISSIONS, type GitHubApp } from '../github/app.js'+import { logger } from '../utils/logger.js'++const PULL = /^https:\/\/github\.com\/([^/]+\/[^/]+)\/pull\/([1-9][0-9]*)$/++/** GitHub's read of one pull request: its status and body, or status 0 when it could not be read. */+export type PullGet = (repository: GitHubRepository, number: number) => Promise<{ status: number; body: unknown }>++/** When each of [urls] merged (ms), null for one GitHub says is not merged; one GitHub could not answer for is left out. */+export async function pullRequestMerges(urls: readonly string[], get: PullGet): Promise<Record<string, number | null>> {+ const answers = await Promise.all(urls.map(async url => {+ const match = PULL.exec(url), repository = match ? githubRepository(`https://github.com/${match[1]}`) : null+ if (!repository) return null+ const number = Number(match![2])+ const answer = await get(repository, number)+ const body = answer.body as { merged_at?: unknown } | null+ if (answer.status !== 200 || !body) {+ // Its rule's line stays as for a task not merged: said here, so a person told it waits can be told why (ENGINEERING.md 6).+ logger.warn('[swarm-instructions] merge time not read; the moved rule stays', { repository: repository.fullName, number, status: answer.status })+ return null+ }+ const at = typeof body.merged_at === 'string' ? Date.parse(body.merged_at) : null+ return [url, at !== null && Number.isNaN(at) ? null : at] as const+ }))+ return Object.fromEntries(answers.filter((answer): answer is readonly [string, number | null] => answer !== null))+}++/** The reader over the Harness GitHub App: one read-only token per repository for this save, revoked after. */+export function appPullRequestMerges(app: GitHubApp): (urls: readonly string[]) => Promise<Record<string, number | null>> {+ return async urls => {+ const tokens = new Map<string, Promise<string | null>>()+ const token = (repository: GitHubRepository) => {+ const key = repository.fullName.toLowerCase()+ if (!tokens.has(key)) tokens.set(key, (async () => {+ const installation = await app.installation(repository)+ return installation === null ? null : (await app.createToken(installation, repository, PULL_READ_PERMISSIONS)).token+ })().catch(() => null))+ return tokens.get(key)!+ }+ try {+ return await pullRequestMerges(urls, async (repository, number) => {+ const granted = await token(repository)+ return granted ? app.get(`/repos/${repository.fullName}/pulls/${number}`, granted).catch(() => ({ status: 0, body: null })) : { status: 0, body: null }+ })+ } finally {+ for (const [repository, granted] of tokens) {+ const value = await granted+ // Never the token: which repository's, and that it lives on until GitHub expires it (ENGINEERING.md 6).+ if (value) await app.revoke(value).catch(() => logger.warn('[swarm-instructions] GitHub token not revoked; it expires by itself within the hour', { repository }))+ }+ }+ }+}diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex e34ac0848..ceeee5a3a 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -70,11 +70,12 @@ import { moveChatMark } from './read/threadMarkSeeds.js'import { closedAgents, nextRemovalAt, removeClosedAgents, reopened, restoreRefusal, restoreSessions } from './closedAgents.js'import { sessionRows } from './memberRows.js'import { RefusalMemory } from './dispatchRefusals.js'+import { tasksHoldingMoves } from './ruleGuard.js'import { candidatesFor, DISPATCH_RULES, dispatchPlan, freeCrew, laneCapacity, openTasks, pinBuilder, pullRequestPin, roundOf, type Skip } from './dispatch.js'import { failRefusedStarts, judgedMachines, loseTasks, nextLossAt, recordTaskState, sweepForLead, sweepLiveness, SWEEP_EVERY_MS, unpurgedNotice } from './liveness.js'import { endedReply, taskLineChats } from './taskLine.js'import { owedAsk } from './timeChecks.js'-import { settleReleases, type ReleaseFacts, type ReleaseRules, type SettledReleases } from './releases.js'+import { ledgerGroupIds, settleReleases, type ReleaseFacts, type ReleaseRules, type SettledReleases } from './releases.js'import { archivable, archiveLine, archiveWaitsFor, idleNotices, reviewClosable, reviewCloseLine, reviewPullRequests, type SettledPullRequest } from './tidy.js'import { clock, insertParts, loadActive, loadGroups, loadLightGroups, loadMachineParts, loadObserved, reassemble, split, type GroupData, type HeadData, type MachineData, type Part, type SwarmParts } from './parts/index.js'import { groupsBy, listingDrops, quietSince, readBy, withoutHints } from './parts/indexed.js'@@ -166,6 +167,10 @@ const hash = (value: unknown): string => createHash('sha256').update(JSON.string* for a busy Swarm) until the maintenance script removes it, and every command and read loads this row. *//** The most Swarms a rename reaches at once, as many as a host reads (read/host.ts FULL_TABS); its readings do the rest. */const MACHINE_RENAME_SWARMS = 500+/** At most this many pull requests are read on GitHub for one instructions save (pullRequestMergesFor); the rest count as not+ * known, and their lines stay. */+export const MAX_MERGE_READS = 20+/** The writes after which the crew dispatch runs (store.ts dispatchSoon): those that may free a member or open a task. A* status only when it hands the task over or ends it; a progress note, the Swarm's most frequent write, frees nobody. */const DISPATCH_TRIGGERS: ReadonlySet<string> = new Set(['work.cancel', 'conversation.create', 'work.define', 'work.priority',@@ -416,6 +421,10 @@ export interface SuperTabStoreHooks {/** The files a handed task's pull requests change and their head (pullRequestFiles.ts), read before its Engineer's Ready so* the server opens its review steps (task #3401). Null with nothing of the project's repository to read. Absent with no GitHub App. */pullRequestFiles?: (repositoryUrl: string | null, pullRequestUrls: string[]) => Promise<PullRequestFilesRead | null>+ /** When GitHub says each of these pull requests merged (ms; null: not merged; absent: not known), read before an+ * instructions save that may drop a person's rule kept in a code task (ruleMoves.ts, task #3463). Absent with no GitHub App:+ * such a line then stays. */+ pullRequestMerges?: (autonomousEnv: string, tabId: string, projectId: string, pullRequestUrls: string[]) => Promise<Record<string, number | null>>/** The same for a branch a start names: its open pull request's answer, clean for the default branch, unknown with no pull request. */branchPushOrigin?: (repositoryUrl: string | null, branch: string) => Promise<PushOrigin>/** Whether the Harness GitHub App reaches a project's GitHub repository for this Swarm (github/projectAccess.ts), read before@@ -1642,13 +1651,44 @@ export class SuperTabStore {}}+ /**+ * When GitHub says the pull requests merged that an instructions save's dropped lines may wait on (task #3463): those linked+ * to the project's code tasks whose brief carries a line the save removes, in the project's own repository (a link+ * elsewhere is not this task's merge), at most MAX_MERGE_READS. Read before the write, as GitHub may take seconds, whatever+ * the tidying setting. Undefined when there is nothing to read or no reader; a failure reads as nothing known (the line stays).+ */+ private async pullRequestMergesFor(user: AuthUser, tabId: string, command: unknown): Promise<Record<string, number | null> | undefined> {+ const hook = this.hooks.pullRequestMerges+ const asked = command as Command | null+ if (!hook || asked?.type !== 'instructions.save') return undefined+ try {+ const urls = await transaction(this.db, async tx => {+ const { state } = await this.load(tx, user, tabId, namedFor(asked))+ const project = projectsOf(state).find(p => p.id === asked.projectId)+ const repositoryUrl = project?.repository?.repositoryUrl+ // Only a project on GitHub has GitHub merges of its own: any other frees nothing by a GitHub link (review 2 of #3273).+ if (!project || !repositoryUrl || !githubRepository(repositoryUrl)) return []+ const stored = await tx.superTabInstructions.findUnique({ where: { id: stableId(tabId, project.id) }, select: { text: true } })+ // The tasks the guard itself would read a dropped rule in (review 1 of #3273): wrapped lines and one rule of several.+ const holding = stored ? tasksHoldingMoves(state, project, stored.text, asked.text) : []+ return [...new Set(holding.flatMap(c => (c.pullRequestUrls ?? []).filter(url => projectPullRequestUrl(url, repositoryUrl) !== null)))]+ .slice(0, MAX_MERGE_READS)+ })+ return urls.length ? await hook(user.autonomousEnv, tabId, asked.projectId, urls) : undefined+ } catch (error) {+ if (error instanceof SuperTabError) return undefined+ logger.warn('[swarm-instructions] merges not read; moved rules stay', { tabId, error: error instanceof Error ? error.message : String(error) })+ return undefined+ }+ }+/** [only]: what the store alone may give a command: `overdue` for decision.answer (leaveOverdueDecisions), `movedTo` for* machine.moved (computerSignedIn). */private async executeOnce(user: AuthUser, tabId: string, input: { operationId: string; command: Command }, asAgentId?: string, hostMachineId?: string,workspaceLeave = false, only: { overdue?: boolean; movedTo?: { machineId: string; ownerId: string }; asProjectPm?: string } = {}) {const { operationId, command } = operationSchema.parse(input)- const [pushOrigin, repositoryReach, pullRequestFiles] = await Promise.all([this.pushOriginFor(user, tabId, command), this.repositoryReachFor(user, tabId, command),- this.pullRequestFilesFor(user, tabId, command)])+ const [pushOrigin, repositoryReach, pullRequestFiles, pullRequestMerges] = await Promise.all([this.pushOriginFor(user, tabId, command),+ this.repositoryReachFor(user, tabId, command), this.pullRequestFilesFor(user, tabId, command), this.pullRequestMergesFor(user, tabId, command)])let ended: WorkHold[] = [], started: WorkHold[] = []// Whether the Swarm, as this write leaves it, has a crew: only then may the write start a dispatch pass (dispatchSoon).let crewed = false@@ -1850,6 +1890,7 @@ export class SuperTabStore {const stored = await tx.superTabInstructions.findUnique({ where: { id: stableId(tabId, projectId) }, select: { revision: true, text: true, updatedAt: true } })context.instructions = stored && { revision: stored.revision, text: stored.text, ...stored.updatedAt ? { at: stored.updatedAt.getTime() } : {} }if (command.type === 'instructions.save' && command.approvals?.length) context.approvals = await readApprovals(tx, tabId, command.approvals)+ if (command.type === 'instructions.save' && pullRequestMerges) context.pullRequestMerges = pullRequestMerges}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.@@ -5063,8 +5104,7 @@ export class SuperTabStore {const head = (await tx.swarmHead.findUnique({ where: { id: `${tabId}:head` }, select: { data: true } }))?.data as { projects?: SwarmProject[] } | undefinedconst ledger = head?.projects?.find(p => p.id === projectId)?.releasesif (!ledger) return null- const groupIds = [...new Set([...ledger.pending.map(e => e.groupId), ...Object.values(ledger.steps ?? {}).map(s => s!.groupId)])]- const loaded = await loadRow(tx, requireParts(row), { groupIds })+ const loaded = await loadRow(tx, requireParts(row), { groupIds: ledgerGroupIds(ledger) })const state = cloneData(loaded.state)const before = JSON.stringify(projectsOf(loaded.state).find(p => p.id === projectId)?.releases)// The project's rules record as it reads now: its saved window, pace and backend pause, or the seed until one is saved.@@ -5235,12 +5275,6 @@ export class SuperTabStore {// Only the group it reviews as the pass read it: one this write did not load would hide its open pull requests.const review = !finished && !!reviewOf && group.reviewOf === reviewOf && reviewClosable(state, group, now) && read(reviewPullRequests(state, group))if (!finished && !review) return false- // What GitHub said merged in its project's repository, as this read saw it: what a person's rule moved into this task- // waits for (ruleGuard.ts rulePlaces, #3392). A link elsewhere, or a step's, is not this task's merge.- const repositoryUrl = groupProject(state, group).repository?.repositoryUrl- const merged = finished && githubRepository(repositoryUrl) ? Object.keys(checked)- .filter(url => checked[url] === 'merged' && projectPullRequestUrl(url, repositoryUrl) !== null) : []- if (merged.length) group.mergeSeen = { ...group.mergeSeen, ...Object.fromEntries(merged.map(url => [url, now])) }// Its work is over: a decision still waiting there waits no more (Dee, 10-31), as when the work ended by a command.await withdrawIn(tx, tabId, [groupId], now)group.archived = truediff --git a/docs/plans/2026-11-06-moved-rule-merge-plan.md b/docs/plans/2026-11-06-moved-rule-merge-plan.mdnew file mode 100644index 000000000..f62f7f719--- /dev/null+++ b/docs/plans/2026-11-06-moved-rule-merge-plan.md@@ -0,0 +1,70 @@+# A person's moved rule leaves only for work merged after the move: implementation plan++> Implemented by the task's Engineer the project's way (project instructions, Engineer): task by task, test first, each+> failing test committed before the code that passes it. No Execution Handoff.++**Goal:** A person-tagged rule moved into a code task may leave the instructions only once that task's pull request merged+after the rule went into the task, by the server's own read of GitHub, and that works with the daily tidy turned off.++**Architecture:** Today a moved rule's task counts as merged when the archive pass recorded any linked pull request merged+(`Conversation.mergeSeen`, written by `store.ts archiveFinished`). That record holds when the Swarm read it, not when it+merged, so an old merged pull request counts; and the archive pass runs only while tidying is on, so with it off a moved+rule can never leave. Instead, a task records when its brief was last set (`briefAt`, by `conversation.create` and+`work.define`), and an `instructions.save` that drops a line kept only in code tasks has the store read those tasks' linked+pull requests on GitHub before the write (`hooks.pullRequestMerges`, GitHub's `merged_at`), as it reads push origins. The+guard (`ruleGuard.ts rulePlaces`) counts a task merged only when one of its links merged after its `briefAt`.+`mergeSeen` is no longer read; its writer and field go.++**Tech Stack:** TypeScript backend (vitest; the Mongo integration suite runs in PR CI).++**Spec:** Task #3463 brief and its two acceptance checks (follow-ups from the review of #3392's #3220).++## Global Constraints++- PR body first line: "Requested by Dee through Harness."+- Owns `backend/src/superTabs/`. Outside it, only wiring: `backend/src/routes/superTabs.ts` (the hook on the API store).+- No new refusal code; a GitHub read that cannot say counts as not merged (the line stays, the refusal says why).+- At most 20 pull requests read per save; a token per repository, revoked after the read.++## Design++- Growth: one number per task (`briefAt`); `mergeSeen` is no longer written.+- Concurrency: the read happens before the write; the write still checks the instructions' base revision.+- Read cost: GitHub reads only on a save that drops a tagged line kept in a code task, capped at 20.+- Compatibility: a task from before (no `briefAt`) counts any merge GitHub reports, as today's rule does; older clients+ never see the fields.+- Migration + rollback: none.+- Audience: GitHub's answer, read by the server; no command writes `briefAt` or a merge time.+- Identity: the read uses the Harness GitHub App's read-only token, never a person's.+- Failure: GitHub unreachable → the line stays and the refusal names the task, as for an unmerged one; each read it+ could not make is logged by repository, number and status.+- A later `work.define` resets `briefAt`: the rule then waits for a merge after the new brief, which fails safe (the line+ stays) (review 1 of #3273).+- The tasks read are those the guard's own matcher finds a dropped rule in (`ruleGuard.ts tasksHoldingMoves`), across+ wrapped lines and as one rule of a line of several (review 1 of #3273).+- Platforms: backend only.++## Review Focus++- A pull request merged before the brief got the rule never frees it (Task 1 test).+- With tidying off, a person's save drops the moved line once its task's pull request merged (Task 2 test).+- A forged merge record (any agent's `conversation.merged`) still frees nothing by itself: only GitHub's `merged_at` counts.++---++### Task 1: count only a merge after the move++**Files:** `ruleGuard.ts`, `model.ts` (`briefAt`, `CommandContext.pullRequestMerges`), `commands.ts`, `instructions.test.ts`++- [ ] Failing tests: a task whose linked pull request GitHub says merged before the brief was set keeps the line (`waiting`);+ one merged after frees it; `briefAt` is set by create and define, by no other command.+- [ ] Implement; commit test, then code.++### Task 2: the store reads GitHub at the save, tidying on or off++**Files:** `store.ts` (pre-read, hook `pullRequestMerges`), new `ruleMoves.ts` (the app reader), `archive.ts`/`store.ts`+(`mergeSeen` writer removed), `routes/superTabs.ts`, `integration/superTabInstructions.test.ts`++- [ ] Failing integration test: tidying off, a person's save dropping a moved line succeeds once the hook says its task's+ pull request merged after the move; refused before, and refused for an older merge.+- [ ] Implement; commit test, then code.