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 j0215: #3236 #3234 #3210 #3221 #3216 (#3245)
0xken1554e5a404f753
diff --git a/.github/workflows/production-be-build.yaml b/.github/workflows/production-be-build.yamlindex 8e9e3819a..6d7a6902b 100644--- a/.github/workflows/production-be-build.yaml+++ b/.github/workflows/production-be-build.yaml@@ -65,6 +65,17 @@ jobs:steps:- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4+ # A tag pushed by hand skips the release scripts, so the window is checked here too+ # (scripts/release-window.py). An urgent release carries `Release-Urgent: <reason>` in its tag message.+ - name: Release window+ if: ${{ github.event_name == 'push' }}+ env:+ REF_NAME: ${{ github.ref_name }}+ run: |+ set -euo pipefail+ git fetch --quiet --force --depth=1 --filter=blob:none origin '+refs/tags/v*_backend:refs/tags/v*_backend'+ python3 scripts/release-window.py --kind backend --from-tag "$REF_NAME" --exclude-tag "$REF_NAME"+# Tag-only trigger, so GITHUB_REF_NAME is already the bare tag (e.g. v1.2.21_backend) and that# is the image tag ArgoCD deploys by.- name: Work out the image tagdiff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.ymlindex 45684fa69..78528badd 100644--- a/.github/workflows/release-desktop.yml+++ b/.github/workflows/release-desktop.yml@@ -53,6 +53,10 @@ on:description: 'Manifest to write. Leave as-is for a real release; metadata-test.json for a dry run.'required: falsedefault: harness/desktop/metadata.json+ urgent_reason:+ description: 'A P0 only: why this real release runs outside the release window (recorded in the run summary).'+ required: false+ default: ''test_publication:description: 'Only test publication against disposable fixture objects; no app build or product release'type: boolean@@ -106,6 +110,29 @@ jobs:candidate_prefix: ${{ steps.resolve.outputs.candidate_prefix }}test_prefix: ${{ steps.resolve.outputs.test_prefix }}steps:+ - uses: actions/checkout@v7+ with:+ fetch-depth: 1++ # A tag pushed by hand skips the release scripts, so the window is checked here too+ # (scripts/release-window.py). An urgent release carries `Release-Urgent: <reason>` in its tag message.+ - name: Release window+ if: ${{ github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && !inputs.prepare_only && !inputs.test_candidate_reuse && (inputs.metadata_path == '' || inputs.metadata_path == 'harness/desktop/metadata.json')) }}+ env:+ REF_NAME: ${{ github.ref_name }}+ EVENT_NAME: ${{ github.event_name }}+ URGENT_REASON: ${{ inputs.urgent_reason }}+ run: |+ set -euo pipefail+ if [ "$EVENT_NAME" = push ]; then+ git fetch --quiet --force --depth=1 origin tag "$REF_NAME"+ python3 scripts/release-window.py --kind desktop --from-tag "$REF_NAME" --exclude-tag "$REF_NAME"+ elif [ -n "$URGENT_REASON" ]; then+ python3 scripts/release-window.py --kind desktop --urgent "$URGENT_REASON"+ else+ python3 scripts/release-window.py --kind desktop+ fi+- id: resolve# Through env, never `${{ }}` inline in run:. Git permits quotes, backticks and $() in a# ref name, so interpolating one into the shell would let a tag name execute as code.@@ -691,7 +718,7 @@ jobs:# 2026-09-21). So fall back to the same commit list the script would have generated —# everything since the previous _desktop tag — and warn, rather than leave the release half done.if [ "$(git cat-file -t "$REF_NAME")" = tag ]; then- git tag -l --format='%(contents)' "$REF_NAME" > RELEASE_NOTES.md+ git tag -l --format='%(contents)' "$REF_NAME" | { grep -v '^Release-Urgent: ' || true; } > RELEASE_NOTES.mdelse: > RELEASE_NOTES.mdfidiff --git a/.github/workflows/release-web.yml b/.github/workflows/release-web.ymlindex 9c95cc24e..0185a6902 100644--- a/.github/workflows/release-web.yml+++ b/.github/workflows/release-web.yml@@ -63,6 +63,17 @@ jobs:steps:- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4+ # A tag pushed by hand skips the release scripts, so the window is checked here too+ # (scripts/release-window.py). An urgent release carries `Release-Urgent: <reason>` in its tag message.+ - name: Release window+ if: ${{ github.event_name == 'push' }}+ env:+ REF_NAME: ${{ github.ref_name }}+ run: |+ set -euo pipefail+ git fetch --quiet --force --depth=1 origin tag "$REF_NAME"+ python3 scripts/release-window.py --kind web --from-tag "$REF_NAME" --exclude-tag "$REF_NAME"+# Tag-only trigger, so GITHUB_REF_NAME is already the bare tag (e.g. v1.3.1_web) and that is# the image tag ArgoCD deploys by. The X.Y.Z inside it is also the bundle's version.- name: Work out the version and image tagdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 558c5b479..964630d7b 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -56,6 +56,10 @@ on:description: 'Manifest to write. Leave as-is for a real release; metadata-test.json for a dry run.'required: falsedefault: harness/cli/metadata.json+ urgent_reason:+ description: 'A P0 only: why this real release runs outside the release window (recorded in the run summary).'+ required: false+ default: ''permissions:contents: read@@ -85,6 +89,29 @@ jobs:metadata_path: ${{ steps.resolve.outputs.metadata_path }}staging_prefix: ${{ steps.resolve.outputs.staging_prefix }}steps:+ - uses: actions/checkout@v7+ with:+ fetch-depth: 1++ # A tag pushed by hand skips the release scripts, so the window is checked here too+ # (scripts/release-window.py). An urgent release carries `Release-Urgent: <reason>` in its tag message.+ - name: Release window+ if: ${{ github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && (inputs.metadata_path == '' || inputs.metadata_path == 'harness/cli/metadata.json')) }}+ env:+ REF_NAME: ${{ github.ref_name }}+ EVENT_NAME: ${{ github.event_name }}+ URGENT_REASON: ${{ inputs.urgent_reason }}+ run: |+ set -euo pipefail+ if [ "$EVENT_NAME" = push ]; then+ git fetch --quiet --force --depth=1 origin tag "$REF_NAME"+ python3 scripts/release-window.py --kind cli --from-tag "$REF_NAME" --exclude-tag "$REF_NAME"+ elif [ -n "$URGENT_REASON" ]; then+ python3 scripts/release-window.py --kind cli --urgent "$URGENT_REASON"+ else+ python3 scripts/release-window.py --kind cli+ fi+- id: resolve# Through env, never `${{ }}` inline in run:. Git permits quotes, backticks and $() in a ref# name, so interpolating one into the shell would let a tag name execute as code.@@ -477,7 +504,7 @@ jobs:# 2026-09-21). So fall back to the same commit list the script would have generated —# everything since the previous _cli tag — and warn, rather than leave the release half done.if [ "$(git cat-file -t "$REF_NAME")" = tag ]; then- git tag -l --format='%(contents)' "$REF_NAME" > RELEASE_NOTES.md+ git tag -l --format='%(contents)' "$REF_NAME" | { grep -v '^Release-Urgent: ' || true; } > RELEASE_NOTES.mdelse: > RELEASE_NOTES.mdfidiff --git a/Makefile b/Makefileindex 046a1bb45..e9f30d82c 100644--- a/Makefile+++ b/Makefile@@ -25,6 +25,12 @@ desktop-test:cli-test:cd cli && npx tsc --noEmit && npx vitest run+## The four release targets below are refused with RELEASE_WINDOW outside 09:00-18:00 Asia/Ho_Chi_Minh, a backend+## release within 2 hours of the last, and a backend release inside 09:00-10:00 (the morning peak). The refusal names the+## next allowed time (scripts/release-window.py; numbers in scripts/release-window.json).+## A P0 adds ARGS='--urgent "<reason>"': the reason goes on the tag and the script prints the line to post in the+## project chat. The tag workflows check the same rule, so a hand-pushed tag is refused too.+## release-cli: tag this commit vX.Y.Z_cli and push the tag — CI bundles the CLI, publishes it to## GCS, and cuts the GitHub Release. The version is bumped from max(last git tag, live## metadata.json's `cli` key). The `_cli` suffix is a tag-trigger marker only (see cli/RELEASE.md);diff --git a/backend/integration/superTabLiveness.test.ts b/backend/integration/superTabLiveness.test.tsindex f50db33e1..8732c54c2 100644--- a/backend/integration/superTabLiveness.test.ts+++ b/backend/integration/superTabLiveness.test.ts@@ -665,7 +665,8 @@ describe('work waiting for its review', () => {// 2026-10-29: five Engineers who had pushed and handed over lost their tasks after 30 quiet minutes waiting for a Reviewer.// Project instructions, phase 4: the review status waits; a failed check is a finding that moves nothing. An older skill's// working hand-off waits too while agents on those skills exist (this release), until someone else's verdict finds problems.- it('stays with its Engineer through 45 quiet minutes in review, a failed check included, and counts 30 once it is working again', async () => {+ // Task #3399: a failed check brings a task in review back to its Engineer, which keeps it for 60 minutes to pick it up.+ it('stays with its Engineer through 45 quiet minutes in review and 45 more once a failed check brings it back, and counts 30 once it is working again', async () => {const f = await swarm({ independent: true })const handedOver = f.clock.nowconst status = (status: 'review' | 'working', result: string) =>@@ -683,8 +684,9 @@ describe('work waiting for its review', () => {expect((await f.assignment()).status).toBe('review')const check = (await f.timed.read(owner, f.tab)).state.conversations.find(c => c.id === f.group)!.checks[0]!.idawait f.execute({ type: 'work.check', conversationId: f.group, assignmentId: f.assignmentId, checkId: check, passed: false, evidence: 'Two findings' })+ expect(await f.assignment()).toMatchObject({ status: 'working', reopened: { at: f.clock.now } })await quiet(f.clock.now, 45)- expect((await f.assignment()).status).toBe('review')+ expect((await f.assignment()).status).toBe('working')expect(await f.lostRows()).toEqual([])// Back to working, as an older skill hands over: that hand-off waits too, until a person's verdict finds problems in it.await status('working', 'Ready for review: PR #7 at 4f9c2e1')diff --git a/backend/integration/superTabNotAvailable.test.ts b/backend/integration/superTabNotAvailable.test.tsindex e810f75f8..cff2b5622 100644--- a/backend/integration/superTabNotAvailable.test.ts+++ b/backend/integration/superTabNotAvailable.test.ts@@ -121,6 +121,7 @@ function calls(tab: string, chat: string, project: string) {json('GET', 'GET /api/super-tabs/:tabId/projects/:projectId/instructions', `${t}/projects/${project}/instructions`),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('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.tsnew file mode 100644index 000000000..76f3b6ed7--- /dev/null+++ b/backend/integration/superTabProjectRules.test.ts@@ -0,0 +1,138 @@+import { randomUUID } from 'node:crypto'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import type { MongoMemoryReplSet } from 'mongodb-memory-server-core'+import type { 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 { superTabRoutes } from '../src/routes/superTabs.js'+import { errorHandler } from '../src/middlewares/errorHandler.js'+import type { Command } from '../src/superTabs/commands.js'+import { MAX_RULES_REVISIONS, SEED_RULES, type ProjectRules } from '../src/superTabs/policy.js'+import { currentRules } from '../src/superTabs/policyStore.js'+import { planDatabase, plan, profiled, reads } from './plans.test-support.js'++// Task #3393 (anh Dee's Swarm redesign, 11-05): a project's rules record, its revisions and who may change it, against real+// transactions. A fresh loopback replica set; never DATABASE_URL.+let replica: MongoMemoryReplSet+let db: PrismaClient+let store: SuperTabStore+let app: FastifyInstance+const owner: AuthUser = { sub: '100000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const peer: AuthUser = { sub: '100000000000000000000002', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const host: AuthUser = { sub: '100000000000000000000003', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const config = { engine: 'codex', model: 'fixture-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }+const run = (tab: string, command: Command, user = owner, asAgentId?: string) =>+ store.execute(user, tab, { operationId: randomUUID(), command }, asAgentId)+async function swarm() {+ const tab = (await store.create(owner, randomUUID(), 'Pilot')).id+ const invitation = await run(tab, { type: 'invite.create', email: peer.email, role: 'collaborator', conversationId: 'lead' })+ await run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, peer)+ const lead = (await run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId: randomUUID(),+ name: 'Lead', configuration: config, lead: true })).result.agentId as string+ return { tab, lead }+}+// No backend pause, so any start keeps the record valid (the pause must fall inside the window).+const rules = (start: string): ProjectRules => ({ ...structuredClone(SEED_RULES), releaseWindow: { ...SEED_RULES.releaseWindow, start },+ releasePace: { ...SEED_RULES.releasePace, backendPause: null } })+const set = (baseRevision: number, value: ProjectRules, extra: Partial<Extract<Command, { type: 'rules.set' }>> = {}): Command =>+ ({ type: 'rules.set', projectId: 'lead', baseRevision, rules: value, summary: 'Releases start later', ...extra })+const get = (user: AuthUser, tab: string, asAgentId?: string) => app.inject({ method: 'GET',+ url: `/api/super-tabs/${tab}/projects/lead/rules${asAgentId ? `?asAgentId=${asAgentId}` : ''}`, headers: { authorization: `Bearer ${user.sub}` } })+const refusal = async (promise: Promise<unknown>) => { try { await promise } catch (error) { return error as { code: string; status: number; details?: unknown } } throw new Error('not refused') }++beforeAll(async () => {+ ({ replica, db } = await planDatabase('project_rules_test'))+ store = new SuperTabStore(db, () => Date.now())+ for (const user of [owner, peer, host]) await db.user.create({ data: { id: user.sub, externalId: `fixture-${user.sub}`,+ email: user.email, autonomousEnv: user.autonomousEnv } })+ await db.machine.create({ data: { machineId: 'test-host', userId: host.sub, apiKey: 'fixture-only', managerId: 'fixture',+ autonomousEnv: 'prod', authMode: 'remote' } })+ await db.machineShare.create({ data: { machineId: 'test-host', ownerId: host.sub, autonomousEnv: 'prod', emails: [owner.email, peer.email] } })+ app = Fastify()+ app.setErrorHandler(errorHandler)+ app.addHook('onRequest', async (request, reply) => {+ const user = [owner, peer, host].find(u => `Bearer ${u.sub}` === request.headers.authorization)+ if (!user) return reply.code(401).send({ success: false })+ request.user = user+ })+ await app.register(superTabRoutes, { store, github: null })+ await app.ready()+}, 120_000)+afterAll(async () => {+ await app?.close()+ await db?.$disconnect()+ await replica?.stop()+})++describe('a project\'s rules record', () => {+ it('reads the seed until the first save, then each saved revision with who, when, the diff and why', async () => {+ const { tab } = await swarm()+ const first = await get(peer, tab)+ expect(first.statusCode, first.body).toBe(200)+ expect(first.json().data).toEqual({ projectId: 'lead', revision: 0, rules: SEED_RULES, seeded: true, history: [] })+ expect((await run(tab, set(0, rules('10:00')))).result).toMatchObject({ projectId: 'lead', revision: 1 })+ const read = (await get(peer, tab)).json().data+ expect(read).toMatchObject({ revision: 1, rules: rules('10:00'), seeded: false })+ expect(read.history).toEqual([{ revision: 1, rules: rules('10:00'), summary: 'Releases start later',+ diff: [{ path: 'releaseWindow.start', before: '09:00', after: '10:00' },+ { path: 'releasePace.backendPause', before: { start: '09:00', end: '10:00' }, after: null }], writtenBy: { kind: 'person', id: owner.sub },+ askedBy: owner.sub, askedIn: null, at: expect.any(String) }])+ // A stale save is refused with the newest record, to merge.+ expect(await refusal(run(tab, set(0, rules('11:00')), peer))).toMatchObject({ code: 'RULES_STALE', status: 409, details: { revision: 1, rules: rules('10:00') } })+ })++ it('lets the PM save only with a person\'s own chat message, recording it', async () => {+ const { tab, lead } = await swarm()+ expect(await refusal(run(tab, set(0, rules('10:00')), host, lead))).toMatchObject({ code: 'RULES_ASKED_IN_REQUIRED', status: 400 })+ const own = await run(tab, { type: 'message.send', conversationId: 'lead', text: 'Status: all good.', replyTo: null, recipientIds: [] }, host, lead)+ const agentMessage = own.result.messageId as string+ expect(await refusal(run(tab, set(0, rules('10:00'), { askedIn: { conversationId: 'lead', messageId: agentMessage } }), host, lead)))+ .toMatchObject({ code: 'RULES_ASKED_IN_REQUIRED' })+ const ask = await run(tab, { type: 'message.send', conversationId: 'lead', text: 'Start releases at 10, please.', replyTo: null, recipientIds: [] }, peer)+ const messageId = ask.result.messageId as string+ await run(tab, set(0, rules('10:00'), { askedIn: { conversationId: 'lead', messageId } }), host, lead)+ expect((await get(peer, tab)).json().data.history[0]).toMatchObject({ writtenBy: { kind: 'agent', id: lead }, askedBy: peer.sub,+ askedIn: { conversationId: 'lead', messageId } })+ // The PM reads the record it saves on.+ expect((await get(host, tab, lead)).json().data).toMatchObject({ revision: 1 })+ })++ // 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()+ expect(await currentRules(db, tab, 'lead')).toEqual({ revision: 0, rules: SEED_RULES })+ await run(tab, set(0, rules('10:00')))+ expect(await currentRules(db, tab, 'lead')).toEqual({ revision: 1, rules: rules('10:00') })+ })++ it('keeps one of two saves on the same revision, refusing the other', async () => {+ const { tab } = await swarm()+ const outcomes = await Promise.allSettled([run(tab, set(0, rules('10:00'))), run(tab, set(0, rules('11:00')), peer)])+ expect(outcomes.filter(o => o.status === 'fulfilled')).toHaveLength(1)+ expect((outcomes.find(o => o.status === 'rejected') as PromiseRejectedResult).reason).toMatchObject({ code: 'RULES_STALE' })+ expect(await db.superTabProjectRules.count({ where: { tabId: tab } })).toBe(1)+ })++ it('keeps the newest 50 revisions, read by its index, and goes with its project', async () => {+ const { tab } = await swarm()+ const created = await run(tab, { type: 'project.create', name: 'App', visibility: 'public', brief: '' })+ const app2 = created.result.projectId as string+ for (let i = 0; i < MAX_RULES_REVISIONS + 2; i++) {+ const start = `${String(10 + Math.floor(i / 60)).padStart(2, '0')}:${String(i % 60).padStart(2, '0')}`+ await run(tab, { ...set(i, rules(start)), projectId: app2 } as Command)+ }+ const kept = await db.superTabProjectRules.findMany({ where: { tabId: tab, projectId: app2 }, orderBy: { revision: 'asc' }, select: { revision: true } })+ expect(kept.map(k => k.revision)).toEqual(Array.from({ length: MAX_RULES_REVISIONS }, (_, i) => i + 3))+ const entries = await profiled(db, () => app.inject({ method: 'GET', url: `/api/super-tabs/${tab}/projects/${app2}/rules`,+ headers: { authorization: `Bearer ${owner.sub}` } }))+ const history = plan(reads(entries, 'SuperTabProjectRules', ['tabId', 'projectId']))+ expect(history.length).toBeGreaterThan(0)+ for (const row of history) {+ expect(row.plan).toContain('IXSCAN')+ expect(row.docsExamined).toBeLessThanOrEqual(row.returned)+ }+ await run(tab, { type: 'project.delete', projectId: app2 })+ expect(await db.superTabProjectRules.count({ where: { tabId: tab, projectId: app2 } })).toBe(0)+ }, 120_000)+})diff --git a/backend/integration/superTabPullRequestEvents.test.ts b/backend/integration/superTabPullRequestEvents.test.tsindex 3a072e0c2..55f77ec57 100644--- a/backend/integration/superTabPullRequestEvents.test.ts+++ b/backend/integration/superTabPullRequestEvents.test.ts@@ -112,6 +112,33 @@ describe('pull request events', () => {expect(await db.superTabDelivery.count({ where: { tabId: f.tab, agentId: f.worker, messageId: { in: rows.map(r => r.id) } } })).toBe(4)})+ // Task #3399: a handed task (its PR ready for review, its Engineer free) comes back to its Engineer on red CI or a conflict.+ it('CI failing or a conflict on a handed task brings it back to its Engineer, in the same attempt, in the message that tells it', async () => {+ for (const red of [true, false]) {+ const f = await swarm()+ f.pulls.set(f.PR, f.pull())+ await f.pass()+ await f.execute({ type: 'work.status', conversationId: f.task, assignmentId: f.assignment, status: 'review', result: `Ready for review: ${f.PR} at abc1234` }, host, f.worker)+ f.pulls.set(f.PR, red ? f.pull({ checkRuns: [{ name: 'build', status: 'completed', conclusion: 'failure', completedAt: f.clock.now + 10_000 }] }) : f.pull({ mergeable: false }))+ expect(await f.pass()).toBe(1)+ const work = (await f.store.read(owner, f.tab)).state.conversations.find(c => c.id === f.task)!.assignment!+ expect(work).toMatchObject({ id: f.assignment, agentId: f.worker, status: 'working' })+ const [told] = await f.told()+ expect(told!.text).toMatch(red ? /^CI failed on your pull request .* Your task is back with you/ : /merge conflict.* Your task is back with you/)+ expect(told!.recipientIds).toEqual([f.worker])+ }+ })++ it('CI passing on a handed task leaves it with its Reviewers', async () => {+ const f = await swarm()+ f.pulls.set(f.PR, f.pull())+ await f.pass()+ await f.execute({ type: 'work.status', conversationId: f.task, assignmentId: f.assignment, status: 'review', result: `Ready for review: ${f.PR} at abc1234` }, host, f.worker)+ f.pulls.set(f.PR, f.pull({ checkRuns: [{ name: 'build', status: 'completed', conclusion: 'success', completedAt: f.clock.now + 10_000 }], checkSuites: [{ status: 'completed', runs: 1 }] }))+ expect(await f.pass()).toBe(1)+ expect((await f.store.read(owner, f.tab)).state.conversations.find(c => c.id === f.task)!.assignment!.status).toBe('review')+ })+it('a second pass and a retried write post nothing', async () => {const f = await swarm()f.pulls.set(f.PR, f.pull())diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex 0942e3f8c..21a2a523d 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -2165,6 +2165,35 @@ describe('Super Tabs on a real Mongo replica set', () => {expect((await db.superTabDelivery.findUnique({ where: { id: delivery.id } }))!.status).toBe('cancelled')})+ // Task #3399, security review of #3221: a handed task frees its Engineer for the next task, which takes the session's run+ // record; when that one ends while the handed task is still open, the record goes back to it, so no other Swarm can assign+ // the session while a No or red CI may bring that task back.+ it('keeps the cross-tab fence on a handed task once the Engineer\'s next task ends', async () => {+ const one = await fixture()+ const two = await fixture()+ const session = randomUUID()+ const task = async (tab: string) => String((await run(tab, { type: 'conversation.create', title: 'Task', brief: 'Check the fixture.',+ checks: [{ description: 'Test passes.', independent: true }] })).result.conversationId)+ const handedTask = await task(one.tab), next = await task(one.tab), other = await task(two.tab)+ const attach = (conversationId: string): Command => ({ type: 'agent.add', conversationId, machineId: 'test-host', harnessId: session,+ name: 'Worker', configuration: config, lead: false })+ const worker = (await run(one.tab, attach(handedTask))).result.agentId as string+ await run(one.tab, { type: 'conversation.agent', conversationId: next, agentId: worker, present: true, lead: false })+ await run(two.tab, attach(other))+ const handed = (await run(one.tab, { type: 'work.assign', conversationId: handedTask, agentId: worker })).result.assignmentId as string+ await run(one.tab, { type: 'work.status', conversationId: handedTask, assignmentId: handed, status: 'review', result: 'Ready for review: PR #7 at abc1234' }, host, worker)+ const following = (await run(one.tab, { type: 'work.assign', conversationId: next, agentId: worker })).result.assignmentId as string+ expect(await db.superTabRun.findUnique({ where: { id: worker } })).toMatchObject({ tabId: one.tab, assignmentId: following })+ await expect(run(two.tab, { type: 'work.assign', conversationId: other, agentId: worker })).rejects.toMatchObject({ code: 'AGENT_BUSY' })+ await run(one.tab, { type: 'work.status', conversationId: next, assignmentId: following, status: 'done', result: 'Merged PR #8' }, host, worker)+ expect(await db.superTabRun.findUnique({ where: { id: worker } })).toMatchObject({ tabId: one.tab, assignmentId: handed })+ await expect(run(two.tab, { type: 'work.assign', conversationId: other, agentId: worker })).rejects.toMatchObject({ code: 'AGENT_BUSY' })+ // Its own end releases the session, as any task's does.+ await run(one.tab, { type: 'work.status', conversationId: handedTask, assignmentId: handed, status: 'done', result: 'Merged PR #7' }, host, worker)+ expect(await db.superTabRun.findUnique({ where: { id: worker } })).toBeNull()+ await run(two.tab, { type: 'work.assign', conversationId: other, agentId: worker })+ })+it('holds a cross-tab assignment until host-confirmed stop and retains the previous attempt', async () => {const one = await fixture()const two = await fixture()diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex 2dd1ecccc..4e9a0842f 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1712,6 +1712,29 @@ model SuperTabInstructionsRevision {@@index([tabId, projectId, revision])}+// A project's rules record (superTabs/policy.ts), one row per saved revision: the newest is the record, the rest its history.+// Removed: the save that writes revision N deletes revisions <= N - 50 of its project (policyStore.ts writeRules, MAX_RULES_REVISIONS);+// a deleted project takes its rows; the Swarm purge takes the tab's (purge.ts). A row is at most 16 KB of rules plus its diff.+// `writtenBy` is a person's or the project's PM's id (`writtenByKind`), `askedBy` the person whose words it carries, `askedIn`+// the chat message the PM passed on (null when a person saved). id = stableId(tabId, projectId, revision): two saves of one+// revision collide on it, and one retries into RULES_STALE.+model SuperTabProjectRules {+ id String @id @map("_id")+ tabId String+ projectId String+ revision Int+ rules Json+ diff Json+ summary String+ writtenByKind String+ writtenBy String+ askedBy String+ askedIn Json?+ at DateTime++ @@index([tabId, projectId, revision])+}+// The small things a member tells a project's coordinator, kept beside its instructions so they survive a restart or a move// (instructions.ts): at most 100 live per project, each up to 300 characters. An expired one is never read and is deleted// by the next note write of its project; all go with the project.diff --git a/backend/scripts/release-be.sh b/backend/scripts/release-be.shindex 5ff9c97bc..2f624be80 100755--- a/backend/scripts/release-be.sh+++ b/backend/scripts/release-be.sh@@ -7,6 +7,10 @@# ./scripts/release-be.sh 1.4.1 # exact version -> v1.4.1_backend (patch 1 to 99)# ./scripts/release-be.sh --dry-run # print what it WOULD do, touch nothing# ./scripts/release-be.sh --allow-older # a rollback: older code under a higher version+# ./scripts/release-be.sh --urgent "P0: why" # a P0 outside 09:00-18:00 VN or within 2 h of the last release+#+# Refused with RELEASE_WINDOW (scripts/release-window.py) outside 10:00-18:00 Asia/Ho_Chi_Minh (09:00-10:00 is the morning peak) and within+# 2 hours of the last backend release; the refusal names the next allowed time. --urgent records its reason on the tag.## Pushing the tag is the whole point: ../.github/workflows/production-be-build.yaml triggers on# `vX.Y.Z_backend` tags and builds Dockerfile.k8s -> autonomous-code-be.@@ -29,13 +33,18 @@ cd "$REPO_ROOT"DRY_RUN=0ALLOW_OLDER=0BUMP="patch"+URGENT_SET=0+URGENT=""+want_urgent=0for arg in "$@"; do+ if [ "$want_urgent" -eq 1 ]; then URGENT="$arg"; want_urgent=0; continue; ficase "$arg" in+ --urgent) URGENT_SET=1; want_urgent=1 ;;--dry-run) DRY_RUN=1 ;;--allow-older) ALLOW_OLDER=1 ;;patch|minor|major) BUMP="$arg" ;;[0-9]*.[0-9]*.[0-9]*) BUMP="exact"; EXACT="${arg#v}" ;;- *) echo "usage: $0 [patch|minor|major|X.Y.Z] [--dry-run] [--allow-older]" >&2; exit 1 ;;+ *) echo "usage: $0 [patch|minor|major|X.Y.Z] [--dry-run] [--allow-older] [--urgent \"<reason>\"]" >&2; exit 1 ;;esacdone@@ -52,6 +61,10 @@ fi# --- preflight: the tag names a commit, so that commit must be the right one and must be on origin.git fetch --tags --quiet origin+# --- the release window and pace: refused here, before anything is tagged (fresh tags are fetched above).+source "$REPO_ROOT/../scripts/release-window.sh"+release_window_guard backend+BRANCH="$(git rev-parse --abbrev-ref HEAD)"HEAD_SHA="$(git rev-parse HEAD)"@@ -128,7 +141,7 @@ if [[ "$DRY_RUN" == "1" ]]; thenexit 0fi-git tag -a "$TAG" -m "$SERVICE release $TAG"+git tag -a "$TAG" -m "$SERVICE release $TAG" ${URGENT_TAG_LINE:+-m "$URGENT_TAG_LINE"}git push origin "$TAG"echo ""diff --git a/backend/src/github/holds.ts b/backend/src/github/holds.tsindex c6be656d4..b8fd5234c 100644--- a/backend/src/github/holds.ts+++ b/backend/src/github/holds.ts@@ -1,10 +1,11 @@-import type { SuperTabState, WorkStatus } from '../superTabs/model.js'+import { isLeads, occupiesAgent, type Agent, type Conversation, type SuperTabState, type WorkStatus } from '../superTabs/model.js'/** An agent's task in progress, which a GitHub token may serve. */export interface WorkHold { agentId: string; assignmentId: string }-/** The statuses of a task still in the agent's hands: working, waiting on a person, stuck, or out for review (a Builder- * fixes what its Reviewer finds). Done, stopped, cancelled and reconciling (its agent removed) are not. */+/** The statuses of a task a GitHub token may serve: working, waiting on a person, stuck, or out for review. A task in review is+ * handed over (model.ts handed, task #3399): its Engineer is free for new work but keeps this hold, to push the fixes its+ * Reviewer or CI asks for. Done, stopped, cancelled and reconciling (its agent removed) are not. */export const HOLDING: ReadonlySet<WorkStatus> = new Set<WorkStatus>(['working', 'needs_human', 'blocked', 'review'])/** Every task in progress in [state], held by an agent still in it. */@@ -28,3 +29,12 @@ export function endedHolds(before: Pick<SuperTabState, 'agents' | 'conversationsconst still = new Set(workHolds(after).map(hold => `${hold.agentId}:${hold.assignmentId}`))return workHolds(before).filter(hold => !still.has(`${hold.agentId}:${hold.assignmentId}`))}++/** The task a GitHub token for [target] is minted for (store.ts githubAssignment): one in progress run by that agent's own+ * session on its machine, the one in its hands first, then one it handed over (task #3399). A handed task's merge revokes+ * every token minted for it, so the token its new task pushes with is never the handed one's. */+export function tokenTask(state: Pick<SuperTabState, 'conversations'>, target: Pick<Agent, 'id' | 'machineId' | 'machineOwnerId'>): Conversation | undefined {+ const held = state.conversations.filter(c => !isLeads(c) && c.assignment?.agentId === target.id && HOLDING.has(c.assignment.status)+ && c.assignment.execution.machineId === target.machineId && c.assignment.execution.machineOwnerId === target.machineOwnerId)+ return held.find(occupiesAgent) ?? held[0]+}diff --git a/backend/src/github/tokens.test.ts b/backend/src/github/tokens.test.tsindex c714e4e55..7a378d2e9 100644--- a/backend/src/github/tokens.test.ts+++ b/backend/src/github/tokens.test.ts@@ -132,9 +132,10 @@ describe('agent tokens', () => {expect(one.token).not.toBe(two.token)// Each token twice, as the agent's entry and among its task's minted tokens, both sealed.expect(stored).toHaveLength(4)+ // The tokens and task ids themselves: sealed output is base64url, which holds "ghs_" by chance about once in 1,500 runs+ // (it failed CI on #3221 at 7fe77c682 that way).for (const value of stored) {- expect(value).not.toContain('ghs_')- expect(value).not.toContain('attempt')+ for (const secret of [one.token, two.token, 'attempt-1', 'attempt-2']) expect(value).not.toContain(secret)}})diff --git a/backend/src/lib/teamSession.test.ts b/backend/src/lib/teamSession.test.tsindex c548027c8..54db1befb 100644--- a/backend/src/lib/teamSession.test.ts+++ b/backend/src/lib/teamSession.test.ts@@ -179,6 +179,8 @@ describe('a team session on its own machine', () => {['GET', '/api/super-tabs/tab-1/projects/project-1/instructions?asAgentId=agent-1', undefined, 'instructions'],['GET', '/api/super-tabs/tab-1/projects/project-1/instructions/revisions?asAgentId=agent-1', undefined, 'instructionRevisions'],['GET', '/api/super-tabs/tab-1/projects/project-1/instructions/revisions/3?asAgentId=agent-1', undefined, 'instructionRevision'],+ // The project's rules record (task #3393): a Team-account PM reads the revision it saves its change on.+ ['GET', '/api/super-tabs/tab-1/projects/project-1/rules?asAgentId=agent-1', undefined, 'projectRules'],// The route's measures and a file over the form's 10 MB (2026-11-03: refused here, so a Team PM routed without the CI hold// and a Team Engineer could not attach a big file). Each store method holds the agent to this machine (integration test).['GET', '/api/super-tabs/tab-1/costs?days=7&asAgentId=agent-1', undefined, 'costSummary'],diff --git a/backend/src/lib/teamSession.ts b/backend/src/lib/teamSession.tsindex d0070a530..9930bf77b 100644--- a/backend/src/lib/teamSession.ts+++ b/backend/src/lib/teamSession.ts@@ -137,6 +137,8 @@ export const TEAM_ROUTES: readonly TeamRoute[] = [{ method: 'GET', url: '/api/super-tabs/:tabId/projects/:projectId/instructions', scope: 'agent' },{ method: 'GET', url: '/api/super-tabs/:tabId/projects/:projectId/instructions/revisions', scope: 'agent' },{ method: 'GET', url: '/api/super-tabs/:tabId/projects/:projectId/instructions/revisions/:revision', scope: 'agent' },+ // Its project's rules record, which a Team-account PM reads for the revision it saves on (superTabs/policy.ts).+ { method: 'GET', url: '/api/super-tabs/:tabId/projects/:projectId/rules', scope: 'agent' },// What the route ranks by: the project's measured costs and its CI load (superTabs/costs/read.ts, github/ciLoad.ts). Missing// here until 2026-11-03, so a Team PM routed without them and the CI hold never applied.{ method: 'GET', url: '/api/super-tabs/:tabId/costs', scope: 'agent' },diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex dccc184c5..ca73717de 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -853,6 +853,10 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Suapp.get<{ Params: z.infer<typeof revisionParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/projects/:projectId/instructions/revisions/:revision',{ preHandler: [validateParams(revisionParams), validateQuery(agentQuery)] },(req, reply) => respond(reply, () => store.instructionRevision(req.user!, req.params.tabId, req.params.projectId, req.params.revision, req.query.asAgentId)))+ // A project's rules record and its kept revisions (superTabs/policy.ts): shown to people, in no prompt.+ 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)))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.test.ts b/backend/src/superTabs/commands.test.tsindex d30aefc45..29b45a960 100644--- a/backend/src/superTabs/commands.test.ts+++ b/backend/src/superTabs/commands.test.ts@@ -4,6 +4,7 @@ import { applyCommand, assertUniqueMessageIds, commandSchema, LOOP_NOTICE_AT, swimport { CREDENTIAL_MARKER, type CredentialKind } from './credentials.js'import { readsRawReason } from './startFailure.js'import { sweepLiveness } from './liveness.js'+import { REOPEN_OWNER_MS } from './handed.js'import { SWITCH_UNCLAIMED_MS } from './tidy.js'import { defaultProfileId, hostLocalGrid, machineSlots, removalPreview, swarmGridRow } from './machines.js'import { activeWork, agentOnly, agentRole, createSuperTab, visibleState, type Actor, type AgentConfiguration, type Author } from './model.js'@@ -2963,14 +2964,16 @@ describe('Reviewer role', () => {return { ...setup, built, builderActor, verdict, task, swept }}- it('keeps work in review when a review finds problems: the findings are information, and its quiet time still does not count', () => {+ // Task #3399: a review that finds problems brings the handed task back to its builder, which has 60 minutes to pick it up.+ it('brings work in review back to its builder when a review finds problems, and its quiet time counts from then', () => {const { verdict, task, swept, builder } = handedOver('review')const foundAt = 2000 + 2 * HOURexpect(swept(foundAt)).toBe('review')const found = verdict(false, foundAt)- expect(task()).toMatchObject({ status: 'review', result: 'Ready for review: PR #42 at abc1234' })- expect(found.messages.filter(m => m.recipients.includes(builder))).toEqual([])- expect(swept(foundAt + 2 * HOUR)).toBe('review')+ expect(task()).toMatchObject({ status: 'working', result: 'Ready for review: PR #42 at abc1234', reopened: { at: foundAt } })+ expect(found.messages.filter(m => m.recipients.includes(builder)).map(m => m.text)).toEqual([expect.stringContaining('back with you')])+ expect(swept(foundAt + REOPEN_OWNER_MS)).toBe('working')+ expect(swept(foundAt + 2 * HOUR)).toBe('lost')})it('keeps work in review when the review passes', () => {@@ -4929,14 +4932,15 @@ describe('checks are information', () => {.toBe('Look into the flaky test\n\nStart each pull request body with: Requested by owner through Harness.')})- it('keeps a failed check as a finding', () => {+ it('keeps a failed check as a finding, and brings a handed task back to its Engineer', () => {const f = routed(), group = f.group(), reviewer = f.add('reviewer', 'owner', group)f.run({ type: 'conversation.agent', conversationId: group, agentId: f.worker, present: true, lead: false })const assignmentId = f.run({ type: 'work.assign', conversationId: group, agentId: f.worker }).result.assignmentId as stringf.run({ type: 'work.status', conversationId: group, assignmentId, status: 'review', result: 'Ready for review: PR #42 at abc1234' }, f.workerActor)const checkId = f.state.conversations.find(c => c.id === group)!.checks[0]!.idconst found = f.run({ type: 'work.check', conversationId: group, assignmentId, checkId, passed: false, evidence: 'Two findings at abc1234' }, as(reviewer))- expect(f.state.conversations.find(c => c.id === group)!.assignment).toMatchObject({ status: 'review', result: 'Ready for review: PR #42 at abc1234' })+ // The task comes back to its Engineer (#3399); its result stays as it wrote it.+ expect(f.state.conversations.find(c => c.id === group)!.assignment).toMatchObject({ status: 'working', result: 'Ready for review: PR #42 at abc1234' })expect(f.state.conversations.find(c => c.id === group)!.checks[0]).toMatchObject({ passedBy: null, evidence: 'Two findings at abc1234' })expect(found.messages.filter(m => m.text.startsWith('Working'))).toEqual([])})@@ -5110,7 +5114,8 @@ describe('notices of failed work', () => {const sonnet = other('sonnet', 'claude-sonnet-4-5')const attempt = give(sonnet)expect(failed(failIt(attempt, sonnet))).toEqual([])- expect(mine().assignment).toMatchObject({ id: attempt, status: 'review' })+ // It comes back to its own agent, in the same attempt (#3399); the grid one above is not pinned, as its next attempt steps up.+ expect(mine().assignment).toMatchObject({ id: attempt, status: 'working' })expect(mine().stepUp).toBeUndefined()})diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex f9e93ace4..eb149919c 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -11,7 +11,7 @@ import { agentWrittenNameOf, setName, shownNameOf } from './personNames.js'import { z } from 'zod'import { tokensByModelSchema } from './costs/tokens.js'import {- activeWork, actorKey, agent, appendPullRequestUrls, author, projectPullRequestUrl, conversation, crossProjectActive, fail, isLeads, person, stableId, numberConversations, nextConversationNumber, renderWorkTask,+ activeWork, occupiesAgent, actorKey, agent, appendPullRequestUrls, author, projectPullRequestUrl, conversation, crossProjectActive, fail, isLeads, person, stableId, numberConversations, nextConversationNumber, renderWorkTask,finishWorker, seenMachineIds, SuperTabError, swarmGridName, visibleState, AGENT_ONLY, STATUS_LABELS, forRecipients,type Actor, type AgentConfiguration, type AgentStart, type AgentStartRequest, type BuddySessionEntry, type WorkTask, type Agent, type Author, type Check, type CommandEffects, type Conversation, type SuperTabState,} from './model.js'@@ -21,11 +21,13 @@ import { recordCheckVerdict } from './checkVerdicts.js'import { routeRecordSchema, routeTitle, startedAs, type KeptCandidate, type RouteDecision, type RouteFinal, type RouteOverride } from './routeRecord.js'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 { 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'import { answerDecision, askDecisions, checkAsker, decisionChoices, decisionQuestion, MAX_OPEN_DECISIONS, MAX_QUESTIONS, type DecisionTarget } from './decisions.js'import { leadOf, TERMINAL_KEYS, terminalAlert, terminalRequest, terminalResult, toLead, type TerminalRequest, workedAgain } from './terminal.js'+import { BACK_WITH_YOU, pickUp, reopenHanded } from './handed.js'import { changesRequested, engineerAnswered, leadNoticeRows, loseTasks, recordTaskState, renewLease, renewOwnTask, restartQuietTime, revisionReady, toldEngineer, waitingForReview } from './liveness.js'import { DELETED_SWARM_COMMANDS, isPersonalSwarm, notThere, SWARM_DELETE_GRACE_MS } from './deletion.js'import { ABANDONED, askedModel, coordinatorCopy, failureNotice, failureRecipients, MACHINE_MOVED, MACHINE_REMOVED, publicReason } from './startFailure.js'@@ -232,6 +234,10 @@ export const commandSchema = z.discriminatedUnion('type', [.max(MAX_DROPPED_LINES).optional(),// The coordinator's daily tidy, done by this save (pmSchedule.ts tidyRequest).tidy: z.literal(true).optional() }).strict(),+ // The project's rules record, saved on the revision the writer read (policy.ts). A person writes in their own name; the+ // project's PM only with `askedIn`, the person's own chat message it passes on.+ z.object({ type: z.literal('rules.set'), projectId: id, baseRevision: z.number().int().nonnegative().safe(), rules: projectRulesSchema,+ summary: summarySchema, askedIn: askedInSchema.optional() }).strict(),// A small thing a member told the coordinator, kept beside the instructions until it ends, if it does (instructions.ts).z.object({ type: z.literal('note.add'), projectId: id, text: noteTextSchema, askedBy: id, expiresAt: z.iso.datetime().optional() }).strict(),z.object({ type: z.literal('note.remove'), projectId: id, noteId: id }).strict(),@@ -452,6 +458,7 @@ const WORDS: Partial<Record<Command['type'], readonly string[]>> = {'note.add': ['text'],'project.coordinatorName': ['name'],'rule.set': ['text'],+ 'rules.set': ['summary'],'route.record': ['decision.assessment.why', 'decision.why', 'decision.excluded[].title', 'decision.excluded[].reason','decision.candidates[].title', 'decision.candidates[].label'],'route.override': ['reason'],@@ -554,6 +561,9 @@ export interface CommandContext {instructions?: { revision: number; text: string; at?: 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`: the project's newest stored rules revision, read by the store; null when none is saved yet, which is+ * the seed at revision 0 (policyStore.ts). Unread (undefined), nothing is saved. */+ projectRules?: { revision: number; rules: ProjectRules } | null/** For `note.add` and `note.remove`: the project's stored notes, expired ones too, read by the store (instructions.ts). */notes?: PmNote[]/** The message a Lead quotes as the owner's request for a rule or skill mode change, loaded from this tab by the store. */@@ -755,7 +765,7 @@ export function authorizeCommandAccess(state: SuperTabState, actor: Actor, commaif (command.type === 'agent.start') readConversation(state, actor, command.request.conversationId)if ((command.type === 'rule.set' || command.type === 'rule.remove' || command.type === 'project.skills' || command.type === 'tab.tidy'|| command.type === 'machine.engineResume' || command.type === 'machine.projects' || command.type === 'machine.ownAccountWork'- || command.type === 'machine.access') && command.askedIn) {+ || command.type === 'machine.access' || command.type === 'rules.set') && command.askedIn) {readConversation(state, actor, command.askedIn.conversationId)}if ('startId' in command && command.type !== 'route.modelResult') {@@ -1868,6 +1878,45 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,}break}+ case 'rules.set': {+ // People change a project's rules, or its PM passing on a person's own chat message of this project from the last day+ // (task #3393): the record keeps who wrote it, for whom and where they asked. Nothing is posted: the history shows it.+ const project = readProject(state, actor, command.projectId)+ let askedBy: string, askedIn: { conversationId: string; messageId: string } | null = null+ if (actor.kind === 'agent') {+ if (ledProject(state, actor.agentId)?.id !== project.id) {+ fail('RULES_EDITOR_REQUIRED', 'A member changes this project\'s rules, or its PM passing on their chat message. Ask the PM in the project chat.', 403)+ }+ const asked = command.askedIn && context.askedIn+ const where = command.askedIn && state.conversations.find(c => c.id === command.askedIn!.conversationId)+ if (!asked || !where || asked.author.kind !== 'person' || asked.source || context.now - asked.createdAt > RULE_MESSAGE_MS+ || groupProject(state, where).id !== project.id) {+ fail('RULES_ASKED_IN_REQUIRED', 'Quote the chat message, from the last day in this project, of the person who asked for this change (askedIn).', 400)+ }+ askedBy = askedByOf(state, project, asked.author.id)+ // The person must still be one who may change the rules themselves: not one made a viewer since (security review).+ if (person(state, askedBy).role === 'viewer') {+ fail('RULES_ASKED_IN_REQUIRED', 'Quote the chat message of a member who may change this project, not a viewer.', 400)+ }+ askedIn = { conversationId: command.askedIn!.conversationId, messageId: command.askedIn!.messageId }+ } else askedBy = (actor as Extract<Actor, { kind: 'person' }>).userId+ if (context.projectRules === undefined) fail('RULES_UNAVAILABLE', 'This project\'s rules cannot be read now. Try again in a moment.', 503)+ const current = context.projectRules ?? { revision: 0, rules: SEED_RULES }+ if (command.baseRevision !== current.revision) {+ // Refused with the record it missed, to merge and save again: never two writers' records kept silently.+ 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)) {+ 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),+ summary: command.summary, writtenBy: { kind: sender.kind, id: sender.id }, askedBy, askedIn, at: context.now }+ Object.assign(result, { projectId: project.id, revision })+ break+ }case 'note.add': {// The coordinator keeps what it is told freely: no approval and no chat line, so a note costs nobody attention (design,// PM notes). A person tells it, or removes one.@@ -3695,7 +3744,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,requireTeamWrittenAccount(state, group, worker)marking(group, () => markTeamWritten(state, group, worker))if (worker.workDecision === 'stop') fail('STOP_REQUESTED', 'This worker is stopping. Wait for its execution host.')- if (state.conversations.some(c => activeWork(c) && c.assignment?.agentId === worker.id)) fail('AGENT_BUSY', 'This agent already owns an active assignment.')+ if (state.conversations.some(c => occupiesAgent(c) && c.assignment?.agentId === worker.id)) fail('AGENT_BUSY', 'This agent already owns an active assignment.')// An older client assigns in a custom role: kept for older readers, and the role name it means for a worker without// one (instructions.ts legacyRoleName). No command reads the role.if (command.roleId) {@@ -3778,6 +3827,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,assignment.result = command.result// A new status is a new hand-off, or the end of one: a review's earlier findings are answered (liveness.ts waitingForReview).delete assignment.reviewFoundAt+ // And a task that came back to its Engineer is picked up, or handed over again (handed.ts).+ pickUp(assignment)if (command.ask) assignment.askedOf = command.ask.personIdelse if (command.status !== 'needs_human') delete assignment.askedOfrecordStatus(group, assignment, previous, context.now, changed ? operationId : null, asked)@@ -3895,7 +3946,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,if (!resumeAt) fail('NO_RESUME', 'This task was not lost to a usage limit with a reset time.')if (context.now < Date.parse(resumeAt)) fail('LIMIT_NOT_RESET', 'Its usage limit has not reset yet.')if (worker.harnessId !== assignment.execution.harnessId) fail('SESSION_CHANGED', 'This agent runs in another session now, so the task does not resume.')- if (state.conversations.some(c => activeWork(c) && c.assignment?.agentId === worker.id)) fail('AGENT_BUSY', 'This agent already owns an active assignment.')+ if (state.conversations.some(c => occupiesAgent(c) && c.assignment?.agentId === worker.id)) fail('AGENT_BUSY', 'This agent already owns an active assignment.')assignment.status = 'working'delete assignment.lostdelete group.lostAttempt@@ -3915,7 +3966,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,const check = group.checks.find(c => c.id === command.checkId) ?? fail('NOT_FOUND', 'This acceptance check is unavailable.', 404)if (actor.kind === 'agent' && !group.agentIds.includes(actor.agentId)) fail('FORBIDDEN', 'This agent does not participate in the review.', 403)// Checks are information (project instructions, phase 4): who passes one is the project's workflow, so anyone in the task- // records a verdict, its assignee too, and a failed one leaves the work's status as its agent set it. A verdict counts as a+ // records a verdict, its assignee too, and a failed one leaves the work's status as its agent set it, except that a failed one+ // from anyone else brings a handed task back to its Engineer (below, #3399). A verdict counts as a// review only from someone other than the assignee (leaderboard/record.ts).const by = actorKey(actor)// A checker who left the Swarm can never pass its failure again: the task's PM or an owner passing the check clears@@ -3949,6 +4001,16 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,group.assignment.reviewFoundAt = context.nowrestartQuietTime(group.assignment, context.now)}+ // A No from anyone but its Engineer brings a handed task back to it, in the same attempt (handed.ts, #3399): it is told why.+ // Not a grid attempt whose review failed: its next attempt steps up to a stronger model (decision 8), so it is not pinned.+ const reopen = (task: Conversation) => {+ const taskRun = task.ledger?.runs?.find(r => r.assignmentId === task.assignment?.id)+ if (taskRun?.grid && taskRun.firstReview === false) return+ if (!reopenHanded(task, `${name}'s verdict on “${check.description}”: ${(command.evidence.split('\n')[0] ?? '').trim()}`, context.now)) return+ message(task.id, `${task.assignment!.reopened!.why} ${BACK_WITH_YOU}`, [task.assignment!.agentId], null, SYSTEM_ROW)+ recordTaskState(state, task, context.now)+ }+ if (!command.passed && !byAssignee) reopen(group)// Its Reviewer's verdict asking for changes: its own review task waits for the new revision (liveness.ts waitingForRevision).if (!command.passed && !byAssignee && actor.kind === 'agent') changesRequested(state, group, actor.agentId, context.now)// A step's own agent failing its step's check asks its Engineer for changes the same way: a Tester's verdict has no set@@ -3957,6 +4019,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,if (!command.passed && byAssignee && actor.kind === 'agent' && group.reviewOf) {const build = state.conversations.find(c => c.id === group.reviewOf)if (build) changesRequested(state, build, actor.agentId, context.now)+ if (build) reopen(build)}if (actor.kind === 'agent') renewOwnTask(state, group, actor.agentId, context.now)breakdiff --git a/backend/src/superTabs/handed.test.ts b/backend/src/superTabs/handed.test.tsnew file mode 100644index 000000000..049555163--- /dev/null+++ b/backend/src/superTabs/handed.test.ts@@ -0,0 +1,206 @@+// Task #3399: a task whose pull request is ready for review is handed over. Its Engineer is free for new work and keeps+// its push access; a No verdict, red CI or a conflict brings the task back to it (docs/plans/2026-11-05-handed-on-ready-plan.md).+import { describe, expect, it } from 'vitest'+import { awaitingWorkers, workerIndex, type SuperTabState } from './model.js'+import type { Command } from './commands.js'+import { sweepLiveness } from './liveness.js'+import { REOPEN_OWNER_MS, reopenOnEvents } from './handed.js'+import { currentGroup } from './terminal.js'+import { workHolds, startedHolds, endedHolds, tokenTask } from '../github/holds.js'+import { stepsFixture } from './steps.test-support.js'++const PR = 'https://github.com/acme/app/pull/7'++/** The fixture's task, handed over by its Engineer, and a second task for the same Engineer. */+function handedFixture() {+ const f = stepsFixture()+ f.run({ type: 'work.status', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id, status: 'review', result: `Ready for review: ${PR} at abc1234` }, f.as(f.dev))+ const next = f.run({ type: 'conversation.create', title: 'Fix logout', brief: 'Sign out works offline.', checks: [{ description: 'Signs out offline', independent: true }], priority: 'P2', requesterId: 'owner' }, f.as(f.lead)).result.conversationId as string+ // Not a spread: it would copy the fixture's `state` getter as a snapshot.+ return Object.assign(f, { next })+}++describe('a ready pull request frees its Engineer (#3399)', () => {+ it('lets the PM assign the Engineer its next task while the first is in review', () => {+ const f = handedFixture()+ const before = f.state+ f.run({ type: 'work.assign', conversationId: f.next, agentId: f.dev }, f.as(f.lead))+ expect(f.group(f.next).assignment).toMatchObject({ agentId: f.dev, status: 'working' })+ // The first task stays open, with the same attempt, in review.+ expect(f.group(f.task).assignment).toMatchObject({ agentId: f.dev, status: 'review', id: before.conversations.find(c => c.id === f.task)!.assignment!.id })+ })++ it('still refuses a second task while the first is in the Engineer\'s hands', () => {+ const f = stepsFixture()+ const next = f.run({ type: 'conversation.create', title: 'Fix logout', brief: 'Sign out works offline.', checks: [{ description: 'Signs out offline', independent: true }], priority: 'P2', requesterId: 'owner' }, f.as(f.lead)).result.conversationId as string+ expect(() => f.run({ type: 'work.assign', conversationId: next, agentId: f.dev }, f.as(f.lead))).toThrow(expect.objectContaining({ code: 'AGENT_BUSY' }))+ })++ it('counts the Engineer as free for routing (awaitingWorkers) once it handed over', () => {+ const f = handedFixture()+ expect(workerIndex(f.state).working.has(f.dev)).toBe(false)+ expect(awaitingWorkers(f.state, 'lead').map(a => a.id)).toContain(f.dev)+ })++ it('keeps the handed task\'s GitHub hold, adds the new task\'s, and ends neither', () => {+ const f = handedFixture()+ const handedAt = structuredClone(f.state)+ expect(workHolds(handedAt)).toEqual([{ agentId: f.dev, assignmentId: f.group(f.task).assignment!.id }])+ f.run({ type: 'work.assign', conversationId: f.next, agentId: f.dev }, f.as(f.lead))+ expect(endedHolds(handedAt, f.state)).toEqual([])+ expect(startedHolds(handedAt, f.state)).toEqual([{ agentId: f.dev, assignmentId: f.group(f.next).assignment!.id }])+ })++ it('does not mark the Engineer finished when its handed task is done while it works on the next', () => {+ const f = handedFixture()+ f.run({ type: 'work.assign', conversationId: f.next, agentId: f.dev }, f.as(f.lead))+ f.run({ type: 'work.status', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id, status: 'done', result: `Merged ${PR}` }, f.as(f.dev))+ expect(f.state.agents.find(a => a.id === f.dev)!.workDecision).toBeUndefined()+ })++ it('gives the GitHub token for the task in the Engineer\'s hands first, then the handed one, and none without either', () => {+ const f = handedFixture()+ const dev = f.state.agents.find(a => a.id === f.dev)!+ // Only the handed task: it still gets a token, to push fixes.+ expect(tokenTask(f.state, dev)?.id).toBe(f.task)+ // A new task listed after it in the Swarm is still the one it pushes for now.+ f.run({ type: 'work.assign', conversationId: f.next, agentId: f.dev }, f.as(f.lead))+ expect(tokenTask(f.state, dev)?.id).toBe(f.next)+ f.run({ type: 'work.status', conversationId: f.next, assignmentId: f.group(f.next).assignment!.id, status: 'done', result: 'Merged' }, f.as(f.dev))+ f.run({ type: 'work.status', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id, status: 'done', result: `Merged ${PR}` }, f.as(f.dev))+ expect(tokenTask(f.state, dev)).toBeUndefined()+ })+})++const MINUTE = 60_000+/** The Engineer's machine last reported at [receivedAt]: its session running with progress then (busy on another task), or+ * stopped. */+function report(state: SuperTabState, receivedAt: number, session: 'running' | 'stopped' = 'running') {+ state.machines = [{ machineId: 'host', name: 'Studio', observation: { runningHarnessIds: session === 'running' ? ['dev'] : [],+ stoppedHarnessIds: session === 'stopped' ? ['dev'] : [], receivedAt, harnessProgress: { dev: receivedAt } } }] as never+}++describe('a handed task is never lost for its Engineer (#3399)', () => {+ it('stays in review when the Engineer\'s session stops, its machine goes offline or it hits a usage limit', () => {+ const stopped = handedFixture()+ report(stopped.state, stopped.now, 'stopped')+ expect(sweepLiveness(stopped.state, stopped.now)).toEqual([])+ expect(stopped.group(stopped.task).assignment!.status).toBe('review')+ const offline = handedFixture()+ report(offline.state, offline.now)+ expect(sweepLiveness(offline.state, offline.now + 10 * MINUTE)).toEqual([])+ expect(offline.group(offline.task).assignment!.status).toBe('review')+ const limited = handedFixture()+ Object.assign(limited.state.agents.find(a => a.id === limited.dev)!, { alerting: ['limit'], limitedUntil: new Date(limited.now + 60 * MINUTE).toISOString() })+ expect(sweepLiveness(limited.state, limited.now)).toEqual([])+ expect(limited.group(limited.task).assignment!.status).toBe('review')+ })+})++describe('No, red CI or a conflict reopens the task pinned to its owner (#3399)', () => {+ const reviewed = () => {+ const f = handedFixture()+ const rev = f.add('rev', f.task)+ const before = structuredClone(f.group(f.task))+ return Object.assign(f, { rev, before })+ }+ const fail = (f: ReturnType<typeof reviewed>, by: string, conversationId = f.task) => {+ const group = f.group(conversationId)+ return f.run({ type: 'work.check', conversationId, assignmentId: group.assignment!.id, checkId: group.checks[0]!.id, passed: false,+ evidence: 'Ready to merge: No. The offline path has no test.' }, f.as(by))+ }++ it('a Reviewer\'s failed check brings the same attempt back to its Engineer, who is told why', () => {+ const f = reviewed()+ const effects = fail(f, f.rev)+ const after = f.group(f.task)+ expect(after.assignment).toMatchObject({ id: f.before.assignment!.id, agentId: f.dev, status: 'working', reopened: { at: f.now } })+ expect(after.assignment!.reopened!.why).toContain('The offline path has no test.')+ // Built by: the attempt and its run stay the Engineer's.+ const builtBy = (runs: Array<{ assignmentId: string; agentId?: string }> | undefined) => runs?.map(r => [r.assignmentId, r.agentId])+ expect(builtBy(after.ledger?.runs)).toEqual(builtBy(f.before.ledger?.runs))+ expect(builtBy(after.ledger?.runs)).toEqual([[f.before.assignment!.id, f.dev]])+ expect(effects.messages).toContainEqual(expect.objectContaining({ conversationId: f.task, recipients: [f.dev], text: expect.stringContaining('back with you') }))+ // The hold is the same assignment's: none starts or ends.+ expect(workHolds(f.state)).toEqual([{ agentId: f.dev, assignmentId: f.before.assignment!.id }])+ })++ it('the Engineer\'s own failed check does not reopen it', () => {+ const f = reviewed()+ fail(f, f.dev)+ expect(f.group(f.task).assignment).toMatchObject({ status: 'review' })+ expect(f.group(f.task).assignment!.reopened).toBeUndefined()+ })++ it('a step\'s own agent failing its step\'s check reopens the task it reviews', () => {+ const f = reviewed()+ const step = f.step('Test', f.as(f.dev), f.task, [{ description: 'Works on a phone', independent: true }])+ const tester = f.add('tester', step)+ f.run({ type: 'work.assign', conversationId: step, agentId: tester }, f.as(f.dev))+ fail(f, tester, step)+ expect(f.group(f.task).assignment).toMatchObject({ agentId: f.dev, status: 'working', reopened: { at: f.now } })+ })++ it('CI failing on the head, or a merge conflict, reopens it; CI passing does not', () => {+ for (const key of ['ci-red:abc1234', 'conflict:abc1234']) {+ const f = reviewed()+ const told = reopenOnEvents(f.group(f.task), [{ key, text: 'CI failed on your pull request #7.' }], f.now)+ expect(f.group(f.task).assignment).toMatchObject({ status: 'working', reopened: { at: f.now, why: 'CI failed on your pull request #7.' } })+ expect(told[0]!.text).toMatch(/^CI failed on your pull request #7\. .*back with you/)+ }+ const green = reviewed()+ const told = reopenOnEvents(green.group(green.task), [{ key: 'ci-green:abc1234', text: 'CI passed.' }], green.now)+ expect(told).toEqual([{ key: 'ci-green:abc1234', text: 'CI passed.' }])+ expect(green.group(green.task).assignment!.status).toBe('review')+ })++ it('is picked up by the Engineer\'s own post in the task, then kept as any working task', () => {+ const f = reviewed()+ fail(f, f.rev)+ f.tick(10 * MINUTE)+ f.run({ type: 'message.send', conversationId: f.task, text: 'Fixing the offline test now.', replyTo: null, recipientIds: [] } as Command, f.as(f.dev))+ expect(f.group(f.task).assignment!.reopened).toBeUndefined()+ report(f.state, f.now + REOPEN_OWNER_MS)+ sweepLiveness(f.state, f.now + REOPEN_OWNER_MS)+ expect(f.group(f.task).assignment!.status).toBe('working')+ })++ it('is released to anyone free once its Engineer has not picked it up in 60 minutes', () => {+ const f = reviewed()+ fail(f, f.rev)+ const reopenedAt = f.now+ // Busy on its next task: its session keeps reporting progress, which keeps any working task's lease.+ report(f.state, reopenedAt + REOPEN_OWNER_MS)+ expect(sweepLiveness(f.state, reopenedAt + REOPEN_OWNER_MS)).toEqual([])+ expect(f.group(f.task).assignment!.status).toBe('working')+ report(f.state, reopenedAt + REOPEN_OWNER_MS + 1)+ sweepLiveness(f.state, reopenedAt + REOPEN_OWNER_MS + 1)+ expect(f.group(f.task).assignment).toMatchObject({ status: 'lost', lost: { reason: expect.stringContaining('60 minutes') } })+ })++ it('is released at once when its Engineer is down', () => {+ const f = reviewed()+ fail(f, f.rev)+ report(f.state, f.now, 'stopped')+ sweepLiveness(f.state, f.now)+ expect(f.group(f.task).assignment!.status).toBe('lost')+ })++ it('is handed over again by the Engineer\'s next Ready, which clears the reopen', () => {+ const f = reviewed()+ fail(f, f.rev)+ f.run({ type: 'work.status', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id, status: 'review', result: `Ready for review: ${PR} at def5678` }, f.as(f.dev))+ expect(f.group(f.task).assignment).toMatchObject({ status: 'review' })+ expect(f.group(f.task).assignment!.reopened).toBeUndefined()+ })+})++describe('an Engineer\'s terminal rows go to the task in its hands (#3399, review of #3221)', () => {+ it('names its working task, not the one it handed over, and the handed one when nothing else is open', () => {+ const f = handedFixture()+ const dev = () => f.state.agents.find(a => a.id === f.dev)!+ expect(currentGroup(f.state, dev()).id).toBe(f.task)+ f.run({ type: 'work.assign', conversationId: f.next, agentId: f.dev }, f.as(f.lead))+ expect(currentGroup(f.state, dev()).id).toBe(f.next)+ })+})diff --git a/backend/src/superTabs/handed.ts b/backend/src/superTabs/handed.tsnew file mode 100644index 000000000..cb0c8435c--- /dev/null+++ b/backend/src/superTabs/handed.ts@@ -0,0 +1,54 @@+// A task whose pull request is ready for review is handed over (task #3399, docs/plans/2026-11-05-handed-on-ready-plan.md).+// Its Engineer is free for new work (model.ts occupiesAgent: every "is this agent busy" check reads it) and keeps its GitHub+// push access (github/holds.ts HOLDING keeps `review`). A No verdict, red CI or a merge conflict brings the same attempt back+// to that Engineer; if it is down, or has not picked it up within REOPEN_OWNER_MS, the task is lost, so anyone free in the+// lane takes it (liveness.ts). A dispatcher looking for a free agent reads occupiesAgent from here.+import { handed, type Assignment, type Conversation } from './model.js'+import type { PullRequestEvent } from './pullRequestEvents.js'++export { handed, occupiesAgent } from './model.js'++/** How long a reopened task waits for its own Engineer before anyone free may take it. One place until the project rules+ * record (#3393) holds the Swarm's numbers. */+export const REOPEN_OWNER_MS = 60 * 60_000+/** What the Engineer is told after why its task came back. */+export const BACK_WITH_YOU = 'Your task is back with you: fix it on the same branch and mark it ready for review again.'+/** The PR watch's events that reopen a handed task (pullRequestEvents.ts keys): CI failed on the head, or a merge conflict. */+const REOPENS = /^(ci-red|conflict):/+const WHY_MAX = 300++/** Brings a handed [group] back to its Engineer, in the same attempt: same assignment id, so its GitHub hold neither ends nor+ * starts, and its run ledger ("built by") is untouched. Its lease runs REOPEN_OWNER_MS from now. False when it is not handed. */+export function reopenHanded(group: Conversation, why: string, now: number): boolean {+ if (!handed(group)) return false+ const assignment = group.assignment!+ assignment.status = 'working'+ assignment.reopened = { at: now, why: why.trim().slice(0, WHY_MAX) }+ assignment.progressAt = now+ assignment.leaseUntil = Math.max(assignment.leaseUntil ?? 0, now + REOPEN_OWNER_MS)+ return true+}++/** The PR watch's new [events] for [group]: the first that reopens it does so, and its message to the Engineer says the task is+ * back with it. The events as they are told. */+export function reopenOnEvents(group: Conversation, events: PullRequestEvent[], now: number): PullRequestEvent[] {+ const trigger = events.find(event => REOPENS.test(event.key))+ if (!trigger || !reopenHanded(group, trigger.text, now)) return events+ return events.map(event => event === trigger ? { ...event, text: `${event.text} ${BACK_WITH_YOU}` } : event)+}++/** Its Engineer's own status, check or post in a reopened task picks it up: from then it is any working task. */+export function pickUp(assignment: Assignment): void {+ delete assignment.reopened+}++/** When a reopened task not picked up stops waiting for its Engineer, or undefined. */+export const unclaimedAt = (assignment: Assignment): number | undefined =>+ assignment.reopened ? assignment.reopened.at + REOPEN_OWNER_MS : undefined++/** Why a reopened task leaves its Engineer now: it did not pick it up in REOPEN_OWNER_MS. Null otherwise. */+export function unclaimedReason(assignment: Assignment, now: number): string | null {+ const until = unclaimedAt(assignment)+ return until !== undefined && now > until+ ? `it came back to it (${assignment.reopened!.why.replace(/[.\s]+$/, '')}) and it did not pick it up within ${REOPEN_OWNER_MS / 60_000} minutes` : null+}diff --git a/backend/src/superTabs/liveness.test.ts b/backend/src/superTabs/liveness.test.tsindex 2994b6898..e738b5855 100644--- a/backend/src/superTabs/liveness.test.ts+++ b/backend/src/superTabs/liveness.test.ts@@ -158,11 +158,17 @@ describe('a task waiting for review', () => {expect(status(offline, handedOver + 4 * MINUTE)).toMatchObject({ status: 'lost', lost: { reason: 'its machine Mac has been offline for 2 minutes' } })})- it('is still lost at once when its session stops or its machine goes offline', () => {+ // Task #3399: a handed task waits on its Reviewers and CI, not its Engineer, so neither loses it (handed.ts). An older skill's+ // working hand-off is still the Engineer's own work.+ it('is not lost when its session stops or its machine goes offline, while an older skill\'s working hand-off still is', () => {const stopped = quiet('review', 1)stopped.machines![0]!.observation!.stoppedHarnessIds = ['h']- expect(status(stopped, handedOver + MINUTE)).toMatchObject({ status: 'lost', lost: { reason: 'its session on Mac stopped' } })- expect(status(quiet('review', 1), handedOver + 4 * MINUTE)).toMatchObject({ status: 'lost', lost: { reason: 'its machine Mac has been offline for 2 minutes' } })+ expect(status(stopped, handedOver + MINUTE)).toMatchObject({ status: 'review' })+ expect(status(quiet('review', 1), handedOver + 4 * MINUTE)).toMatchObject({ status: 'review' })+ const older = swarm(assignment({ status: 'working', result: 'Ready for review: abc1234', leaseUntil: handedOver + LEASE_MS, progressAt: handedOver }),+ { receivedAt: handedOver + MINUTE, harnessProgress: { h: handedOver } })+ older.machines![0]!.observation!.stoppedHarnessIds = ['h']+ expect(status(older, handedOver + MINUTE)).toMatchObject({ status: 'lost', lost: { reason: 'its session on Mac stopped' } })})})diff --git a/backend/src/superTabs/liveness.ts b/backend/src/superTabs/liveness.tsindex f5d3e75d1..266da1d40 100644--- a/backend/src/superTabs/liveness.ts+++ b/backend/src/superTabs/liveness.ts@@ -15,6 +15,7 @@ import { coordinatorNameOf } from './instructions.js'import { waitedOn } from './leaderboard/record.js'import { isStep } from './steps.js'import { endedReply } from './taskLine.js'+import { handed, pickUp, unclaimedAt, unclaimedReason } from './handed.js'// Work never sits with a dead owner (design: "A Swarm that never stops", 2026-10-26). A worker's active assignment is held// by a lease that its progress renews. A dead, stalled or limited worker loses it within minutes: the assignment becomes@@ -232,7 +233,11 @@ function workerTasks(state: SuperTabState): Array<{ group: Conversation; assignm/** The worker's own status, check or message in its task's group renews its lease. A Reviewer or Tester checks and posts in* the build's group, so there it renews its own linked task (reviewOf), never another agent's. */export function renewOwnTask(state: SuperTabState, group: Conversation, agentId: string, now: number): void {- if (activeWork(group) && group.assignment!.agentId === agentId) renewLease(group.assignment!, now)+ if (activeWork(group) && group.assignment!.agentId === agentId) {+ renewLease(group.assignment!, now)+ // A task that came back to it (handed.ts, #3399) is picked up by its own progress there.+ pickUp(group.assignment!)+ }for (const linked of ownLinkedTasks(state, group, agentId)) renewLease(linked.assignment!, now)}@@ -292,10 +297,13 @@ function limitReason(worker: Agent, now: number): string | null {* or undefined when none can. Reports that keep its session running with progress no older can only move it later. */export function nextLossAt(state: SuperTabState, machineId: string): number | undefined {const steps = stepIndex(state)- const ends = workerTasks(state)- .filter(({ group, worker, assignment }) => worker.machineId === machineId && !waitingForReview(assignment) && !waitingForRevision(state, group)+ const mine = workerTasks(state).filter(({ worker }) => worker.machineId === machineId)+ const ends = [...mine+ .filter(({ group, worker, assignment }) => !waitingForReview(assignment) && !waitingForRevision(state, group)&& !waitingOnSteps(state, group, steps) && !waitingOnPerson(state, group, worker, assignment))- .map(({ group, assignment, worker }) => leaseEnd(group, assignment, reportRenewedAt(state, worker)))+ .map(({ group, assignment, worker }) => leaseEnd(group, assignment, reportRenewedAt(state, worker))),+ // A task back with its Engineer and not picked up leaves it then, whatever it waits on (handed.ts).+ ...mine.map(({ assignment }) => unclaimedAt(assignment))].filter((end): end is number => end !== undefined)return ends.length ? Math.min(...ends) : undefined}@@ -309,6 +317,8 @@ const reopening = (worker: Agent, now: number): boolean => {/** Why a worker has lost its task now, or null while it still holds it. Only a machine that has reported can be offline. */function lostReason(state: SuperTabState, group: Conversation, worker: Agent, assignment: Assignment, now: number, steps: StepIndex): string | null {+ // A handed task waits on its Reviewers and CI, not on its Engineer, which may be down or at work elsewhere (task #3399).+ if (handed(group)) return nullconst pool = state.machines?.find(m => m.machineId === worker.machineId)// A crew member's host reopens its session in place (crew.ts): it keeps its task for the reopen's grace.if (pool?.observation?.stoppedHarnessIds.includes(worker.harnessId) && !reopening(worker, now)) return sessionStopped(pool.name)@@ -318,6 +328,9 @@ function lostReason(state: SuperTabState, group: Conversation, worker: Agent, as// Its host alerts only after ten minutes of retries without an answer (cli superTabs/terminal.ts MODEL_WAIT_MS), so a// short burst of failures that recovers never gets here.if (worker.alerting?.includes('model')) return 'its model keeps failing'+ // Back with its Engineer and not picked up in time: anyone free in the lane takes it (handed.ts, #3399).+ const unclaimed = unclaimedReason(assignment, now)+ if (unclaimed) return unclaimedif (waitingForReview(assignment) || waitingForRevision(state, group) || waitingOnSteps(state, group, steps) || waitingOnPerson(state, group, worker, assignment)) return nullconst end = leaseEnd(group, assignment, reportRenewedAt(state, worker))if (end !== undefined && now > end) {diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.tsindex ca369a643..22d5e9bca 100644--- a/backend/src/superTabs/machines.ts+++ b/backend/src/superTabs/machines.ts@@ -3,7 +3,7 @@ import { createHash } from 'node:crypto'import { z } from 'zod'import { engineUnusable, machineSuspensionReason } from './engineHealth.js'import { MAX_HARNESSES, tokensByModelSchema } from './costs/tokens.js'-import { activeWork, fail, person, stableId, type Actor, type Agent, type AgentStart, type AgentStartRequest, type MessageDraft, type SuperTabState } from './model.js'+import { activeWork, occupiesAgent, fail, person, stableId, type Actor, type Agent, type AgentStart, type AgentStartRequest, type MessageDraft, type SuperTabState } from './model.js'import { WORKSPACE_LABEL } from './workspaces.js'import { startFinished } from './parts/write.js'import { agentProjectId, canReadAgent, canReadProject, groupProject, ledProject, ownsProject, projectOf, projectsOf, teamAccountPool, type SwarmProject } from './projects.js'@@ -735,7 +735,9 @@ export function removalPreview(state: SuperTabState, actor: Actor, machineId: stblockedBy: led ? canReadProject(state, actor, led)? { projectId: led.id, projectName: led.name } : { reason: "A Product Manager of a project you can't see runs on this machine." } : null,agents: visibleAgents.map(a => {- const task = state.conversations.find(c => activeWork(c) && c.assignment!.agentId === a.id)+ // The task in its hands first, then one it handed over (#3399).+ const task = state.conversations.find(c => occupiesAgent(c) && c.assignment!.agentId === a.id)+ ?? state.conversations.find(c => activeWork(c) && c.assignment!.agentId === a.id)return { id: a.id, name: a.displayName ?? a.name, projectName: projectsOf(state).find(p => p.id === agentProjectId(state, a))?.name ?? '',...(task ? { task: task.title } : {}) }}),diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex 0126c30f8..14bb6ee9b 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -274,6 +274,10 @@ export interface Assignment {* never written since (phase 4: the server opens and counts no review), kept on older rows. */handoffs?: numberverdicts?: ReviewVerdict[]+ /** A handed task brought back to its Engineer (handed.ts reopenHanded): when, and why (a No verdict, red CI, a conflict).+ * Its Engineer's own status, check or post in the task picks it up and clears it; with none in REOPEN_OWNER_MS the task is+ * lost, so anyone free takes it (liveness.ts). The next status clears it too. */+ reopened?: { at: number; why: string }/** Why and when it was lost (status `lost`); after a usage limit whose screen gave a reset time, when its own agent may* take it back (work.resume) unless it was handed on first. */lost?: { reason: string; at: number; resumeAt?: string }@@ -770,6 +774,8 @@ export interface CommandEffects {lateDeliveries?: Array<{ messageId: string; conversationId: string; agentId: string; author: { kind: 'person'; id: string; generation: string }; lead?: true }>/** A project's new instructions revision, written outside the tab state by the store (instructions.ts). */instructions?: import('./instructions.js').InstructionsWrite+ /** A project's new rules revision, written outside the tab state by the store (policyStore.ts). */+ projectRules?: import('./policy.js').RulesWrite/** A coordinator's note kept or a note removed, written outside the tab state by the store (instructions.ts). */notes?: import('./instructions.js').NotesWrite/** Reactions the Swarm adds as a task's agent on the message that asked for it (taskLine.ts), written by the store as that@@ -788,8 +794,16 @@ export class SuperTabError extends Error {export function fail(code: string, message: string, status = 409, details?: Record<string, unknown>): never { throw new SuperTabError(code, message, status, false, details) }export const stableId = (...parts: string[]): string => createHash('sha256').update(JSON.stringify(parts)).digest('hex').slice(0, 24)export const actorKey = (actor: Actor): string => actor.kind === 'person' ? `person:${actor.userId}` : `agent:${actor.agentId}`+/** The task is open: assigned, and its attempt not ended. A handed task (below) is open too: archive, steps, deletion and the+ * GitHub token hold all read this. Whether its agent is busy is occupiesAgent. */export const activeWork = (group: Conversation): boolean => !!group.assignment &&!['done', 'stopped', 'cancelled', 'lost'].includes(group.assignment.status)+/** A task its Engineer handed over (task #3399, handed.ts): its pull request is ready for review, the status its Engineer sets+ * when it marks it ready. The task stays open and its Engineer keeps its push access, but the work waits on others, so the+ * Engineer is free for new work. A step's own Ready is its verdict, not a hand-over. */+export const handed = (group: Conversation): boolean => !group.reviewOf && group.assignment?.status === 'review'+/** Work in its agent's hands, which makes the agent busy: open and not handed over. Every "is this agent busy" check reads it. */+export const occupiesAgent = (group: Conversation): boolean => activeWork(group) && !handed(group)/** What awaitingWorkers reads of the conversations, from one pass over them: the agents leading any conversation, those with* active work, and each agent's assigned groups (not lost) in conversation order. Scanning every conversation per agent and@@ -801,7 +815,8 @@ export function workerIndex(state: SuperTabState): WorkerIndex {for (const c of state.conversations) {if (c.leadId !== null) leaders.add(c.leadId)if (!c.assignment) continue- if (activeWork(c)) working.add(c.assignment.agentId)+ // Busy with work in its hands; a task it handed over leaves it free (task #3399).+ if (occupiesAgent(c)) working.add(c.assignment.agentId)// A lost task's agent did not finish it, even once the task is cancelled: it may be gone.if (c.assignment.lost) continueconst groups = groupsByAgent.get(c.assignment.agentId)@@ -817,7 +832,7 @@ export function awaitingWorkers(state: SuperTabState, projectId: string, index =if (index.leaders.has(a.id) || index.working.has(a.id)) return falseconst groups = index.groupsByAgent.get(a.id) ?? []return (a.projectId ?? groups.map(c => groupProject(state, c).id)[0] ?? 'lead') === projectId &&- (a.workDecision === 'awaiting' || (!a.workDecision && groups.some(c => !activeWork(c))))+ (a.workDecision === 'awaiting' || (!a.workDecision && groups.some(c => !occupiesAgent(c))))})}/** A task's work ended: its worker is marked `awaiting`, whatever its kind. People see the mark; no command reads it, so@@ -826,6 +841,8 @@ export function awaitingWorkers(state: SuperTabState, projectId: string, index =export function finishWorker(state: SuperTabState, workerId: string): void {const target = state.agents.find(a => a.id === workerId)if (!target || state.conversations.some(c => c.leadId === target.id) || target.workDecision === 'stop') return+ // A handed task that ends while its Engineer works on its next one leaves that Engineer busy (task #3399).+ if (state.conversations.some(c => occupiesAgent(c) && c.assignment!.agentId === target.id)) returntarget.workDecision = 'awaiting'}diff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.tsindex be606b6e9..4adcf1e40 100644--- a/backend/src/superTabs/parts/light.test.ts+++ b/backend/src/superTabs/parts/light.test.ts@@ -9,7 +9,7 @@ import { FINISHED, GROUP_FIELDS } from './light.js'const assignment: Required<Assignment> = {id: 'w', agentId: 'a', status: 'working', configuration: { engine: 'codex', model: null, effort: null, contextWindow: null, engineVersion: null },execution: { machineId: 'm', harnessId: 'h', machineOwnerId: 'o' }, result: null, recordingProgress: { at: 1, revision: 1 }, leaseUntil: 1, progressAt: 1, askedOf: 'p', reviewFoundAt: 1, changesRequestedAt: 1, toldEngineerAt: 1,- handoffs: 1, verdicts: [{ by: 'agent:r', passed: true, handoff: 1, review: 'g' }], lost: { reason: 'r', at: 1 },+ reopened: { at: 1, why: 'r' }, handoffs: 1, verdicts: [{ by: 'agent:r', passed: true, handoff: 1, review: 'g' }], lost: { reason: 'r', at: 1 },}const conversation: Required<Conversation> = {id: 'g', kind: 'leads', projectId: 'p', number: 1, title: 't', leadId: null, agentIds: [], archived: false, brief: '',diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.tsindex 0d125c0f5..5b24b21a3 100644--- a/backend/src/superTabs/parts/light.ts+++ b/backend/src/superTabs/parts/light.ts@@ -19,17 +19,18 @@ const running = { $and: [{ $ne: [{ $type: '$data.assignment.status' }, 'missing'/*** Which conversation fields a light load keeps. `always`: who reads it and who is in it, and how its work ended (a lost* task's worker awaits no decision, model.ts awaitingWorkers), with the work's id: a host row tells whether a task lost to a- * usage limit is still that one before its host resumes it (read/hostRows.ts). `whenRunning`: what other projects' work and host rows read of+ * usage limit is still that one before its host resumes it (read/hostRows.ts), and whether it is a step, whose Ready is no hand-over+ * (model.ts handed: a handed task's Engineer reads as free). `whenRunning`: what other projects' work and host rows read of* running work. `unread`: what visibility checks, derived values and host rows never read. light.test.ts fails when* model.ts gains a field this does not place.*/export const GROUP_FIELDS = {always: ['id', 'kind', 'projectId', 'leadId', 'agentIds', 'archived', 'audience', 'dormant', 'assignment.id', 'assignment.agentId', 'assignment.status',- 'assignment.lost'],+ 'assignment.lost', 'reviewOf'],whenRunning: ['title', 'task.owns', 'assignment.execution', 'assignment.result'],- unread: ['number', 'brief', 'reviewOf', 'teamWritten', 'teamWrittenBy', 'step', 'reviewStamp', 'checks', 'lastMessageSequence', 'lastMainSequence', 'lastPersonSequence', 'heardAt', 'pullRequestUrls', 'pullRequestEvents', 'cards', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals', 'buddyName', 'buddySessions', 'buddyDownTold', 'liveness', 'leadAction', 'stepUp', 'queueRank', 'notBefore', 'priority',+ unread: ['number', 'brief', 'teamWritten', 'teamWrittenBy', 'step', 'reviewStamp', 'checks', 'lastMessageSequence', 'lastMainSequence', 'lastPersonSequence', 'heardAt', 'pullRequestUrls', 'pullRequestEvents', 'cards', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals', 'buddyName', 'buddySessions', 'buddyDownTold', 'liveness', 'leadAction', 'stepUp', 'queueRank', 'notBefore', 'priority','assignment.configuration', 'assignment.recordingProgress', 'assignment.leaseUntil', 'assignment.progressAt', 'assignment.askedOf', 'assignment.reviewFoundAt', 'assignment.changesRequestedAt', 'assignment.toldEngineerAt',- 'assignment.handoffs', 'assignment.verdicts'],+ 'assignment.reopened', 'assignment.handoffs', 'assignment.verdicts'],} as constconst LIGHT_GROUP = {_id: 0, key: 1, version: 1, changedAt: 1, ordinal: 1, dormant: 1,diff --git a/backend/src/superTabs/parts/touches.ts b/backend/src/superTabs/parts/touches.tsindex 246502cef..2126d09ad 100644--- a/backend/src/superTabs/parts/touches.ts+++ b/backend/src/superTabs/parts/touches.ts@@ -83,7 +83,7 @@ export function touchesFor(command: Command, actor: Actor, before: SuperTabStatebreakcase 'project.report': case 'project.repository':// The coordinator's own writes check it leads the project, which a concurrent Lead change ends (review of phase 2).- case 'instructions.save': case 'note.add': case 'note.remove': case 'project.coordinatorName':+ case 'instructions.save': case 'note.add': case 'note.remove': case 'project.coordinatorName': case 'rules.set':leadCheck(command.projectId)break// An older CLI's rule is a save to its project's instructions, the coordinator's like instructions.save (commands.ts).diff --git a/backend/src/superTabs/policy.test.ts b/backend/src/superTabs/policy.test.tsnew file mode 100644index 000000000..0ba3ace87--- /dev/null+++ b/backend/src/superTabs/policy.test.ts@@ -0,0 +1,267 @@+import { describe, expect, it } from 'vitest'+import { applyCommand, type Command, type CommandContext } from './commands.js'+import { createSuperTab, type Actor, type AgentConfiguration } from './model.js'+import { RULE_MESSAGE_MS } from './rules.js'+import { globMatch, MAX_RULES_BYTES, projectRulesSchema, requiredReads, rulesDiff, rulesEqual, SEED_RULES, testsFor, type ProjectRules } from './policy.js'++const copy = (): ProjectRules => structuredClone(SEED_RULES)+const refused = (value: unknown) => projectRulesSchema.safeParse(value).success === false++describe('the project rules record', () => {+ // Task #3393 (anh Dee's Swarm redesign, 11-05): the numbers the project runs on today, in project data, not constants.+ it('seeds today\'s numbers', () => {+ expect(projectRulesSchema.parse(SEED_RULES)).toEqual(SEED_RULES)+ expect(SEED_RULES.releaseWindow).toEqual({ start: '09:00', end: '18:00', timeZone: 'Asia/Ho_Chi_Minh' })+ // The backend stays off the morning peak (Shipper, #3405).+ expect(SEED_RULES.releasePace).toEqual({ backendEveryMinutes: 120, appsAfterVisibleBatch: true, backendPause: { start: '09:00', end: '10:00' } })+ expect(SEED_RULES.reviews.defaultReads).toBe(1)+ expect(SEED_RULES.reviews.rows.map(r => [r.area, r.reads])).toEqual(['Sign-in', 'Tokens', 'Encryption', 'Access', 'Buddy guard', 'Device links', 'Deletion']+ .map(area => [area, 2]))+ // Every security row has its paths, so a change there is counted (#3401, #3402: fail closed).+ for (const row of SEED_RULES.reviews.rows) expect(row.paths.length).toBeGreaterThan(0)+ expect(SEED_RULES.reviews.test.map(t => t.where)).toEqual(['Desktop on a Mac', 'The CLI on a Mac and on a Linux machine',+ 'The phone app in a simulator', 'The web in a browser', 'Install and update on a Mac', 'Firmware on the device plugged into a machine'])+ // The merge train is opt-in per project (River, #3402).+ expect(SEED_RULES.mergeTrain).toEqual({ enabled: false, everyMinutes: 10 })+ expect(SEED_RULES).toMatchObject({ caps: [], paths: [], crew: [], lanes: [] })+ })++ it('holds caps, paths, the crew and lanes', () => {+ const rules = { ...copy(), caps: [{ name: 'Agents on the phone Mac', value: 4 }], paths: [{ name: 'Plans', path: 'docs/plans/' }],+ crew: [{ role: 'Engineer', names: ['Ledger'] }], lanes: [{ name: 'Backend', owns: ['backend/'] }] }+ expect(projectRulesSchema.parse(rules)).toEqual(rules)+ })++ it('refuses bad values', () => {+ expect(refused({ ...copy(), extra: 1 })).toBe(true)+ expect(refused({ ...copy(), releaseWindow: { ...SEED_RULES.releaseWindow, start: '25:00' } })).toBe(true)+ expect(refused({ ...copy(), releaseWindow: { ...SEED_RULES.releaseWindow, start: '18:00', end: '09:00' } })).toBe(true)+ expect(refused({ ...copy(), releaseWindow: { ...SEED_RULES.releaseWindow, timeZone: 'Mars/Base' } })).toBe(true)+ expect(refused({ ...copy(), releasePace: { ...SEED_RULES.releasePace, backendEveryMinutes: 0 } })).toBe(true)+ expect(refused({ ...copy(), releasePace: { ...SEED_RULES.releasePace, backendEveryMinutes: 1.5 } })).toBe(true)+ expect(refused({ ...copy(), releasePace: { ...SEED_RULES.releasePace, backendPause: { start: '10:00', end: '09:00' } } })).toBe(true)+ expect(refused({ ...copy(), releasePace: { ...SEED_RULES.releasePace, backendPause: { start: '9:00', end: '10:00' } } })).toBe(true)+ expect(projectRulesSchema.safeParse({ ...copy(), releasePace: { ...SEED_RULES.releasePace, backendPause: null } }).success).toBe(true)+ expect(refused({ ...copy(), reviews: { ...SEED_RULES.reviews, defaultReads: 0 } })).toBe(true)+ expect(refused({ ...copy(), reviews: { ...SEED_RULES.reviews, rows: [{ area: '', reads: 2, paths: ['**/*auth*'] }] } })).toBe(true)+ expect(refused({ ...copy(), reviews: { ...SEED_RULES.reviews, rows: [{ area: 'Tokens', reads: 2, paths: [] }, { area: 'tokens', reads: 1, paths: [] }] } })).toBe(true)+ // A glob is a relative path pattern: never absolute, never climbing out, at most 50 a row.+ for (const glob of ['/etc/**', '../**', 'a/../b', '']) {+ expect(refused({ ...copy(), reviews: { ...SEED_RULES.reviews, rows: [{ area: 'Tokens', reads: 2, paths: [glob] }] } })).toBe(true)+ }+ expect(refused({ ...copy(), reviews: { ...SEED_RULES.reviews, rows: [{ area: 'Tokens', reads: 2, paths: Array.from({ length: 51 }, (_, i) => `a${i}/**`) }] } })).toBe(true)+ // Security review of #3216: at most 4 wildcards a pattern, a double star counting as one, and no run of three stars.+ const pattern = (glob: string) => refused({ ...copy(), reviews: { ...SEED_RULES.reviews, rows: [{ area: 'Tokens', reads: 2, paths: [glob] }] } })+ for (const glob of ['*a*a*a*a*a', '**/'.repeat(5) + 'z', '**/**/**/**/*.ts', 'a???b??', '***.ts', '*'.repeat(200)]) {+ expect(pattern(glob), glob).toBe(true)+ }+ for (const glob of ['**/*buddy_guard*', '**/*.test.*', 'a/**/b/*.ts', '**/?x*']) expect(pattern(glob), glob).toBe(false)+ // The backend pause is a part of the release window (review of #3216).+ expect(refused({ ...copy(), releasePace: { ...SEED_RULES.releasePace, backendPause: { start: '08:00', end: '10:00' } } })).toBe(true)+ expect(refused({ ...copy(), releasePace: { ...SEED_RULES.releasePace, backendPause: { start: '17:00', end: '19:00' } } })).toBe(true)+ expect(refused({ ...copy(), releasePace: { ...SEED_RULES.releasePace, backendPause: { start: '09:00', end: '18:00' } } })).toBe(false)+ expect(refused({ ...copy(), reviews: { ...SEED_RULES.reviews, test: [{ where: 'Mac', paths: ['desktop/**'] }, { where: 'mac', paths: [] }] } })).toBe(true)+ expect(refused({ ...copy(), mergeTrain: { enabled: 'yes', everyMinutes: 30 } })).toBe(true)+ expect(refused({ ...copy(), caps: Array.from({ length: 51 }, (_, i) => ({ name: `Cap ${i}`, value: i })) })).toBe(true)+ expect(refused({ ...copy(), caps: [{ name: 'Agents', value: -1 }] })).toBe(true)+ expect(refused({ ...copy(), paths: [{ name: 'Plans', path: 'docs/\nplans/' }] })).toBe(true)+ const { mergeTrain: _gone, ...missing } = copy()+ expect(refused(missing)).toBe(true)+ // At most 8 KB as stored: within every list's own limits, still too big together.+ const big = { ...copy(), crew: Array.from({ length: 50 }, (_, i) => ({ role: `Role ${i}`, names: Array.from({ length: 5 }, (_, j) => `${'n'.repeat(60)}${j}`) })) }+ expect(Buffer.byteLength(JSON.stringify(big))).toBeGreaterThan(MAX_RULES_BYTES)+ expect(refused(big)).toBe(true)+ })++ it('lists what changed, by path, and nothing for an equal record', () => {+ const after = copy()+ after.releaseWindow.start = '10:00'+ after.reviews.rows = [...after.reviews.rows, { area: 'Payments', reads: 2, paths: ['**/payments/**'] }]+ after.mergeTrain.enabled = true+ expect(rulesDiff(SEED_RULES, after)).toEqual([+ { path: 'releaseWindow.start', before: '09:00', after: '10:00' },+ { path: 'reviews.rows', before: SEED_RULES.reviews.rows, after: after.reviews.rows },+ { path: 'mergeTrain.enabled', before: false, after: true },+ ])+ expect(rulesDiff(SEED_RULES, copy())).toEqual([])+ expect(rulesEqual(SEED_RULES, copy())).toBe(true)+ expect(rulesEqual(SEED_RULES, after)).toBe(false)+ })+})++const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }+const peer: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'peer', email: '[email protected]' }+const config: AgentConfiguration = { engine: 'codex', model: 'test-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }+const as = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'host-owner' })+const NOW = 5 * RULE_MESSAGE_MS++function fixture() {+ let state = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')+ let sequence = 0+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {+ const effects = applyCommand(state, actor, command, { now: NOW, operationId: `op-${++sequence}`, ...context })+ state = effects.state+ return effects+ }+ const invite = (role: 'viewer' | 'collaborator' = 'collaborator') => {+ const invited = run({ type: 'invite.create', email: peer.email, role, conversationId: 'lead' })+ run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, peer)+ }+ const add = (harnessId: string, group = 'lead', lead = false) =>+ run({ type: 'agent.add', conversationId: group, machineId: 'host', harnessId, name: harnessId, configuration: config, lead }, owner,+ { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }).result.agentId as string+ const group = () => run({ type: 'conversation.create', title: 'Offline editing', brief: 'Save edits while offline.', checks: [] }).result.conversationId as string+ return { run, invite, add, group, get state() { return state } }+}++// An earlier start keeps the seed's 09:00-10:00 backend pause inside the window.+const later = (): ProjectRules => ({ ...copy(), releaseWindow: { ...SEED_RULES.releaseWindow, start: '08:00' } })+const set = (baseRevision: number, rules: ProjectRules, extra: Partial<Extract<Command, { type: 'rules.set' }>> = {}): Command =>+ ({ type: 'rules.set', projectId: 'lead', baseRevision, rules, summary: 'Releases start at 10', ...extra })+const code = (run: () => unknown): unknown => { try { run() } catch (error) { return (error as { code?: string }).code ?? 'INVALID' } return undefined }++describe('reads and tests a change needs', () => {+ it('matches globs as the review steps do: ** any folders, * and ? in one name, ignoring case', () => {+ expect(globMatch('**/*auth*', 'backend/src/lib/ssoAuth.ts')).toBe(true)+ expect(globMatch('**/*auth*', 'oauth.ts')).toBe(true)+ expect(globMatch('desktop/**', 'desktop/lib/a.dart')).toBe(true)+ expect(globMatch('desktop/*', 'desktop/lib/a.dart')).toBe(false)+ expect(globMatch('a?c.ts', 'abc.ts')).toBe(true)+ expect(globMatch('a?c.ts', 'a/c.ts')).toBe(false)+ expect(globMatch('**/e2ee/**', 'mobile/lib/e2ee/box.dart')).toBe(true)+ expect(globMatch('docs/a.md', 'docs/aXmd')).toBe(false)+ })++ // Review of #3216 (minor 2): a saved pattern became a backtracking regex, and many `*` against a long name could stall a+ // server worker. The matcher's time grows with the name times the pattern, whatever the pattern.+ it('matches a pattern of many wildcards against a long name quickly', () => {+ const pattern = '*a'.repeat(40) + '*'+ const name = 'a'.repeat(5_000) + '/b'+ const started = performance.now()+ expect(globMatch(pattern, name)).toBe(false)+ expect(globMatch('**/' + '*a'.repeat(25) + 'z', 'x/'.repeat(500) + 'a'.repeat(3_000))).toBe(false)+ expect(performance.now() - started).toBeLessThan(500)+ expect(globMatch('**/' + '*a'.repeat(3), 'x/yaaa')).toBe(true)+ expect(globMatch('**', 'any/thing/at.all')).toBe(true)+ expect(globMatch('**/', 'a/b/')).toBe(true)+ expect(globMatch('a/**/b.ts', 'a/b.ts')).toBe(true)+ expect(globMatch('a/**/b.ts', 'a/x/y/b.ts')).toBe(true)+ expect(globMatch('a/**/b.ts', 'a/x/y/c.ts')).toBe(false)+ })++ it('asks the most reads any touched row asks, at least the default, and fails closed on files it cannot read', () => {+ expect(requiredReads(SEED_RULES, ['desktop/lib/super_tabs/view.dart'])).toBe(1)+ expect(requiredReads(SEED_RULES, ['desktop/lib/super_tabs/view.dart', 'backend/src/lib/ssoAuth.ts'])).toBe(2)+ expect(requiredReads(SEED_RULES, ['backend/src/superTabs/deletion.ts'])).toBe(2)+ expect(requiredReads(SEED_RULES, [])).toBe(1)+ expect(requiredReads(SEED_RULES, null)).toBe(2)+ const three = { ...copy(), reviews: { ...copy().reviews, defaultReads: 3 } }+ expect(requiredReads(three, ['backend/src/lib/ssoAuth.ts'])).toBe(3)+ })++ it('names where a change runs, never for tests, fixtures and docs alone', () => {+ expect(testsFor(SEED_RULES, ['desktop/lib/a.dart', 'cli/src/b.ts'])).toEqual(['Desktop on a Mac', 'The CLI on a Mac and on a Linux machine'])+ expect(testsFor(SEED_RULES, ['desktop/test/a_test.dart', 'cli/src/b.spec.ts', 'docs/plans/x.md', 'backend/src/a.ts'])).toEqual([])+ expect(testsFor(SEED_RULES, null)).toEqual([])+ })+})++describe('rules.set', () => {+ it('validates, versions and records who, when, the diff and why, and changes no state or chat', () => {+ const f = fixture()+ const before = structuredClone(f.state.projects)+ const effects = f.run(set(0, later()), owner, { projectRules: null })+ expect(effects.result).toMatchObject({ projectId: 'lead', revision: 1 })+ expect(effects.projectRules).toEqual({ projectId: 'lead', revision: 1, rules: later(), summary: 'Releases start at 10',+ diff: [{ path: 'releaseWindow.start', before: '09:00', after: '08:00' }],+ writtenBy: { kind: 'person', id: 'owner' }, askedBy: 'owner', askedIn: null, at: NOW })+ expect(effects.messages).toEqual([])+ expect(f.state.projects).toEqual(before)+ // The next revision diffs against the stored one, not the seed.+ const next = { ...later(), mergeTrain: { enabled: true, everyMinutes: 10 } }+ const second = f.run(set(1, next, { summary: 'Merge train on' }), owner, { projectRules: { revision: 1, rules: later() } })+ expect(second.projectRules).toMatchObject({ revision: 2, diff: [{ path: 'mergeTrain.enabled', before: false, after: true }], summary: 'Merge train on' })+ })++ it('refuses bad values and a summary that is not one line, storing nothing', () => {+ const f = fixture()+ expect(code(() => f.run(set(0, { ...copy(), releasePace: { ...SEED_RULES.releasePace, backendEveryMinutes: -5 } }), owner, { projectRules: null }))).toBe('INVALID')+ expect(code(() => f.run(set(0, { ...copy(), surprise: true } as ProjectRules), owner, { projectRules: null }))).toBe('INVALID')+ expect(code(() => f.run(set(0, later(), { summary: 'two\nlines' }), owner, { projectRules: null }))).toBe('INVALID')+ })++ it('refuses a save on an older revision with the current record to merge, and saves nothing for the same record', () => {+ const f = fixture()+ let refused: unknown+ try { f.run(set(0, later()), owner, { projectRules: { revision: 3, rules: later() } }) } catch (error) { refused = error }+ expect(refused).toMatchObject({ code: 'RULES_STALE', status: 409, details: { revision: 3, rules: later() } })+ expect((refused as Error).message).toContain('revision 3')+ // The record could not be read: nothing is saved over what nobody saw.+ expect(code(() => f.run(set(0, later())))).toBe('RULES_UNAVAILABLE')+ const same = f.run(set(3, later()), owner, { projectRules: { revision: 3, rules: later() } })+ expect(same.result).toMatchObject({ projectId: 'lead', revision: 3, unchanged: true })+ expect(same.projectRules).toBeUndefined()+ const seed = f.run(set(0, copy()), owner, { projectRules: null })+ expect(seed.result).toMatchObject({ revision: 0, unchanged: true })+ expect(seed.projectRules).toBeUndefined()+ })+})++describe('who changes the rules', () => {+ const asked = (conversationId: string, messageId = 'ask-1') => ({ askedIn: { conversationId, messageId } })+ const author = (kind: 'person' | 'agent', id: string) => ({ kind, id, name: id, membershipGeneration: 'tab' })+ const personAsked = (id = 'peer', createdAt = NOW - 60_000) => ({ author: author('person', id), source: false, createdAt })++ it('lets a person who may write the project change them, never a viewer', () => {+ const f = fixture()+ f.invite()+ expect(f.run(set(0, later()), peer, { projectRules: null }).projectRules).toMatchObject({ writtenBy: { kind: 'person', id: 'peer' }, askedBy: 'peer' })+ const viewer = fixture()+ viewer.invite('viewer')+ expect(code(() => viewer.run(set(0, later()), peer, { projectRules: null }))).toBe('READ_ONLY')+ })++ it('lets the project\'s PM change them only with a person\'s own chat message of this project from the last day', () => {+ const f = fixture()+ f.invite()+ const lead = f.add('lead', 'lead', true), task = f.group()+ const pm = (extra: Partial<Extract<Command, { type: 'rules.set' }>>, context: Partial<CommandContext>) =>+ () => f.run(set(0, later(), extra), as(lead), { projectRules: null, ...context })+ expect(code(pm({}, {}))).toBe('RULES_ASKED_IN_REQUIRED')+ // Quoted but not found in this tab.+ expect(code(pm(asked('lead'), {}))).toBe('RULES_ASKED_IN_REQUIRED')+ // An agent's message, a Swarm notice, and a person's message older than a day.+ expect(code(pm(asked('lead'), { askedIn: { author: author('agent', lead), source: false, createdAt: NOW } }))).toBe('RULES_ASKED_IN_REQUIRED')+ expect(code(pm(asked('lead'), { askedIn: { ...personAsked(), source: true } }))).toBe('RULES_ASKED_IN_REQUIRED')+ expect(code(pm(asked('lead'), { askedIn: personAsked('peer', NOW - RULE_MESSAGE_MS - 1) }))).toBe('RULES_ASKED_IN_REQUIRED')+ // A person who is no member any more.+ expect(code(pm(asked('lead'), { askedIn: personAsked('stranger') }))).toBe('ASKED_BY_UNAVAILABLE')+ // A person who may only read the project now (security review of #3216).+ f.state.people.find(p => p.id === 'peer')!.role = 'viewer'+ expect(code(pm(asked('lead'), { askedIn: personAsked() }))).toBe('RULES_ASKED_IN_REQUIRED')+ f.state.people.find(p => p.id === 'peer')!.role = 'collaborator'+ // A message of another project's chat: the PM reads none of it, so the quote is refused as one it cannot see.+ const other = f.run({ type: 'project.create', name: 'App', visibility: 'public', brief: '' }).result as { conversationId: string }+ expect(code(pm(asked(other.conversationId), { askedIn: personAsked() }))).toBe('NOT_FOUND')+ // In a task of this project: recorded with who asked and where.+ const effects = pm(asked(task, 'ask-2'), { askedIn: personAsked() })() as ReturnType<typeof f.run>+ expect(effects.projectRules).toMatchObject({ writtenBy: { kind: 'agent', id: lead }, askedBy: 'peer', askedIn: { conversationId: task, messageId: 'ask-2' } })+ expect(effects.messages).toEqual([])+ })++ it('refuses every other agent, the PM of another project and a Buddy', () => {+ const f = fixture()+ f.invite()+ f.add('lead', 'lead', true)+ const task = f.group(), engineer = f.add('engineer', task)+ const context = { projectRules: null, askedIn: personAsked() }+ expect(code(() => f.run(set(0, later(), asked(task)), as(engineer), context))).toBe('RULES_EDITOR_REQUIRED')+ const other = f.run({ type: 'project.create', name: 'App', visibility: 'public', brief: '' }).result as { projectId: string; conversationId: string }+ const otherLead = f.add('other-lead', other.conversationId, true)+ // Another project's PM reads nothing of this one.+ expect(code(() => f.run(set(0, later(), asked('lead')), as(otherLead), context))).toBe('NOT_FOUND')+ const buddy = f.add('buddy', task)+ f.state.agents.find(a => a.id === buddy)!.buddyOf = { personId: 'owner', generation: 'tab' }+ expect(code(() => f.run(set(0, later(), asked(task)), as(buddy), context))).toBe('BUDDY_FORBIDDEN')+ })+})diff --git a/backend/src/superTabs/policy.ts b/backend/src/superTabs/policy.tsnew file mode 100644index 000000000..e634e87b3--- /dev/null+++ b/backend/src/superTabs/policy.ts@@ -0,0 +1,233 @@+/**+ * A project's rules record (task #3393, anh Dee's Swarm redesign, 2026-11-05: code over prompts). The numbers a project runs+ * on — its release window and pace, its review table, the merge train's switch, its caps, paths, crew and lanes — kept as one+ * schema-checked record with every revision, changed by people (or the project's PM passing on a person's chat message)+ * without a release. Nothing here enters the Swarm state, the instructions read or any prompt: it is project data, read by+ * the server and shown to people. Revision 0 is the seed below, never stored until the first save (policyStore.ts).+ */+import { z } from 'zod'++/** The record as stored, as JSON: small enough that a reader reads every revision kept. */+export const MAX_RULES_BYTES = 16_384+/** Revisions kept per project, the current one included; the save that writes the 51st deletes the oldest. */+export const MAX_RULES_REVISIONS = 50+const MAX_LIST = 50+/** Wildcards a path pattern may hold, a double star counting as one. */+export const MAX_WILDCARDS = 4++const clock = z.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/, 'A time of day as HH:MM, 00:00 to 23:59.')+const timeZone = z.string().min(1).max(64).refine(zone => {+ try { new Intl.DateTimeFormat('en-US', { timeZone: zone }); return true } catch { return false }+}, 'An IANA time zone, such as Asia/Ho_Chi_Minh.')+/** One line of text a person reads: no line breaks or control characters. */+const line = (max: number) => z.string().trim().min(1).max(max).regex(/^[^\x00-\x1f\x7f]*$/, 'One line, without control characters.')+const minutes = z.number().int().min(1).max(10_080)+const reads = z.number().int().min(1).max(5)+/** A path pattern relative to the repository (globMatch): never absolute, never climbing out of it. */+const glob = z.string().trim().min(1).max(200).regex(/^[A-Za-z0-9_.*?\/@+ -]+$/, 'A path pattern: letters, digits and _ . * ? / @ + - only.')+ .refine(g => !g.startsWith('/') && !g.split('/').includes('..'), 'A path pattern relative to the repository, without "..".')+ // At most MAX_WILDCARDS a pattern, a double star counting as one, and no run of three stars (security review of #3216).+ // globMatch is linear whatever the pattern; this keeps patterns readable and the matcher's work small.+ .refine(g => !g.includes('***') && (g.match(/\*\*|\*|\?/g)?.length ?? 0) <= MAX_WILDCARDS,+ 'A path pattern has at most 4 wildcards (* ? or **).')+const globs = z.array(glob).max(MAX_LIST)+/** A list whose entries' [key] differ, ignoring case: two rows for one area would leave the table saying two things. */+const distinct = <T extends z.ZodTypeAny>(item: T, key: (entry: z.infer<T>) => string, what: string) =>+ z.array(item).max(MAX_LIST).refine(list => new Set(list.map(e => key(e).toLowerCase())).size === list.length, `Each ${what} once.`)++export const projectRulesSchema = z.object({+ /** When releases go out, in a local time of day; the end comes after the start, the same day. */+ releaseWindow: z.object({ start: clock, end: clock, timeZone }).strict()+ .refine(w => w.start < w.end, 'The release window ends after it starts, the same day.'),+ /** The backend at most every N minutes (each release reconnects everyone); Desktop, CLI and web after each visible batch. */+ /** `backendPause`: a part of the window, in its time zone, when no backend release goes out (the morning peak); null for none. */+ releasePace: z.object({ backendEveryMinutes: minutes, appsAfterVisibleBatch: z.boolean(),+ backendPause: z.object({ start: clock, end: clock }).strict().refine(p => p.start < p.end, 'The pause ends after it starts.').nullable() }).strict(),+ /** How many independent reads a change gets: the default, more for a change to the paths of an area listed; where a change+ * runs, for its test; and the paths whose change alone needs no test (tests, fixtures, docs). requiredReads and testsFor+ * read it. */+ reviews: z.object({+ defaultReads: reads,+ rows: distinct(z.object({ area: line(80), reads, paths: globs }).strict(), row => row.area, 'area'),+ test: distinct(z.object({ where: line(200), paths: globs }).strict(), row => row.where, 'place'),+ untested: globs,+ }).strict(),+ /** The batch merge: on or off, and how often it runs. */+ mergeTrain: z.object({ enabled: z.boolean(), everyMinutes: minutes }).strict(),+ /** Named limits, such as the agents one machine takes. */+ caps: distinct(z.object({ name: line(80), value: z.number().int().min(0).max(1_000_000) }).strict(), cap => cap.name, 'cap'),+ /** Named places in the repository, such as where plans go. */+ paths: distinct(z.object({ name: line(80), path: line(400) }).strict(), entry => entry.name, 'path name'),+ /** The crew roster: each role and who fills it. */+ crew: distinct(z.object({ role: line(40), names: z.array(line(80)).max(20) }).strict(), entry => entry.role, 'role'),+ /** Lanes of work and the paths each owns. */+ lanes: distinct(z.object({ name: line(80), owns: z.array(line(400)).max(MAX_LIST) }).strict(), lane => lane.name, 'lane'),+}).strict().refine(rules => Buffer.byteLength(JSON.stringify(rules)) <= MAX_RULES_BYTES,+ `Project rules are at most ${MAX_RULES_BYTES / 1024} KB.`)+ // 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+ return !pause || (pause.start >= rules.releaseWindow.start && pause.end <= rules.releaseWindow.end)+ }, 'The backend pause falls inside the release window.')++export type ProjectRules = z.infer<typeof projectRulesSchema>++/** [value] frozen all the way down: the seed is shared, so no reader may change it. */+function deepFreeze<T>(value: T): T {+ if (typeof value === 'object' && value !== null) for (const inner of Object.values(value)) deepFreeze(inner)+ return Object.freeze(value)+}++/** Today's numbers (task #3393; project instructions, 2026-11-05): what a project reads until its first save. */+export const SEED_RULES: ProjectRules = deepFreeze({+ releaseWindow: { start: '09:00', end: '18:00', timeZone: 'Asia/Ho_Chi_Minh' },+ releasePace: { backendEveryMinutes: 120, appsAfterVisibleBatch: true, backendPause: { start: '09:00', end: '10:00' } },+ // The review table the review steps plan by (#3401, reviewTable.ts at c935c0665): two security reviews for these areas+ // (project instructions, Ken 2026-10-29), a test where the change runs (Workflow 2).+ reviews: {+ defaultReads: 1,+ rows: [+ { area: 'Sign-in', reads: 2, paths: ['**/*auth*', '**/*login*', '**/*logout*', '**/*signin*', '**/*sign_in*', '**/middlewares/**'] },+ { area: 'Tokens', reads: 2, paths: ['**/*token*', '**/*credential*', '**/*secret*', '**/*keychain*', 'backend/src/github/**'] },+ { area: 'Encryption', reads: 2, paths: ['**/*crypto*', '**/*encrypt*', '**/e2ee/**', '**/*seal*', '**/*pake*'] },+ { area: 'Access', reads: 2, paths: ['**/*access*', '**/*permission*', '**/*authority*', '**/*trust*', '**/teamWritten*'] },+ { area: 'Buddy guard', reads: 2, paths: ['**/*buddyguard*', '**/*buddy_guard*'] },+ { area: 'Device links', reads: 2, paths: ['**/*devicelink*', '**/*device_link*', '**/*deviceauth*', '**/*pairing*'] },+ { area: 'Deletion', reads: 2, paths: ['**/*delet*', '**/*purge*', '**/*cleanup*', '**/*tombstone*', '**/*wipe*'] },+ ],+ test: [+ { where: 'Desktop on a Mac', paths: ['desktop/**'] },+ { where: 'The CLI on a Mac and on a Linux machine', paths: ['cli/**', 'pty/**', 'term/**', 'tui/**', 'daemons/**'] },+ { where: 'The phone app in a simulator', paths: ['mobile/**'] },+ { where: 'The web in a browser', paths: ['website/**'] },+ { where: 'Install and update on a Mac', paths: ['installer/**'] },+ { where: 'Firmware on the device plugged into a machine', paths: ['devices/**', 'serial/**'] },+ ],+ untested: ['**/*.test.*', '**/*.spec.*', '**/*_test.*', '**/test/**', '**/tests/**', '**/integration/**', '**/__fixtures__/**',+ '**/*.md', 'docs/**'],+ },+ // Opt-in per project (River, #3402): a project turns it on with a rules save.+ mergeTrain: { enabled: false, everyMinutes: 10 },+ caps: [],+ paths: [],+ crew: [],+ lanes: [],+})++/** One change a save made: a leaf of an object section, or a whole list. */+export interface RulesChange { path: string; before: unknown; after: unknown }++const isObject = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)+/** JSON with keys in order, so two equal records compare equal whatever order their keys came in. */+const canonical = (value: unknown): string => isObject(value)+ ? `{${Object.keys(value).sort().map(k => `${JSON.stringify(k)}:${canonical(value[k])}`).join(',')}}`+ : Array.isArray(value) ? `[${value.map(canonical).join(',')}]` : JSON.stringify(value)++export const rulesEqual = (a: ProjectRules, b: ProjectRules): boolean => canonical(a) === canonical(b)++/** What changed from [before] to [after], in the schema's key order: each changed leaf of an object by its dotted path, and+ * a changed list whole (its rows have no identity to diff by). Empty for equal records. */+export function rulesDiff(before: ProjectRules, after: ProjectRules): RulesChange[] {+ const changes: RulesChange[] = []+ const walk = (path: string, a: unknown, b: unknown) => {+ if (isObject(a) && isObject(b)) {+ for (const key of [...new Set([...Object.keys(a), ...Object.keys(b)])]) walk(path ? `${path}.${key}` : key, a[key], b[key])+ } else if (canonical(a) !== canonical(b)) changes.push({ path, before: a, after: b })+ }+ walk('', before, after)+ return changes+}++/** What a save hands the store: the new revision, its diff from the one before, and who wrote it for whom. `writtenBy` is a+ * person or the project's PM; `askedBy` the person whose words it carries; `askedIn` the chat message the PM passed on (null+ * when a person wrote it). Never the machine owner's login. */+export interface RulesWrite {+ projectId: string+ revision: number+ rules: ProjectRules+ diff: RulesChange[]+ summary: string+ writtenBy: { kind: 'person' | 'agent'; id: string }+ askedBy: string+ askedIn: { conversationId: string; messageId: string } | null+ at: number+}++type GlobToken = { kind: 'char'; c: string } | { kind: 'one' } | { kind: 'name' } | { kind: 'any' } | { kind: 'dirs' }+const tokenCache = new Map<string, GlobToken[]>()+/** [glob] as tokens: `**` then a slash, any folders or none (`dirs`); `**` anything (`any`); `*` within one name (`name`); `?` one+ * character of a name (`one`); anything else itself, lower-cased. */+function globTokens(glob: string): GlobToken[] {+ let tokens = tokenCache.get(glob)+ if (tokens) return tokens+ tokens = []+ for (let i = 0; i < glob.length; i++) {+ const c = glob[i]!+ if (c === '*' && glob[i + 1] === '*') {+ if (glob[i + 2] === '/') { tokens.push({ kind: 'dirs' }); i += 2 } else { tokens.push({ kind: 'any' }); i += 1 }+ } else if (c === '*') tokens.push({ kind: 'name' })+ else if (c === '?') tokens.push({ kind: 'one' })+ else tokens.push({ kind: 'char', c: c.toLowerCase() })+ }+ // Bounded: a project has at most 50 rows of 50 patterns; the cache only saves tokenizing them again.+ if (tokenCache.size > 10_000) tokenCache.clear()+ tokenCache.set(glob, tokens)+ return tokens+}++/** Whether [path] matches [glob], ignoring case: `**` any folders (or none), `*` and `?` within one name; anything else is+ * itself. The review steps' rules (#3401 reviewTable.ts globMatch), so both read a row alike. It walks the pattern as a+ * set of positions, one step per character of the path: time grows with the path times the pattern and never backtracks,+ * whatever a project saves (security review of #3216: the regex it replaced took 19 s on `*a` ten times). */+export function globMatch(glob: string, path: string): boolean {+ const tokens = globTokens(glob), end = tokens.length+ // Every position reachable from [from] without reading a character: a wildcard may match nothing.+ const close = (from: Iterable<number>): Set<number> => {+ const seen = new Set<number>(), stack = [...from]+ while (stack.length) {+ const i = stack.pop()!+ if (seen.has(i)) continue+ seen.add(i)+ const t = tokens[i]+ if (t && (t.kind === 'name' || t.kind === 'any' || t.kind === 'dirs')) stack.push(i + 1)+ }+ return seen+ }+ let states = close([0])+ for (const raw of path) {+ const c = raw.toLowerCase(), next: number[] = []+ for (const i of states) {+ const t = tokens[i]+ if (!t) continue+ if (t.kind === 'char') { if (t.c === c) next.push(i + 1) }+ else if (t.kind === 'one') { if (c !== '/') next.push(i + 1) }+ else if (t.kind === 'name') { if (c !== '/') next.push(i) }+ else if (t.kind === 'any') next.push(i)+ // A double star and a slash: any characters, leaving after a slash.+ else { next.push(i); if (c === '/') next.push(i + 1) }+ }+ if (!next.length) return false+ states = close(next)+ }+ return states.has(end)+}++const matchesAny = (patterns: readonly string[], file: string) => patterns.some(g => globMatch(g, file))++/** The review rows a change to [files] touches; every row when its files could not be read (null): fail closed. */+export function touchedRows(rules: ProjectRules, files: readonly string[] | null): ProjectRules['reviews']['rows'] {+ return files === null ? [...rules.reviews.rows] : rules.reviews.rows.filter(row => files.some(file => matchesAny(row.paths, file)))+}++/** The independent reads a change to [files] needs: the most any touched row asks, at least the default. Files that could+ * not be read (null) need the most any row asks (the merge train and the review steps fail closed, #3401, #3402). */+export function requiredReads(rules: ProjectRules, files: readonly string[] | null): number {+ return Math.max(rules.reviews.defaultReads, ...touchedRows(rules, files).map(row => row.reads))+}++/** Where a change to [files] runs, for its test, in the table's order: none for tests, fixtures and docs alone, and none when+ * its files could not be read (where it runs is unknown). */+export function testsFor(rules: ProjectRules, files: readonly string[] | null): string[] {+ const running = (files ?? []).filter(file => !matchesAny(rules.reviews.untested, file))+ return rules.reviews.test.filter(row => running.some(file => matchesAny(row.paths, file))).map(row => row.where)+}diff --git a/backend/src/superTabs/policyStore.ts b/backend/src/superTabs/policyStore.tsnew file mode 100644index 000000000..a2fbd57b1--- /dev/null+++ b/backend/src/superTabs/policyStore.ts@@ -0,0 +1,60 @@+/**+ * A project's rules record in its own collection (policy.ts), one row per revision, written in the command's transaction.+ * Every filter is an equality or a range on the indexed fields (tabId, projectId, revision): never `in` (hotFilters.test.ts).+ */+import type { Prisma } from '@prisma/client'+import { stableId } from './model.js'+import { MAX_RULES_REVISIONS, SEED_RULES, type ProjectRules, type RulesChange, type RulesWrite } from './policy.js'++type Transaction = Prisma.TransactionClient++export const rulesRevisionId = (tabId: string, projectId: string, revision: number): string => stableId(tabId, projectId, 'rules', String(revision))++/** One kept revision as the history lists it. */+export interface RulesRevision {+ revision: number+ rules: ProjectRules+ diff: RulesChange[]+ summary: string+ writtenBy: { kind: string; id: string }+ askedBy: string+ askedIn: { conversationId: string; messageId: string } | null+ at: Date+}++/** The project's newest revision, or null when none is saved (the seed, revision 0). One indexed read. */+export async function readRules(tx: Transaction, tabId: string, projectId: string): Promise<{ revision: number; rules: ProjectRules } | null> {+ const row = await tx.superTabProjectRules.findFirst({ where: { tabId, projectId }, orderBy: { revision: 'desc' }, select: { revision: true, rules: true } })+ return row && { revision: row.revision, rules: row.rules as unknown as ProjectRules }+}++/** The record a project runs on now, for a server worker (the merge train, the release schedule): its newest revision, or+ * the seed at revision 0. Takes the client or a transaction. */+export async function currentRules(tx: Transaction, tabId: string, projectId: string): Promise<{ revision: number; rules: ProjectRules }> {+ return await readRules(tx, tabId, projectId) ?? { revision: 0, rules: SEED_RULES }+}++/** Every kept revision, newest first: at most MAX_RULES_REVISIONS rows of the same index. */+export async function readRulesHistory(tx: Transaction, tabId: string, projectId: string): Promise<RulesRevision[]> {+ const rows = await tx.superTabProjectRules.findMany({ where: { tabId, projectId }, orderBy: { revision: 'desc' }, take: MAX_RULES_REVISIONS })+ return rows.map(row => ({ revision: row.revision, rules: row.rules as unknown as ProjectRules, diff: row.diff as unknown as RulesChange[],+ summary: row.summary, writtenBy: { kind: row.writtenByKind, id: row.writtenBy }, askedBy: row.askedBy,+ askedIn: (row.askedIn ?? null) as RulesRevision['askedIn'], at: row.at }))+}++/** The new revision, created (never upserted: a second writer of the same revision meets the taken key and retries into+ * RULES_STALE), and no more than MAX_RULES_REVISIONS of them. */+export async function writeRules(tx: Transaction, tabId: string, write: RulesWrite): Promise<void> {+ const { projectId, revision } = write+ await tx.superTabProjectRules.create({ data: { id: rulesRevisionId(tabId, projectId, revision), tabId, projectId, revision,+ rules: write.rules as unknown as Prisma.InputJsonValue, diff: write.diff as unknown as Prisma.InputJsonValue, summary: write.summary,+ writtenByKind: write.writtenBy.kind, writtenBy: write.writtenBy.id, askedBy: write.askedBy,+ askedIn: write.askedIn === null ? undefined : write.askedIn as unknown as Prisma.InputJsonValue, at: new Date(write.at) } })+ // Growth: the 51st revision deletes the oldest.+ await tx.superTabProjectRules.deleteMany({ where: { tabId, projectId, revision: { lte: revision - MAX_RULES_REVISIONS } } })+}++/** Everything a deleted project kept of its rules. */+export async function deleteRules(tx: Transaction, tabId: string, projectId: string): Promise<void> {+ await tx.superTabProjectRules.deleteMany({ where: { tabId, projectId } })+}diff --git a/backend/src/superTabs/projects.test.ts b/backend/src/superTabs/projects.test.tsindex a733209a1..35e646325 100644--- a/backend/src/superTabs/projects.test.ts+++ b/backend/src/superTabs/projects.test.ts@@ -1,7 +1,7 @@import { createHash } from 'node:crypto'import { describe, expect, it } from 'vitest'import { applyCommand, commandSchema, type Command, type CommandContext } from './commands.js'-import { activeWork, agentOnly, awaitingWorkers, createSuperTab, fail, SuperTabError, visibleState, workerIndex, type Actor, type Agent, type Conversation, type MessageDraft, type SuperTabState, type WorkStatus } from './model.js'+import { occupiesAgent, agentOnly, awaitingWorkers, createSuperTab, fail, SuperTabError, visibleState, workerIndex, type Actor, type Agent, type Conversation, type MessageDraft, type SuperTabState, type WorkStatus } from './model.js'import { canReadAgent, canWatchAgent, confidentialSession, groupProject, ledProject, markConfidential, projectOf, projectsOf, readConversation, requireSingleRegistration, sessionKey, skillModeOf, skillSetOf, watchersLost, workRequesterId, requestedByLine, STUCK_START_MS, type OtherRegistrations, type SwarmProject } from './projects.js'import { mayDrive } from './terminal.js'@@ -713,13 +713,14 @@ function legacyRequireSingleRegistration(before: SuperTabState, after: SuperTabS}}}+/** The reference scan, with today's busy rule: a task its agent handed over leaves it free (model.ts occupiesAgent, #3399). */function legacyAwaitingWorkers(state: SuperTabState, projectId: string): Agent[] {return state.agents.filter(a => {if (state.conversations.some(c => c.leadId === a.id)- || state.conversations.some(c => activeWork(c) && c.assignment?.agentId === a.id)) return false+ || state.conversations.some(c => occupiesAgent(c) && c.assignment?.agentId === a.id)) return falseconst groups = state.conversations.filter(c => c.assignment?.agentId === a.id && !c.assignment.lost)return (a.projectId ?? groups.map(c => groupProject(state, c).id)[0] ?? 'lead') === projectId &&- (a.workDecision === 'awaiting' || (!a.workDecision && groups.some(c => !activeWork(c))))+ (a.workDecision === 'awaiting' || (!a.workDecision && groups.some(c => !occupiesAgent(c))))})}diff --git a/backend/src/superTabs/purge.ts b/backend/src/superTabs/purge.tsindex 450a2d8f5..ee3fc0612 100644--- a/backend/src/superTabs/purge.ts+++ b/backend/src/superTabs/purge.ts@@ -20,7 +20,7 @@ export const PURGE_RETRY_MS = 6 * 60 * 60 * 1000export const PURGED_BY_TAB_ID = ['superTabMessage', 'superTabMention', 'superTabReaction', 'superTabActivity', 'superTabChatSetting', 'superTabReminder', 'superTabReadMark','superTabThreadMark', 'superTabThread', 'superTabOpenProposal', 'superTabDecision', 'superTabOperation', 'superTabNativeContext', 'superTabDelivery', 'superTabReceipt','superTabRun', 'superTabAttempt', 'superTabRouteDecision', 'superTabModelEvidence', 'superTabModelRecent', 'superTabStopReceipt',- 'superTabRoleText', 'superTabInstructions', 'superTabInstructionsRevision', 'superTabPmNote', 'superTabConfiguration', 'superTabTerminalRequest',+ 'superTabRoleText', 'superTabInstructions', 'superTabInstructionsRevision', 'superTabProjectRules', 'superTabPmNote', 'superTabConfiguration', 'superTabTerminalRequest','gitHubRepositoryApproval', 'gitHubApprovalRefusal', 'swarmHead', 'swarmMember', 'swarmGroup', 'swarmAgent', 'swarmMachine', 'swarmStart','swarmProgress'] as constdiff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex dac5da35b..cddc57f78 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -52,6 +52,8 @@ import { isBuddy, isBuddyChat, isBuddyReader, refuseBuddyRouting, routingRow } fimport { lostReasonWithoutMachine } from './lostReason.js'import { LEAD_NAME } from './leadStart.js'import { deleteInstructions, instructionsId, readNotes, revisionId, writeInstructions, writeNotes } from './instructionsStore.js'+import { deleteRules, readRules, readRulesHistory, writeRules } from './policyStore.js'+import { SEED_RULES } 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'@@ -61,7 +63,7 @@ import { digestDue, digestMessageId, digestOf, digestRequest, digestSince } fromimport { moveChatMark } from './read/threadMarkSeeds.js'import { closedAgents, nextRemovalAt, removeClosedAgents, reopened, restoreRefusal, restoreSessions } from './closedAgents.js'import { sessionRows } from './memberRows.js'-import { failRefusedStarts, judgedMachines, loseTasks, nextLossAt, sweepForLead, sweepLiveness, SWEEP_EVERY_MS, unpurgedNotice } from './liveness.js'+import { failRefusedStarts, judgedMachines, loseTasks, nextLossAt, recordTaskState, sweepForLead, sweepLiveness, SWEEP_EVERY_MS, unpurgedNotice } from './liveness.js'import { endedReply, taskLineChats } from './taskLine.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'@@ -74,6 +76,7 @@ import { commitParts, indexesOf, machineContentChanged, numberMessages, type Touimport { loadDeliveryParts, ms } from './parts/light.js'import { endSteps, ownerOf, stepEndedRows, stepsOf } from './steps.js'import { pullRequestEvents, type PullRequestWatch } from './pullRequestEvents.js'+import { reopenOnEvents } from './handed.js'import { guardedWrite, partId } from './parts/write.js'import { retryable } from './retry.js'import { touchesFor } from './parts/touches.js'@@ -84,7 +87,7 @@ import { revokeNativeContexts, SuperTabNativeStore } from './native.js'import { activeMember, addMember, hasWorkspaceAccess, latestRemovalAt, listWorkspaces, memberId, removedFromWorkspace, WORKSPACE_ACCESS_REVOKED, workspaceForNewSwarm, requireWorkspaceAccess, requireWorkspaceRole, SwarmWorkspaces } from './workspaceStore.js'import { WORKSPACE_LABEL, workspaceCan, type WorkspaceRole } from './workspaces.js'import { STATUS_LABELS,- activeWork, actorKey, agent, agentOnly, appendPullRequestUrls, author, conversation, createSuperTab, fail, person, stableId, visibleState, finishWorker,+ activeWork, handed, occupiesAgent, actorKey, agent, agentOnly, appendPullRequestUrls, author, conversation, createSuperTab, fail, person, stableId, visibleState, finishWorker,SuperTabError, isLeads, knownKind, parkLaterConversations, type Actor, type Agent, type Assignment, type Author, type CommandEffects, type Conversation, type MessageDraft, type Person, type SuperTabState,projectPullRequestUrl, pullRequestLinks,} from './model.js'@@ -93,7 +96,7 @@ import { stuck } from './deliverySettle.js'import { agentPost, digestIsDue, digestMessage, digestText, doneRow, endedAlert, GATHERED_LIMIT_MS, gatheredMessage, NOTICE_DIGEST_MAX, noticeLine } from './noticeDigest.js'import { PM_SCHEDULE_TEXT, recordTidy, recordWake, scheduleRequest, tidyRequest } from './pmSchedule.js'import { agentDisplayName } from './agentNames.js'-import { endedHolds, HOLDING, startedHolds, type WorkHold } from '../github/holds.js'+import { endedHolds, startedHolds, tokenTask, type WorkHold } from '../github/holds.js'import { accrueLent, addLent, lentAgents, lentProjects } from './leaderboard/lent.js'import { mayDrive, TERMINAL_ANSWER_MS, TERMINAL_EXPIRY_MS, TERMINAL_PICKUP_MS, TERMINAL_RECHECK_MS, type TerminalEffect } from './terminal.js'import { costRows, failedStarts, summarizeCosts } from './costs/read.js'@@ -1763,9 +1766,11 @@ export class SuperTabStore {if (command.type === 'instructions.save' && command.approvals?.length) context.approvals = await readApprovals(tx, tabId, command.approvals)}if (command.type === 'note.add' || command.type === 'note.remove') context.notes = await readNotes(tx, tabId, command.projectId)+ // A stale rules save is refused with the newest revision, to merge (policy.ts); null is the seed.+ if (command.type === 'rules.set') context.projectRules = await readRules(tx, tabId, command.projectId)if ((command.type === 'rule.set' || command.type === 'rule.remove' || command.type === 'project.skills' || command.type === 'tab.tidy'|| command.type === 'machine.engineResume' || command.type === 'machine.projects' || command.type === 'machine.ownAccountWork'- || command.type === 'machine.access') && command.askedIn) {+ || command.type === 'machine.access' || command.type === 'rules.set') && command.askedIn) {const asked = await tx.superTabMessage.findFirst({ where: { id: command.askedIn.messageId, tabId, conversationId: command.askedIn.conversationId } })if (asked) context.askedIn = { author: asked.author as unknown as Author, source: !!asked.source, createdAt: asked.createdAt.getTime() }}@@ -1994,10 +1999,15 @@ export class SuperTabStore {const running = await tx.superTabRun.findUnique({ where: { id: assigned.agentId } })// A record of this Swarm's for work that has ended here is stale (endRuns): it goes, by its own assignment, and the agent// is free. A record of another Swarm's, or a stopping agent's, still means busy.- if (running && (running.tabId !== tabId || !(await this.staleRuns(tx, tabId, original)).includes(running.assignmentId))) {+ // A task the agent handed over here (model.ts handed, task #3399) gives its record to the new work: only the record+ // moves, since that task is still open and a Reviewer's findings queued for the agent there must still arrive.+ const handedHere = !!running && running.tabId === tabId+ && original.conversations.some(c => handed(c) && c.assignment!.id === running.assignmentId && c.assignment!.agentId === assigned.agentId)+ if (running && !handedHere && (running.tabId !== tabId || !(await this.staleRuns(tx, tabId, original)).includes(running.assignmentId))) {fail('AGENT_BUSY', 'This agent already owns active work in a Super Tab.')}- if (running) await this.releaseRuns(tx, tabId, [running.assignmentId])+ if (handedHere) await tx.superTabRun.deleteMany({ where: { id: assigned.agentId, tabId, assignmentId: running!.assignmentId } })+ else if (running) await this.releaseRuns(tx, tabId, [running.assignmentId])await tx.superTabRun.create({ data: { id: assigned.agentId, tabId, assignmentId: assigned.id,machineId: assigned.execution.machineId, harnessId: assigned.execution.harnessId } })}@@ -2049,7 +2059,9 @@ export class SuperTabStore {if (command.type === 'project.delete') await tx.superTabRoleText.deleteMany({ where: { tabId, projectId: command.projectId } })if (effects.instructions) await writeInstructions(tx, tabId, effects.instructions)if (effects.notes) await writeNotes(tx, tabId, effects.notes, context.now)+ if (effects.projectRules) await writeRules(tx, tabId, effects.projectRules)if (command.type === 'project.delete') await deleteInstructions(tx, tabId, command.projectId)+ if (command.type === 'project.delete') await deleteRules(tx, tabId, command.projectId)if (effects.terminal) await this.writeTerminal(tx, tabId, effects.terminal, context.now)// A deleted Swarm's observer sockets, on any instance, check again and close (deletion.ts).if (this.hooks.accessChanged && (watchersLost.length || command.type === 'swarm.delete')) {@@ -2203,8 +2215,7 @@ export class SuperTabStore {author(state, actor, true)const target = agent(state, asAgentId)if (target.machineId !== machineId) fail('FORBIDDEN', 'Only the machine running this agent can ask for its GitHub token.', 403)- const group = state.conversations.find(c => !isLeads(c) && c.assignment?.agentId === target.id && HOLDING.has(c.assignment.status)- && c.assignment.execution.machineId === target.machineId && c.assignment.execution.machineOwnerId === target.machineOwnerId)+ const group = tokenTask(state, target)?? fail('NO_ASSIGNMENT', 'This agent has no task in progress. A GitHub token is only for an agent working on a task.')const project = groupProject(state, group)const owner = await ownerAccount(tx.user, project)@@ -2809,6 +2820,16 @@ export class SuperTabStore {})}+ /** A project's rules record and its kept revisions, newest first (policy.ts): the seed at revision 0 until a first save.+ * Anyone who reads the project reads them; a Buddy reads nothing, since the history names who asked for what. */+ async projectRules(user: AuthUser, tabId: string, projectId: string, asAgentId?: string) {+ return this.instructionHistory(user, tabId, projectId, asAgentId, async tx => {+ const history = await readRulesHistory(tx, tabId, projectId)+ const newest = history[0]+ return { projectId, revision: newest?.revision ?? 0, rules: newest?.rules ?? SEED_RULES, seeded: !newest, history }+ })+ }+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)@@ -2970,6 +2991,25 @@ export class SuperTabStore {if (!changed || !activeWork(changed) || changed.assignment!.id !== group.assignment!.id) ended.add(group.assignment!.id)}await this.releaseRuns(tx, tabId, [...ended])+ // An agent whose work in hand ended, or whose handed task came back to it, may still have a task open here: a task it+ // handed over (model.ts handed, #3399) gave its record to the next one. The record goes back to it, so no other Swarm+ // assigns the session while a No or red CI may bring that task back (security review of #3221).+ const agentOf = new Map([...before.conversations, ...after.conversations].flatMap(c => c.assignment ? [[c.assignment.id, c.assignment.agentId] as const] : []))+ const reopened = after.conversations.filter(c => c.assignment?.status === 'working' && earlier.get(c.id)?.assignment?.id === c.assignment.id+ && earlier.get(c.id)?.assignment?.status === 'review').map(c => c.assignment!.agentId)+ await this.restoreRuns(tx, tabId, after, [...new Set([...[...ended].flatMap(id => agentOf.get(id) ?? []), ...reopened])])+ }++ /** Each of [agentIds] with no run record and a task still open in this Swarm gets one for that task, the one in its hands+ * first (endRuns). A record already there, this Swarm's or another's, is left as it is. */+ private async restoreRuns(tx: Transaction, tabId: string, state: SuperTabState, agentIds: string[]) {+ for (const agentId of agentIds) {+ const open = state.conversations.filter(c => activeWork(c) && c.assignment!.agentId === agentId && c.assignment!.status !== 'reconciling')+ const task = open.find(occupiesAgent) ?? open[0]+ if (!task || await tx.superTabRun.findUnique({ where: { id: agentId } })) continue+ const work = task.assignment!+ await tx.superTabRun.create({ data: { id: agentId, tabId, assignmentId: work.id, machineId: work.execution.machineId, harnessId: work.execution.harnessId } })+ }}/** For these ended assignments of this Swarm, by their exact ids: their run records go, and their deliveries still queued,@@ -4661,9 +4701,16 @@ export class SuperTabStore {if (!group || group.archived || group.reviewOf || !group.pullRequestUrls?.includes(watch.url)|| ['done', 'cancelled'].includes(group.assignment?.status ?? '')) return 0const now = this.now(), seen = group.pullRequestEvents?.[watch.url] ?? []- const { events, keys } = pullRequestEvents(watch, seen, botLogin, now)+ const { events: seenEvents, keys } = pullRequestEvents(watch, seen, botLogin, now)if (keys.length === seen.length && keys.every((key, i) => key === seen[i])) return 0group.pullRequestEvents = { ...group.pullRequestEvents, [watch.url]: keys }+ // CI failing or a conflict brings a handed task back to its Engineer, in the message that tells it (handed.ts, #3399).+ const events = reopenOnEvents(group, seenEvents, now)+ if (events !== seenEvents) {+ recordTaskState(state, group, now)+ // Back in its hands: the session's cross-Swarm fence covers it again if nothing does (endRuns).+ await this.restoreRuns(tx, tabId, state, [group.assignment!.agentId])+ }const ownerId = ownerOf(state, group), owner = ownerId ? state.agents.find(a => a.id === ownerId) : undefined// Written as its project's Lead, as the Swarm's own lines are (tidy.ts archiveLine); as the Engineer itself without one.const leadId = state.conversations.find(c => c.id === groupProject(state, group).leadConversationId)?.leadIddiff --git a/backend/src/superTabs/terminal.ts b/backend/src/superTabs/terminal.tsindex 759249cdd..0004f9825 100644--- a/backend/src/superTabs/terminal.ts+++ b/backend/src/superTabs/terminal.ts@@ -1,7 +1,7 @@import { isBuddy, isBuddyChat } from './buddies.js'import type { PrismaClient } from '@prisma/client'import { ensureIndex } from '../lib/db/indexes.js'-import { activeWork, actorKey, agent, author, conversation, fail, isLeads, stableId, SuperTabError, type Actor, type Agent, type Author, type Conversation, type MessageDraft,+import { activeWork, occupiesAgent, actorKey, agent, author, conversation, fail, isLeads, stableId, SuperTabError, type Actor, type Agent, type Author, type Conversation, type MessageDraft,type SuperTabState } from './model.js'import { downSince, productManagerOn } from './machines.js'import { agentProjectId, isConfidential, ledProject, onTeamAccount, ownSession, projectAgent, projectOf, readAgent, teamSessionAccess } from './projects.js'@@ -97,7 +97,9 @@ export function currentGroup(state: SuperTabState, target: Agent): Conversation// A Buddy's rows are its person's alone, in its own chat: it has no PM, and a Swarm-wide one no project (Dee, 10-31).const own = isBuddy(target) ? state.conversations.find(c => isBuddyChat(c) && c.agentIds.includes(target.id)) : undefinedif (own) return own- return state.conversations.find(c => activeWork(c) && c.assignment!.agentId === target.id)+ // The task in its hands first: an Engineer that handed a task over and took the next one is at work on that one (#3399).+ return state.conversations.find(c => occupiesAgent(c) && c.assignment!.agentId === target.id)+ ?? state.conversations.find(c => activeWork(c) && c.assignment!.agentId === target.id)?? state.conversations.findLast(c => !c.archived && !isLeads(c) && !c.audience && c.agentIds.includes(target.id) && c.leadId !== target.id)?? conversation(state, projectOf(state, agentProjectId(state, target)).leadConversationId)}diff --git a/backend/src/superTabs/tidy.test.ts b/backend/src/superTabs/tidy.test.tsindex 8c0e1d38b..51fa220c0 100644--- a/backend/src/superTabs/tidy.test.ts+++ b/backend/src/superTabs/tidy.test.ts@@ -74,6 +74,14 @@ describe('idle agents', () => {expect(idleNotices(swarm({ groups: [linked] }), 'lead', at, new Set())).toEqual([])})+ it('tells of an Engineer whose own task is handed over for review, which leaves it free (#3399)', () => {+ const handed = group({ assignment: done({ status: 'review', result: 'Ready for review: PR #7 at abc1234' }) })+ expect(idleNotices(swarm({ groups: [handed] }), 'lead', at, new Set())).toEqual([expect.objectContaining({ text: 'Rowan has had no open task for 15 minutes.' })])+ // A step's own Ready is its verdict, no hand-over: its Reviewer is still at work on it.+ const step = group({ reviewOf: 'g0', assignment: done({ status: 'review' }) })+ expect(idleNotices(swarm({ groups: [step] }), 'lead', at, new Set())).toEqual([])+ })+it('waits until a full 15 minutes have passed since the group of its own task last spoke', () => {const state = swarm({ groups: [group({ lastActivityAt: iso(START + 5 * MINUTE) })] })expect(idleNotices(state, 'lead', at, new Set())).toEqual([])diff --git a/backend/src/superTabs/tidy.ts b/backend/src/superTabs/tidy.tsindex 28e21f895..becb402dc 100644--- a/backend/src/superTabs/tidy.ts+++ b/backend/src/superTabs/tidy.ts@@ -4,7 +4,7 @@ import { isCrew } from './crew.js'import { expiredModelRequests, unservedBuddyModels } from './buddyModel.js'import { agentDisplayName } from './agentNames.js'import { githubRepository, type GitHubRepository } from '../github/repository.js'-import { activeWork, appendPullRequestUrls, stableId, type Actor, type Agent, type Conversation, type MessageDraft, type SuperTabState } from './model.js'+import { activeWork, occupiesAgent, appendPullRequestUrls, stableId, type Actor, type Agent, type Conversation, type MessageDraft, type SuperTabState } from './model.js'import { agentProjectId, canReadGroup, groupProject, ledProject, projectsOf } from './projects.js'import { toLead } from './terminal.js'@@ -64,7 +64,9 @@ export function idleNotices(state: SuperTabState, projectId: string, now: numberif (target.id === coordinator.id || isBuddy(target) || isCrew(target) || target.workDecision === 'stop' || target.workDecision === 'keep' || busy.has(target.id)|| agentProjectId(state, target) !== projectId || waitingToResume(state, target)) continueconst groups = groupsOf(state, target)- if (groups.some(activeWork)) continue+ // Its own work in its hands, or a member of a task whose work is going (a Reviewer or a Tester linked to it). Its own task+ // handed over (task #3399) leaves it free, so the coordinator hears it is idle.+ if (groups.some(c => c.assignment?.agentId === target.id ? occupiesAgent(c) : activeWork(c))) continue// A Reviewer or Tester, by what it worked on: the instructions keep it while the work it checked is open (Ken,// 2026-11-02: "Tester has had no open task" twice in 8 minutes, nothing for the PM to do), and no longer.if (checksOpenWork(state, groups, target.id)) continuediff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.tsindex 433383d52..0b03060d6 100644--- a/backend/vitest.super-tabs.config.ts+++ b/backend/vitest.super-tabs.config.ts@@ -8,5 +8,5 @@ export default defineConfig({ test: { include: ['integration/superTabs.test.ts','integration/superTabBuddyProbes.test.ts', 'integration/superTabBuddySessions.test.ts', 'integration/superTabSwarmBuddy.test.ts', 'integration/superTabPersonalLead.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/harnessSharesIndexPlan.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts','integration/superTabEvidence.test.ts', 'integration/superTabAttemptModels.test.ts', 'integration/superTabNamedReads.test.ts', 'integration/swarmSweepPlans.test.ts', 'integration/overdueDecisions.test.ts', 'integration/workerIndexPlans.test.ts', 'integration/superTabReflection.test.ts','integration/superTabMessagePages.test.ts', 'integration/superTabDeliveryCompaction.test.ts', 'integration/superTabNoticeDigest.test.ts', 'integration/superTabPmSchedule.test.ts', 'integration/superTabDigestHour.test.ts', 'integration/superTabCommandLoads.test.ts', 'integration/superTabThreads.test.ts', 'integration/superTabMachineRemovals.test.ts',- 'integration/superTabInstructions.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabComputerMoves.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts', 'integration/superTabPullRequestEvents.test.ts', 'integration/superTabProposals.test.ts', 'integration/superTabRequestReads.test.ts', 'integration/superTabVoiceMessages.test.ts', 'integration/superTabThumbnails.test.ts', 'integration/superTabProjectChatWorkers.test.ts', 'integration/prismaQueryTiming.test.ts', 'integration/secondaryReads.test.ts', 'integration/pushDevices.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/noDefaultDigest.test-support.ts', 'integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],+ 'integration/superTabInstructions.test.ts', 'integration/superTabProjectRules.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabComputerMoves.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts', 'integration/superTabPullRequestEvents.test.ts', 'integration/superTabProposals.test.ts', 'integration/superTabRequestReads.test.ts', 'integration/superTabVoiceMessages.test.ts', 'integration/superTabThumbnails.test.ts', 'integration/superTabProjectChatWorkers.test.ts', 'integration/prismaQueryTiming.test.ts', 'integration/secondaryReads.test.ts', 'integration/pushDevices.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/noDefaultDigest.test-support.ts', 'integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })diff --git a/cli/scripts/release-cli.sh b/cli/scripts/release-cli.shindex 68ab8bcb1..e5a46753e 100755--- a/cli/scripts/release-cli.sh+++ b/cli/scripts/release-cli.sh@@ -12,6 +12,7 @@# bash cli/scripts/release-cli.sh --notes-file f.md # hand-written release notes instead of the# # generated commit list# bash cli/scripts/release-cli.sh --allow-older # a rollback: older code under a higher version+# bash cli/scripts/release-cli.sh --urgent "P0: why" # a P0 outside the 09:00-18:00 VN release window## THE NEXT VERSION COMES FROM TWO SOURCES, AND BOTH MATTER — same reasoning as# autonomous-harness-desktop/scripts/release-desktop.sh. Git tags alone are not enough:@@ -45,23 +46,33 @@ ALLOW_NO_MANIFEST=0ALLOW_OLDER=0NEW_VER=""NOTES_FILE=""+URGENT_SET=0+URGENT=""want_notes_file=0+want_urgent=0for arg in "$@"; doif [ "$want_notes_file" -eq 1 ]; then NOTES_FILE="$arg"; want_notes_file=0; continue; fi+ if [ "$want_urgent" -eq 1 ]; then URGENT="$arg"; want_urgent=0; continue; ficase "$arg" in+ --urgent) URGENT_SET=1; want_urgent=1 ;;--dry-run) DRY_RUN=1 ;;--allow-no-manifest) ALLOW_NO_MANIFEST=1 ;;--allow-older) ALLOW_OLDER=1 ;;--notes-file) want_notes_file=1 ;;--notes-file=*) NOTES_FILE="${arg#*=}" ;;- -h|--help) sed -n '2,24p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; exit 0 ;;+ -h|--help) sed -n '2,25p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; exit 0 ;;-*) echo "ERROR unknown flag: $arg" >&2; exit 1 ;;*) NEW_VER="$arg" ;;esacdone[ "$want_notes_file" -eq 0 ] || { echo "ERROR --notes-file needs a path" >&2; exit 1; }+# --- the release window: refused with RELEASE_WINDOW outside 09:00-18:00 Asia/Ho_Chi_Minh, naming the next allowed+# time (scripts/release-window.py). A P0 passes --urgent "<reason>"; the reason goes on the tag.+source "$ROOT/scripts/release-window.sh"+release_window_guard cli+# Same rule as next_adapter_version() in cli/scripts/upload-cli.sh:28-42, which is where this# convention is defined. Note the rollover: .99 goes to the next MINOR at .1, not .0.next_patch_version() {@@ -249,6 +260,7 @@ if [ "$DRY_RUN" -eq 1 ]; thenfi# --- tag and push ---+[ -z "$URGENT_TAG_LINE" ] || printf '\n%s\n' "$URGENT_TAG_LINE" >> "$NOTES"git tag -a "$TAG" --cleanup=verbatim -F "$NOTES"git push origin "$TAG"diff --git a/cli/src/core/agents/retarget.spec.ts b/cli/src/core/agents/retarget.spec.tsindex 455992563..4240ca14d 100644--- a/cli/src/core/agents/retarget.spec.ts+++ b/cli/src/core/agents/retarget.spec.ts@@ -595,6 +595,22 @@ describe('retargeting an agent', () => {expect(vi.mocked(validateLaunchOverrides).mock.lastCall?.[2]).toMatchObject({ subscriptionModel: null })})+ // Task #3449: the move home is built from its own source, so it dropped the launch model, and a PM came back from a grid+ // without its xhigh (lib/launchOverrides.ts ranks the launch model above the remembered one).+ it('back home: the launch model rides with the remembered model; a move onto a grid carries none', async () => {+ const launchModel = { model: 'opus', effort: 'xhigh' }+ const home = setup(agent({ grid: { baseUrl: 'x' }, subscriptionModel: 'opus', launchModel } as Partial<RegisteredSession>), {+ relaunchOverrides: vi.fn(async () => ({ ok: true, overrides: {} })) as never,+ })+ expect(await home.retarget({ agentId: 'a1', grid: null })).toEqual({ ok: true })+ expect(vi.mocked(validateLaunchOverrides).mock.lastCall?.[2]).toEqual({ gridLaunch: null, codexHome: undefined, subscriptionModel: 'opus', launchModel })+ expect(home.deps.relaunchOverrides).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ launchModel }), expect.any(Function), undefined)+ const away = setup(agent({ launchModel } as Partial<RegisteredSession>))+ await away.retarget({ agentId: 'a1', grid })+ expect(away.deps.relaunchOverrides).toHaveBeenCalledWith(expect.anything(), expect.not.objectContaining({ launchModel: expect.anything() }),+ expect.any(Function), undefined)+ })+it('on a ptyhost pane: swapped through that pane\'s own backend, the grid\'s names cleared by the respawn on the way home', async () => {const pty = { backend: 'ptyhost' as const, instance: 'p1', paneId: '%3' }const ptyBackend = { name: 'ptyhost', holdOpen: vi.fn(), respawn: vi.fn(), releaseHold: vi.fn(async () => {}) }diff --git a/cli/src/core/agents/retarget.ts b/cli/src/core/agents/retarget.tsindex c43d28bba..f89212bce 100644--- a/cli/src/core/agents/retarget.ts+++ b/cli/src/core/agents/retarget.ts@@ -172,7 +172,8 @@ export function createAgentRetargeter({const target: LaunchSource = {gridLaunch: grid,codexHome: session.codexHome,- ...(grid ? {} : { subscriptionModel: remembered }),+ // Home, the model it was launched with too: it outranks the remembered one (lib/launchOverrides.ts, task #3449).+ ...(grid ? {} : { subscriptionModel: remembered, ...(session.launchModel ? { launchModel: session.launchModel } : {}) }),}const inspected = await launchOverridesDeps.native?.(session.engine, session, { id: session.agentId, current })if (!current()) return changed()diff --git a/cli/src/lib/launchOverrides.spec.ts b/cli/src/lib/launchOverrides.spec.tsindex 65665c885..4db736e67 100644--- a/cli/src/lib/launchOverrides.spec.ts+++ b/cli/src/lib/launchOverrides.spec.ts@@ -663,12 +663,29 @@ describe('buildLaunchOverrides — the model the session was launched with', ()expect(result).toMatchObject({ ok: true, overrides: { extraArgs: ['--model', 'opus', '--effort', 'xhigh'] } })})- it('leaves it to a grid launch and to a model remembered off a grid, and to an engine with no launch flags', async () => {+ it('leaves it to a grid launch, and to an engine with no launch flags', async () => {const grid = await buildLaunchOverrides(deps().d, 'claude', { gridLaunch: GRID, launchModel: { model: 'opus', effort: 'xhigh' } }, 'a')expect(grid.ok && grid.overrides.extraArgs).not.toContain('--effort')- const home = await buildLaunchOverrides(deps().d, 'claude', { subscriptionModel: 'sonnet', launchModel: { model: 'opus', effort: 'xhigh' } }, 'a')- expect(home).toMatchObject({ ok: true, overrides: { env: { ANTHROPIC_MODEL: 'sonnet' }, extraArgs: [] } })const codex = await buildLaunchOverrides(deps().d, 'codex', { launchModel: { model: 'gpt-6', effort: 'high' } }, 'a')expect(codex).toMatchObject({ ok: true, overrides: { extraArgs: ['-c', 'model_provider="openai"'] } })+ const codexHome = await buildLaunchOverrides(deps().d, 'codex', { subscriptionModel: 'gpt-5-codex', launchModel: { model: 'gpt-6', effort: 'high' } }, 'a')+ expect(codexHome).toMatchObject({ ok: true, overrides: { extraArgs: ['-c', 'model_provider="openai"', '-m', 'gpt-5-codex'] } })+ })++ // Task #3449: the model remembered when the session left for a grid is a model alone, and it stays after the move home.+ // Ranked first, a PM back from a grid relaunched without its xhigh, then and on every relaunch after, and a later pick lost.+ it('outranks the model remembered off a grid, once back home and on every relaunch after', async () => {+ for (const subscriptionModel of ['opus', 'sonnet']) {+ const home = await buildLaunchOverrides(deps().d, 'claude', { subscriptionModel, launchModel: { model: 'opus', effort: 'xhigh' } }, 'a')+ expect(home).toMatchObject({ ok: true, overrides: { extraArgs: ['--model', 'opus', '--effort', 'xhigh'] } })+ expect(home.ok && home.overrides.env).not.toHaveProperty('ANTHROPIC_MODEL')+ }+ const picked = await buildLaunchOverrides(deps().d, 'claude', { subscriptionModel: 'opus', launchModel: { model: 'sonnet', effort: 'high' } }, 'a')+ expect(picked).toMatchObject({ ok: true, overrides: { extraArgs: ['--model', 'sonnet', '--effort', 'high'] } })+ })++ it('keeps the remembered model beside a launch effort that names no model', async () => {+ const result = await buildLaunchOverrides(deps().d, 'claude', { subscriptionModel: 'opus', launchModel: { model: null, effort: 'xhigh' } }, 'a')+ expect(result).toMatchObject({ ok: true, overrides: { env: { ANTHROPIC_MODEL: 'opus' }, extraArgs: ['--effort', 'xhigh'] } })})})diff --git a/cli/src/lib/launchOverrides.ts b/cli/src/lib/launchOverrides.tsindex 9002e4dce..b242e4c51 100644--- a/cli/src/lib/launchOverrides.ts+++ b/cli/src/lib/launchOverrides.ts@@ -361,9 +361,14 @@ async function prepareBaseLaunchOverrides(if (!source.gridLaunch) {const remembered = subscriptionModelLaunch(engine, source.subscriptionModel, (await deps.machine(engine)).opencodeMajor ?? null)// The flags it was launched with hold for that launch alone: reopened without them, a Product Manager launched on Opus at- // xhigh ran its engine's own default, the machine's last-used Claude Code model (task #3395, anh Dee 11-05).- const launched = !remembered && source.launchModel ? launchModelArgs(engine, source.launchModel) : []- const restored = remembered ?? (launched.length ? { env: {}, args: launched } : null)+ // xhigh ran its engine's own default, the machine's last-used Claude Code model (task #3395, anh Dee 11-05). They outrank+ // the model remembered when it left for a grid: that one is a model alone and stays after the move home, so ranked+ // first a PM back from a grid lost its xhigh on every relaunch, and a later pick lost too (task #3449). A launch model+ // that names no model keeps the remembered one beside its effort; an engine with no launch flags keeps the remembered one.+ const launched = source.launchModel ? launchModelArgs(engine, source.launchModel) : []+ const restored = !launched.length ? remembered+ : source.launchModel?.model || !remembered ? { env: {}, args: launched }+ : { ...remembered, args: [...remembered.args, ...launched] }// In the Harness Team account, an engine it has not signed in itself spends the owner's subscription through the// owner's relay, on every relaunch as on its first: Codex keeps the relay's provider per thread, so it is named again// here in place of its own login's (two `-c model_provider` would leave Codex to pick one).diff --git a/desktop/lib/super_tabs/backend_transport.dart b/desktop/lib/super_tabs/backend_transport.dartindex 40e91ffd5..889834777 100644--- a/desktop/lib/super_tabs/backend_transport.dart+++ b/desktop/lib/super_tabs/backend_transport.dart@@ -29,7 +29,9 @@ final _swarmRoute = RegExp('|threads/$_id/(?:read|follow)''|messages/$_id/attachments/$_id|messages/$_id/reminder)''|projects/$_id/(?:github|github/approve|github/repository'- '|instructions(?:/revisions(?:/[0-9]+)?)?)'+ '|instructions(?:/revisions(?:/[0-9]+)?)?'+ // The project's rules record, read in Project settings (#3393).+ '|rules)''|route-decisions/$_id|machines/$_id/removal(?:/v2)?)'r')(?:\?[A-Za-z0-9_=&%-]+)?$',);diff --git a/desktop/lib/super_tabs/project_rules.dart b/desktop/lib/super_tabs/project_rules.dartnew file mode 100644index 000000000..a21d0652f--- /dev/null+++ b/desktop/lib/super_tabs/project_rules.dart@@ -0,0 +1,378 @@+import 'dart:async';++import 'package:flutter/material.dart';++import '../core/relative_time.dart';+import '../shared/widgets/app_dialog.dart';+import '../shared/widgets/skeleton.dart';+import '../widgets/desktop_chrome.dart';+import 'controller.dart';+import 'detail_dialog.dart';+import 'dialog_scope.dart';+import 'instructions_model.dart';++const _gap = DesktopChrome.controlGap;+const _halfGap = _gap / 2;++DateTime _time(Object? value) =>+ DateTime.tryParse(value as String? ?? '') ??+ DateTime.fromMillisecondsSinceEpoch(0, isUtc: true);++/// One change a rules save made: a field by its dotted path, or a whole list.+typedef SuperTabRulesChange = ({String path, Object? before, Object? after});++/// One kept revision of a project's rules (backend superTabs/policyStore.ts).+class SuperTabRulesRevision {+ SuperTabRulesRevision.fromJson(Map<String, dynamic> row)+ : revision = (row['revision'] as num?)?.toInt() ?? 0,+ summary = row['summary'] as String? ?? '',+ diff = List.unmodifiable([+ for (final change in row['diff'] as List? ?? const [])+ if (change is Map<String, dynamic>)+ (+ path: change['path'] as String? ?? '',+ before: change['before'],+ after: change['after'],+ ),+ ]),+ writtenBy = switch (row['writtenBy']) {+ {'kind': final String kind, 'id': final String id} => (+ kind: kind,+ id: id,+ ),+ _ => (kind: 'person', id: ''),+ },+ askedBy = row['askedBy'] as String?,+ at = _time(row['at']);+ final int revision;+ final String summary;+ final List<SuperTabRulesChange> diff;++ /// `kind` is `person` or `agent` (the project's PM).+ final ({String kind, String id}) writtenBy;+ final String? askedBy;+ final DateTime at;+}++/// A project's rules record as the backend answers it (superTabs/policy.ts): the record, its revision (0 is the+/// built-in seed, never saved) and its kept revisions, newest first.+class SuperTabProjectRules {+ SuperTabProjectRules.fromJson(Map<String, dynamic> row)+ : projectId = row['projectId'] as String? ?? '',+ revision = (row['revision'] as num?)?.toInt() ?? 0,+ seeded = row['seeded'] == true,+ rules = row['rules'] as Map<String, dynamic>? ?? const {},+ history = List.unmodifiable([+ for (final entry in row['history'] as List? ?? const [])+ if (entry is Map<String, dynamic>)+ SuperTabRulesRevision.fromJson(entry),+ ]);+ final String projectId;+ final int revision;+ final bool seeded;+ final Map<String, dynamic> rules;+ final List<SuperTabRulesRevision> history;+}++/// The backend path of a project's rules record.+String superTabRulesPath(String tabId, String projectId) =>+ '/api/super-tabs/${Uri.encodeComponent(tabId)}/projects/'+ '${Uri.encodeComponent(projectId)}/rules';++/// Project settings ▸ Project rules (task #3393): the record and its history, read only. People change it by asking+/// the PM, who saves it with their message.+Future<void> showSuperTabProjectRules(+ BuildContext context,+ SuperTabController c,+ String projectId,+) => showAppDialog<void>(+ context: context,+ builder: (context) => SuperTabDialogScope(+ controller: c,+ projectId: projectId,+ requireWrite: false,+ child: _ProjectRulesDialog(controller: c, projectId: projectId),+ ),+);++class _ProjectRulesDialog extends StatefulWidget {+ const _ProjectRulesDialog({+ required this.controller,+ required this.projectId,+ });++ final SuperTabController controller;+ final String projectId;++ @override+ State<_ProjectRulesDialog> createState() => _ProjectRulesDialogState();+}++class _ProjectRulesDialogState extends State<_ProjectRulesDialog> {+ SuperTabController get c => widget.controller;+ SuperTabProjectRules? _rules;+ Object? _failure;++ /// Counts reads, so that an older answer never lands over a newer one.+ int _reads = 0;++ @override+ void initState() {+ super.initState();+ unawaited(_read());+ }++ Future<void> _read() async {+ final read = ++_reads;+ if (_failure != null) setState(() => _failure = null);+ try {+ final answer = await c.request(+ 'GET',+ superTabRulesPath(c.tabId, widget.projectId),+ );+ if (!mounted || read != _reads) return;+ setState(() => _rules = SuperTabProjectRules.fromJson(answer));+ } catch (failure) {+ if (!mounted || read != _reads) return;+ setState(() => _failure = failure);+ }+ }++ String get _projectName =>+ c.snapshot?.projects+ .where((p) => p.id == widget.projectId)+ .firstOrNull+ ?.name ??+ 'Project';++ @override+ Widget build(BuildContext context) {+ final rules = _rules;+ return SuperTabDetailDialog(+ title: 'Project rules',+ detail: rules == null+ ? _projectName+ : rules.seeded+ ? '$_projectName · Built-in rules'+ : '$_projectName · Revision ${rules.revision}',+ body: rules == null ? _empty() : _body(rules),+ footer: rules == null+ ? null+ : Text(+ 'To change these, ask the PM in the project chat.',+ style: DesktopChrome.metadata(),+ ),+ );+ }++ Widget _empty() {+ final failure = _failure;+ if (failure is SuperTabFailure &&+ superTabMissingRoute(failure.code, failure.statusCode)) {+ return Text(+ 'Project rules are not available on this server yet.',+ style: DesktopChrome.text(),+ );+ }+ if (failure != null) {+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ 'Could not read the project rules.',+ style: DesktopChrome.metadata(),+ ),+ const SizedBox(height: _gap),+ TextButton(onPressed: _read, child: const Text('Try again')),+ ],+ );+ }+ return SkeletonBlock(+ semanticsLabel: 'Loading the project rules',+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ for (final width in const [.5, .8, .7, .6, .8])+ SkeletonText(style: DesktopChrome.text(), widthFactor: width),+ ],+ ),+ );+ }++ Widget _body(SuperTabProjectRules record) {+ final rules = record.rules;+ Map<String, dynamic> section(String key) =>+ rules[key] as Map<String, dynamic>? ?? const {};+ List<Map<String, dynamic>> list(Object? value) => [+ for (final entry in value as List? ?? const [])+ if (entry is Map<String, dynamic>) entry,+ ];+ String joined(Object? value) =>+ [for (final v in value as List? ?? const []) '$v'].join(', ');+ final window = section('releaseWindow');+ final pace = section('releasePace');+ final reviews = section('reviews');+ final train = section('mergeTrain');+ final pause = pace['backendPause'] as Map<String, dynamic>?;+ Widget row(String label, String value) =>+ SuperTabDetailRow(label: label, value: value);+ // The named lists: each with entries is its own section; the empty ones share one line, as the mockup draws.+ final lists =+ <(String, String, String, String Function(Map<String, dynamic>))>[+ (+ 'Crew',+ 'crew',+ 'role',+ (r) {+ final names = joined(r['names']);+ return names.isEmpty ? 'Nobody yet' : names;+ },+ ),+ ('Caps', 'caps', 'name', (r) => '${r['value']}'),+ ('Paths', 'paths', 'name', (r) => '${r['path'] ?? ''}'),+ ('Lanes', 'lanes', 'name', (r) => joined(r['owns'])),+ ];+ final empty = [+ for (final (title, key, _, _) in lists)+ if (list(rules[key]).isEmpty) title,+ ];++ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ SuperTabDetailSection(+ first: true,+ title: 'Releases',+ children: [+ row(+ 'Window',+ '${window['start']}–${window['end']} ${window['timeZone']}',+ ),+ row(+ 'Backend',+ [+ 'At most every ${_minutes(pace['backendEveryMinutes'])}',+ if (pause != null) 'not ${pause['start']}–${pause['end']}',+ ].join(' · '),+ ),+ row(+ 'Desktop, CLI and web',+ pace['appsAfterVisibleBatch'] == true+ ? 'After each visible batch'+ : 'When someone releases them',+ ),+ ],+ ),+ SuperTabDetailSection(+ title: 'Reviews',+ children: [+ row('Every change', _reads_(reviews['defaultReads'])),+ for (final r in list(reviews['rows']))+ row(+ '${r['area'] ?? ''}',+ [+ _reads_(r['reads']),+ if (joined(r['paths']).isNotEmpty) joined(r['paths']),+ ].join(' · '),+ ),+ ],+ ),+ SuperTabDetailSection(+ title: 'Tests',+ children: [+ for (final t in list(reviews['test']))+ row('${t['where'] ?? ''}', joined(t['paths'])),+ if (joined(reviews['untested']).isNotEmpty)+ row('No test needed', joined(reviews['untested'])),+ ],+ ),+ SuperTabDetailSection(+ title: 'Merge train',+ children: [+ row(+ 'Batch merge',+ '${train['enabled'] == true ? 'On' : 'Off'} · every '+ '${train['everyMinutes']} minutes',+ ),+ ],+ ),+ for (final (title, key, label, value) in lists)+ if (list(rules[key]).isNotEmpty)+ SuperTabDetailSection(+ title: title,+ children: [+ for (final r in list(rules[key]))+ row('${r[label] ?? ''}', value(r)),+ ],+ ),+ if (empty.isNotEmpty)+ SuperTabDetailSection(+ title: empty.join(' · '),+ children: [Text('None yet.', style: DesktopChrome.metadata())],+ ),+ SuperTabDetailSection(+ title: 'History',+ children: record.history.isEmpty+ ? [Text('No changes yet.', style: DesktopChrome.metadata())]+ : [for (final entry in record.history) _revision(entry)],+ ),+ ],+ );+ }++ Widget _revision(SuperTabRulesRevision entry) => Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ const SizedBox(height: _halfGap),+ Text(+ 'Revision ${entry.revision} · ${_writer(entry)} · '+ '${relativeAgo(entry.at, DateTime.now())}',+ style: DesktopChrome.metadata(),+ ),+ Text(entry.summary, style: DesktopChrome.control()),+ for (final change in entry.diff)+ Text(+ '${change.path} ${_shown(change.before)} → ${_shown(change.after)}',+ style: DesktopChrome.metadata(),+ ),+ const SizedBox(height: _halfGap),+ ],+ );++ String _personName(String id) =>+ c.snapshot?.people.where((p) => p.id == id).firstOrNull?.shownName ??+ 'a member';++ /// Who saved a revision: a person by name, the PM by its agent's name; `for <asker>` when it carries someone+ /// else's words.+ String _writer(SuperTabRulesRevision entry) {+ final by = entry.writtenBy;+ final name = by.kind == 'agent'+ ? c.snapshot?.agentName(by.id, fallback: 'The PM') ?? 'The PM'+ : _personName(by.id);+ final asker = entry.askedBy;+ if (asker == null || asker == by.id) return name;+ return '$name for ${_personName(asker)}';+ }+}++String _minutes(Object? value) {+ final minutes = (value as num?)?.toInt() ?? 0;+ if (minutes > 0 && minutes % 60 == 0) return '${minutes ~/ 60} h';+ return '$minutes min';+}++String _reads_(Object? value) {+ final reads = (value as num?)?.toInt() ?? 1;+ return reads == 1 ? '1 read' : '$reads reads';+}++/// A value in a change line: a switch as On or Off, nothing as None, a list or a section by its size.+String _shown(Object? value) => switch (value) {+ true => 'On',+ false => 'Off',+ null => 'None',+ final List list => list.length == 1 ? '1 entry' : '${list.length} entries',+ final Map _ => 'changed',+ _ => '$value',+};diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex ba091b41b..86a665f7b 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -59,6 +59,7 @@ import 'dialog_scope.dart';import 'folder_zip.dart';import 'crew_panel.dart';import 'instructions_panel.dart';+import 'project_rules.dart';import 'model.dart';import 'agent_details.dart';import 'identity.dart' show superTabMachineName;@@ -1793,6 +1794,13 @@ class _SuperTabViewState extends State<SuperTabView>}return;}+ if (action == 'rules') {+ final project = c.snapshot?.projectFor(group.id);+ if (project != null) {+ await showSuperTabProjectRules(context, c, project.id);+ }+ return;+ }if (action == 'crew') {final project = c.snapshot?.projectFor(group.id);if (project != null) await showSuperTabCrew(context, c, project.id);@@ -2398,10 +2406,14 @@ class _SuperTabViewState extends State<SuperTabView>if (_page == null) return;_page = null;c.select(id);- // A tag in a thread opens the thread; one in a thread reply shown only- // there is not in the chat to scroll to.- if (message.thread case final root?) {- c.openThread(root, at: message.inMainStream ? null : message.id);+ // A tag in a thread reply opens the thread; one shown only there is not in+ // the chat to scroll to. A top-level message is its own thread's root, but+ // it has no thread to open: it is in the chat.+ if (message.threadReply) {+ c.openThread(+ message.thread!,+ at: message.inMainStream ? null : message.id,+ );if (!message.inMainStream) return;}setState(() {@@ -3887,6 +3899,8 @@ class _SuperTabViewState extends State<SuperTabView>repository?['cwd'] as String? ??'Not set',),+ // The project's numbers, read only (task #3393): every member reads them; the PM changes them when asked.+ row('Project rules', 'rules'),// While the PM has a switch under way, there is nothing to ask for.if (editable &&c.snapshot?.maySwitchLead(project.id, c.accountId) == true &&diff --git a/desktop/scripts/release-desktop.sh b/desktop/scripts/release-desktop.shindex 53ac9bc26..70f981be2 100755--- a/desktop/scripts/release-desktop.sh+++ b/desktop/scripts/release-desktop.sh@@ -48,11 +48,16 @@ ALLOW_NO_MANIFEST=0ALLOW_OLDER=0NEW_VER=""NOTES_FILE=""+URGENT_SET=0+URGENT=""want_notes_file=0+want_urgent=0for arg in "$@"; doif [ "$want_notes_file" -eq 1 ]; then NOTES_FILE="$arg"; want_notes_file=0; continue; fi+ if [ "$want_urgent" -eq 1 ]; then URGENT="$arg"; want_urgent=0; continue; ficase "$arg" in+ --urgent) URGENT_SET=1; want_urgent=1 ;;--dry-run) DRY_RUN=1 ;;--wait) WAIT=1 ;;--prepare) PREPARE=1 ;;@@ -78,6 +83,12 @@ if [ "$WAIT" -eq 1 ] || { [ "$PREPARE" -eq 1 ] && [ "$DRY_RUN" -eq 0 ]; }; thenfi[ "$want_notes_file" -eq 0 ] || { echo "ERROR --notes-file needs a path" >&2; exit 1; }+# --- the release window: refused with RELEASE_WINDOW outside 09:00-18:00 Asia/Ho_Chi_Minh, naming the next allowed+# time (scripts/release-window.py). A P0 passes --urgent "<reason>"; the reason goes on the tag.+# A --prepare candidate publishes nothing, so it is not a release and runs at any hour.+source "$ROOT/../scripts/release-window.sh"+[ "$PREPARE" -eq 1 ] || release_window_guard desktop+# Same rules as next_desktop_version()/bump_minor_version() in scripts/upload-desktop.sh:55-86, which# is where this convention is defined. Note the rollover: .99 goes to the next MINOR at .1, not .0.next_patch_version() {@@ -304,6 +315,7 @@ if [ "$PREPARE" -eq 1 ]; thenfi# --- tag and push ---+[ -z "$URGENT_TAG_LINE" ] || printf '\n%s\n' "$URGENT_TAG_LINE" >> "$NOTES"git tag -a "$TAG" --cleanup=verbatim -F "$NOTES"git push origin "$TAG"diff --git a/desktop/scripts/release-web.sh b/desktop/scripts/release-web.shindex ea38df536..c5d29a2dc 100755--- a/desktop/scripts/release-web.sh+++ b/desktop/scripts/release-web.sh@@ -13,6 +13,7 @@# Usage (from the repo root, `make release-web ARGS=...` runs the same thing):# bash desktop/scripts/release-web.sh # bump the patch of the last v*_web tag and ship# bash desktop/scripts/release-web.sh --dry-run # print the plan, tag/push nothing+# bash desktop/scripts/release-web.sh --urgent "P0: why" # a P0 outside the 09:00-18:00 VN release window# bash desktop/scripts/release-web.sh --minor # bump the MINOR version# bash desktop/scripts/release-web.sh --website-only # preserve the deployed Flutter bundle# bash desktop/scripts/release-web.sh 1.3.0 # an explicit version@@ -44,13 +45,18 @@ DO_MINOR=0WEBSITE_ONLY=0ALLOW_OLDER=0NEW_VER=""+URGENT_SET=0+URGENT=""+want_urgent=0for arg in "$@"; do+ if [ "$want_urgent" -eq 1 ]; then URGENT="$arg"; want_urgent=0; continue; ficase "$arg" in+ --urgent) URGENT_SET=1; want_urgent=1 ;;--dry-run) DRY_RUN=1 ;;--minor) DO_MINOR=1 ;;--website-only) WEBSITE_ONLY=1 ;;--allow-older) ALLOW_OLDER=1 ;;- -h|--help) sed -n '2,31p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; exit 0 ;;+ -h|--help) sed -n '2,32p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; exit 0 ;;-*) echo "ERROR unknown flag: $arg" >&2; exit 1 ;;*) NEW_VER="${arg#v}" ;;esac@@ -106,6 +112,10 @@ if git rev-parse -q --verify "refs/tags/$TAG" >/dev/null; thenfielseTAG_EXISTS=0+ # A new tag is a release, so the window applies (RELEASE_WINDOW, scripts/release-window.py). Resuming an existing+ # tag publishes nothing new and is not refused. A P0 passes --urgent "<reason>"; the reason goes on the tag.+ source "$ROOT/scripts/release-window.sh"+ release_window_guard web[ -z "$(git status --porcelain)" ] || { git status --short >&2; die "working tree is dirty — the tag must capture the tested source exactly"; }SHA="$(git rev-parse HEAD)"git merge-base --is-ancestor "$SHA" "origin/$BRANCH" 2>/dev/null \@@ -147,9 +157,9 @@ fi# --- 1. the tag ---if [ "$TAG_EXISTS" -eq 0 ]; thenif [ "$WEBSITE_ONLY" -eq 1 ]; then- git tag -a "$TAG" -m "Harness website $VER" -m 'Website-Only: true' "$SHA"+ git tag -a "$TAG" -m "Harness website $VER" -m 'Website-Only: true' ${URGENT_TAG_LINE:+-m "$URGENT_TAG_LINE"} "$SHA"else- git tag -a "$TAG" -m "Harness web $VER" "$SHA"+ git tag -a "$TAG" -m "Harness web $VER" ${URGENT_TAG_LINE:+-m "$URGENT_TAG_LINE"} "$SHA"figit push origin "$TAG"say "pushed $TAG"diff --git a/desktop/test/super_tab_backend_transport_test.dart b/desktop/test/super_tab_backend_transport_test.dartindex a90b62933..ef599be60 100644--- a/desktop/test/super_tab_backend_transport_test.dart+++ b/desktop/test/super_tab_backend_transport_test.dart@@ -337,6 +337,8 @@ void main() {('GET', '/api/super-tabs/tab1/projects/p1/instructions'),('GET', '/api/super-tabs/tab1/projects/p1/instructions/revisions'),('GET', '/api/super-tabs/tab1/projects/p1/instructions/revisions/4'),+ // The project's rules record, read only in Project settings (#3393).+ ('GET', '/api/super-tabs/tab1/projects/p1/rules'),('GET', '/api/super-tabs/tab1/route-decisions/d1'),('POST', '/api/super-tabs/tab1/machines/m1/removal'),('POST', '/api/super-tabs/tab1/join'),diff --git a/desktop/test/super_tab_personal_lead_test.dart b/desktop/test/super_tab_personal_lead_test.dartindex fdf229241..36d90aeab 100644--- a/desktop/test/super_tab_personal_lead_test.dart+++ b/desktop/test/super_tab_personal_lead_test.dart@@ -199,6 +199,36 @@ void main() {expect(_create(f)['cwd'], '/Users/huy/games');});+ // Task #3449 (anh Dee, 11-05): a PM was seen on Sonnet medium. A Personal+ // project's Lead, started on this Mac, runs Claude on Opus at xhigh as flags+ // of its launch; a Codex Lead takes no Claude flags.+ test(+ 'a Claude Lead starts on Opus at xhigh, a Codex Lead with no model flags',+ () async {+ final f = SuperTabLaunchFixture();+ _desk(f, remote: 'https://github.com/huy/games', cwd: '/Users/huy/games');+ final c = await _swarm(f);+ final games = _games(c);+ await PersonalLeadStarter.of(f.app).start(c, games);+ expect(_create(f)['engine'], 'claude');+ expect(_create(f)['model'], 'opus');+ expect(_create(f)['effort'], 'xhigh');++ final codex = SuperTabLaunchFixture();+ _desk(+ codex,+ remote: 'https://github.com/huy/games',+ cwd: '/Users/huy/games',+ );+ final other = await _swarm(codex);+ await PersonalLeadStarter.of(codex.app)+ .start(other, _games(other), machineId: 'm', engine: 'codex');+ expect(_create(codex)['engine'], 'codex');+ expect(_create(codex).containsKey('model'), isFalse);+ expect(_create(codex).containsKey('effort'), isFalse);+ },+ );+test('a Team Swarm starts no Lead', () async {final f = SuperTabLaunchFixture();_desk(f, remote: 'https://github.com/huy/games', cwd: '/Users/huy/games');diff --git a/desktop/test/super_tab_project_rules_test.dart b/desktop/test/super_tab_project_rules_test.dartnew file mode 100644index 000000000..3dd0a620a--- /dev/null+++ b/desktop/test/super_tab_project_rules_test.dart@@ -0,0 +1,270 @@+import 'dart:io';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/widgets/app_menu.dart';+import 'package:harness/super_tabs/detail_dialog.dart';+import 'package:harness/super_tabs/project_rules.dart';++import 'super_tab_mentions_test.dart' show showView;+import 'support/capture.dart';+import 'support/super_tab_fixture.dart';++/// The backend's seed (superTabs/policy.ts SEED_RULES), cut to two review rows and two test rows.+Map<String, dynamic> _rules({bool train = false}) => {+ 'releaseWindow': {+ 'start': '09:00',+ 'end': '18:00',+ 'timeZone': 'Asia/Ho_Chi_Minh',+ },+ 'releasePace': {+ 'backendEveryMinutes': 120,+ 'appsAfterVisibleBatch': true,+ 'backendPause': {'start': '09:00', 'end': '10:00'},+ },+ 'reviews': {+ 'defaultReads': 1,+ 'rows': [+ {+ 'area': 'Sign-in',+ 'reads': 2,+ 'paths': ['**/*auth*', '**/*login*', '**/*logout*'],+ },+ {+ 'area': 'Deletion',+ 'reads': 2,+ 'paths': ['**/*delet*'],+ },+ ],+ 'test': [+ {+ 'where': 'Desktop on a Mac',+ 'paths': ['desktop/**'],+ },+ {+ 'where': 'The phone app in a simulator',+ 'paths': ['mobile/**'],+ },+ ],+ 'untested': ['**/*.md', 'docs/**'],+ },+ 'mergeTrain': {'enabled': train, 'everyMinutes': 10},+ 'caps': <dynamic>[],+ 'paths': <dynamic>[],+ 'crew': [+ {+ 'role': 'Engineer',+ 'names': ['Ledger', 'Yarrow4'],+ },+ ],+ 'lanes': <dynamic>[],+};++Map<String, dynamic> _saved() => {+ 'projectId': 'lead',+ 'revision': 3,+ 'rules': _rules(train: true),+ 'seeded': false,+ 'history': [+ {+ 'revision': 3,+ 'rules': _rules(train: true),+ 'summary': 'Merge train on',+ 'diff': [+ {'path': 'mergeTrain.enabled', 'before': false, 'after': true},+ ],+ 'writtenBy': {'kind': 'agent', 'id': 'lead-agent'},+ 'askedBy': 'peer',+ 'askedIn': {'conversationId': 'lead', 'messageId': 'm1'},+ 'at': DateTime.now()+ .subtract(const Duration(hours: 2))+ .toUtc()+ .toIso8601String(),+ },+ {+ 'revision': 2,+ 'rules': _rules(),+ 'summary': 'Releases start at 10',+ 'diff': [+ {'path': 'releaseWindow.start', 'before': '09:00', 'after': '10:00'},+ ],+ 'writtenBy': {'kind': 'person', 'id': 'owner'},+ 'askedBy': 'owner',+ 'askedIn': null,+ 'at': DateTime.now()+ .subtract(const Duration(days: 1))+ .toUtc()+ .toIso8601String(),+ },+ ],+};++ConversationServer _swarm(Map<String, dynamic>? rules) {+ final server = ConversationServer();+ server.state['projects'] = [projectFixture('lead', 'openharness', 'lead')];+ (server.state['people'] as List).add({+ 'id': 'peer',+ 'email': '[email protected]',+ 'role': 'collaborator',+ 'username': 'dee',+ });+ (server.state['agents'] as List).add({+ 'id': 'lead-agent',+ 'projectId': 'lead',+ 'name': 'Lead',+ 'displayName': 'River',+ 'machineId': 'host',+ 'harnessId': 'session',+ 'contributorId': 'owner',+ 'configuration': {'engine': 'codex'},+ });+ if (rules != null) server.projectRules['lead'] = rules;+ return server;+}++Future<void> _openRules(WidgetTester tester) async {+ await tester.tap(find.byTooltip('Project options'));+ await tester.pumpAndSettle();+ await tester.tap(find.widgetWithText(AppMenuItem, 'Project settings…'));+ await tester.pumpAndSettle();+ await tester.tap(+ find.byKey(const ValueKey('super-project-setting-Project rules')),+ );+ await tester.pumpAndSettle();+}++/// Set to a folder to write the PR's pictures of the dialog there, in light and dark.+final _shots = Platform.environment['PROJECT_RULES_SHOTS'];++void main() {+ setUpAll(() => loadCaptureFonts(_shots));++ for (final brightness in Brightness.values) {+ testWidgets('pictures of Project rules (${brightness.name})', (+ tester,+ ) async {+ if (_shots == null) return;+ tester.view.devicePixelRatio = 2;+ addTearDown(tester.view.reset);+ final c = await showView(+ tester,+ _swarm(_saved()),+ brightness: brightness,+ );+ await _openRules(tester);+ await captureWindow(tester, _shots, 'project-rules-${brightness.name}');+ await c.flush();+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));+ }++ test('reads the backend\'s answer, seed and history', () {+ final rules = SuperTabProjectRules.fromJson(_saved());+ expect(rules.revision, 3);+ expect(rules.seeded, isFalse);+ expect(rules.rules['mergeTrain'], {'enabled': true, 'everyMinutes': 10});+ expect(rules.history.map((h) => h.revision), [3, 2]);+ expect(rules.history.first.writtenBy, (kind: 'agent', id: 'lead-agent'));+ expect(rules.history.first.askedBy, 'peer');+ expect(rules.history.first.diff.single.path, 'mergeTrain.enabled');+ expect(+ superTabRulesPath('tab 1', 'lead'),+ '/api/super-tabs/tab%201/projects/lead/rules',+ );+ });++ for (final brightness in Brightness.values) {+ testWidgets('Project settings opens the rules, read only, with their '+ 'history (${brightness.name})', (tester) async {+ final server = _swarm(_saved());+ final c = await showView(tester, server, brightness: brightness);+ await _openRules(tester);+ expect(server.rulesReads, ['/api/super-tabs/tab/projects/lead/rules']);+ for (final text in [+ 'Project rules',+ 'openharness · Revision 3',+ 'Releases',+ '09:00–18:00 Asia/Ho_Chi_Minh',+ 'At most every 2 h · not 09:00–10:00',+ 'After each visible batch',+ 'Reviews',+ 'Every change',+ '1 read',+ 'Sign-in',+ '2 reads · **/*auth*, **/*login*, **/*logout*',+ 'Desktop on a Mac',+ 'desktop/**',+ 'Merge train',+ 'On · every 10 minutes',+ 'Crew',+ 'Engineer',+ 'Ledger, Yarrow4',+ 'Caps · Paths · Lanes',+ 'None yet.',+ 'History',+ 'Merge train on',+ 'mergeTrain.enabled Off → On',+ 'Releases start at 10',+ 'releaseWindow.start 09:00 → 10:00',+ 'To change these, ask the PM in the project chat.',+ ]) {+ expect(find.text(text), findsWidgets, reason: text);+ }+ expect(+ find.textContaining('River for dee · 2 hours ago'),+ findsOneWidget,+ );+ expect(find.textContaining('Revision 2 · '), findsOneWidget);+ // Read only: nothing to type into or save.+ final dialog = find.byType(SuperTabDetailDialog);+ expect(+ find.descendant(of: dialog, matching: find.byType(TextField)),+ findsNothing,+ );+ expect(+ find.descendant(of: dialog, matching: find.byType(FilledButton)),+ findsNothing,+ );+ await c.flush();+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));+ }++ testWidgets('a project with no save shows the built-in rules', (+ tester,+ ) async {+ final server = _swarm({+ 'projectId': 'lead',+ 'revision': 0,+ 'rules': _rules(),+ 'seeded': true,+ 'history': <dynamic>[],+ });+ final c = await showView(tester, server);+ await _openRules(tester);+ expect(find.text('openharness · Built-in rules'), findsOneWidget);+ expect(find.text('Off · every 10 minutes'), findsOneWidget);+ expect(find.text('No changes yet.'), findsOneWidget);+ await c.flush();+ });++ testWidgets('a backend without rules says so, and a failed read can be '+ 'tried again', (tester) async {+ final server = _swarm(_saved())..rulesRoute = false;+ final c = await showView(tester, server);+ await _openRules(tester);+ expect(+ find.text('Project rules are not available on this server yet.'),+ findsOneWidget,+ );+ await tester.tap(find.byTooltip('Close'));+ await tester.pumpAndSettle();+ server.rulesRoute = true;+ server.projectRules.remove('lead');+ await _openRules(tester);+ expect(find.text('Could not read the project rules.'), findsOneWidget);+ server.projectRules['lead'] = _saved();+ await tester.tap(find.text('Try again'));+ await tester.pumpAndSettle();+ expect(find.text('openharness · Revision 3'), findsOneWidget);+ await c.flush();+ });+}diff --git a/desktop/test/super_tab_reminders_test.dart b/desktop/test/super_tab_reminders_test.dartindex 1fd73538f..2909c363f 100644--- a/desktop/test/super_tab_reminders_test.dart+++ b/desktop/test/super_tab_reminders_test.dart@@ -13,8 +13,8 @@ const _question = 'Should a reminder clear when it is opened?';/// Three messages in the Lead conversation, the last an agent's question,/// read to the end.-ConversationServer _chat() {- final server = ConversationServer();+ConversationServer _chat({bool threads = false}) {+ final server = ConversationServer()..threads = threads;server.append('Planning the reminders');server.append('Draft PR is up');server.append(_question);@@ -30,8 +30,12 @@ void main() {late SuperTabController c;late List<String> arrived;- Future<void> show(WidgetTester tester, ConversationServer server) async {- await tester.binding.setSurfaceSize(const Size(1200, 900));+ Future<void> show(+ WidgetTester tester,+ ConversationServer server, {+ double width = 1200,+ }) async {+ await tester.binding.setSurfaceSize(Size(width, 900));addTearDown(() => tester.binding.setSurfaceSize(null));c = server.controller();arrived = [];@@ -287,4 +291,58 @@ void main() {]);expect(arrived, ['reminder-message-2']);});++ // A due reminder of a top-level message opened the chat at it and also an+ // empty Thread pane rooted at it: the message showed twice, under 1080 px+ // the drawer covered the chat, and a thread read mark was sent (Diego,+ // 2026-11-05). The backend gives every top-level message its own id as its+ // thread, so only a reply (`threadReply`) has a thread to open.+ for (final width in [1200.0, 1000.0]) {+ testWidgets('a reminder of a top-level message opens no thread, at '+ '${width.round()} px', (tester) async {+ final server = _chat(threads: true);+ server.remindElsewhere(+ 'message-3',+ clock.now().add(const Duration(minutes: 20)),+ );+ await show(tester, server, width: width);+ await tester.pump(const Duration(minutes: 20, seconds: 1));+ await tester.pumpAndSettle();+ await openActivity(tester);+ await tester.tap(reminderRow('message-3'));+ await tester.pumpAndSettle();++ expect(c.selectedId, 'lead');+ expect(c.openedThread, isNull);+ expect(find.byKey(const ValueKey('super-thread-panel')), findsNothing);+ expect(server.threadMarkPosts, isEmpty);+ expect(find.text(_question).hitTestable(), findsOneWidget);+ });+ }++ for (final width in [1200.0, 1000.0]) {+ testWidgets('a reminder of a reply that lives only in its thread opens '+ 'the thread at that reply, at ${width.round()} px', (tester) async {+ final server = _chat(threads: true);+ server.append('Only in the thread');+ server.messages.last+ ..['thread'] = 'message-2'+ ..['alsoInChat'] = false;+ server.remindElsewhere(+ 'message-4',+ clock.now().add(const Duration(minutes: 20)),+ );+ await show(tester, server, width: width);+ await tester.pump(const Duration(minutes: 20, seconds: 1));+ await tester.pumpAndSettle();+ await openActivity(tester);+ await tester.tap(reminderRow('message-4'));+ await tester.pumpAndSettle();++ expect(c.selectedId, 'lead');+ expect(c.openedThread, (conversationId: 'lead', root: 'message-2'));+ expect(find.byKey(const ValueKey('super-thread-panel')), findsOneWidget);+ expect(find.text('Only in the thread').hitTestable(), findsOneWidget);+ });+ }}diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dartindex b10ce0759..663e051ee 100644--- a/desktop/test/support/super_tab_fixture.dart+++ b/desktop/test/support/super_tab_fixture.dart@@ -656,6 +656,12 @@ class ConversationServer {/// Every instructions read, by path.final instructionReads = <String>[];++ /// Each project's rules record as GET .../projects/:id/rules answers it (backend store.ts `projectRules`), by+ /// project id; a project missing here reads as unavailable. False [rulesRoute] answers as a backend from before it.+ final projectRules = <String, Map<String, dynamic>>{};+ bool rulesRoute = true;+ final rulesReads = <String>[];final state = <String, dynamic>{'version': 1,'id': 'tab',@@ -1830,6 +1836,27 @@ class ConversationServer {uri.pathSegments[5] == 'instructions') {return _readInstructions(path, uri);}+ if (uri.pathSegments.length == 6 &&+ uri.pathSegments[3] == 'projects' &&+ uri.pathSegments[5] == 'rules') {+ rulesReads.add(path);+ if (!rulesRoute) {+ throw const SuperTabFailure(+ 'BACKEND_UNAVAILABLE',+ 'Not Found',+ statusCode: 404,+ );+ }+ final rules = projectRules[uri.pathSegments[4]];+ if (rules == null) {+ throw const SuperTabFailure(+ 'NOT_FOUND',+ 'This project is unavailable.',+ statusCode: 404,+ );+ }+ return jsonDecode(jsonEncode(rules)) as Map<String, dynamic>;+ }if (uri.pathSegments.length > 2 &&uri.pathSegments[uri.pathSegments.length - 2] == 'attachments') {fileLinkReads.add(path);diff --git a/docs/plans/2026-11-05-handed-on-ready-plan.md b/docs/plans/2026-11-05-handed-on-ready-plan.mdnew file mode 100644index 000000000..45433780c--- /dev/null+++ b/docs/plans/2026-11-05-handed-on-ready-plan.md@@ -0,0 +1,118 @@+# An engineer is free once its PR is ready for review: 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:** A task whose pull request is ready for review is handed over: its Engineer is free for new work, keeps its+GitHub push access to fix findings, and the task comes back to it on a No verdict, red CI or a merge conflict. If that+Engineer is down, or has not picked it back up within 60 minutes, the task is released so anyone free in the lane takes+it (task #3399, requested by Dee through Harness).++**Architecture:** "Handed" is the `review` status of a task (not a step), the status its Engineer sets when it marks the+pull request ready. A new module `backend/src/superTabs/handed.ts` holds the rule and its one constant:+`handed(group)`, `occupiesAgent(group)` (active work that is not handed), `reopenHanded(...)` and `REOPEN_OWNER_MS`.+`activeWork` keeps meaning "the task is open" (archive, steps, deletion and token holds all need that); every check+that asks "is this agent busy" reads `occupiesAgent` instead. A reopen puts the same assignment back to `working`, so the+assignment id, the GitHub token hold and "built by" (the run ledger) do not change.++**Tech Stack:** TypeScript backend (vitest unit tests; the Mongo integration suite runs in PR CI).++**Spec:** task #3399 brief and its two acceptance checks.++## Design note++**States.**++| From | Event | To |+| --- | --- | --- |+| working | Engineer's own Ready (`work.status review`) | review = handed: Engineer free, hold kept |+| review (handed) | a failed check by someone other than the Engineer (a Reviewer's or Tester's No; sibling #3394 makes that the verdict signal), or a step's own agent failing its step check | working, `reopened {at, why}`, Engineer told |+| review (handed) | PR watch: CI failed on the current head, or a merge conflict | working, `reopened`, Engineer told in the same CI/conflict message |+| working + reopened | Engineer's own status, check or post in the task | working (pick-up; `reopened` cleared) |+| working + reopened | 60 minutes (`REOPEN_OWNER_MS`) with no pick-up, or the Engineer is down (session stopped, machine offline, usage limit) | lost, so the PM (or #3400's dispatcher) hands it to anyone free in the lane |+| review (handed) | Engineer sets done after merge | done; hold and run released as today |++A handed task is never lost for its Engineer's machine or session: nothing waits on that agent. One exception to the+reopen: a grid attempt whose review failed is not pinned to its grid agent, since its next attempt steps up to a stronger+model (decision 8); it stays in review for the coordinator to route, as before. A step's own Ready+(a Reviewer's or Tester's) is not a handover; steps keep today's rules.++**Why not a new `handed` WorkStatus.** Older CLIs and Desktop read the status and show "Ready for review"; a new value+would show as unknown on every client released before this change. The `review` status already means exactly "the PR is+ready", so it is the state; `Assignment.reopened` is the only new field.++**Token holds.** `github/holds.ts` HOLDING keeps `review`, so a handed task keeps its hold and the Engineer can push fixes.+A reopen keeps the assignment id, so no hold starts or ends. While the Engineer holds two tasks (one handed, one new),+`githubAssignment` gives the token for the task in its hands first (working/needs_human/blocked), then the handed one, so+a handed task's merge (which revokes its tokens) never revokes the token the new task is pushing with.++**Assignment ids and run records.** The new task gets its own assignment id as today. The cross-Swarm run record+(`superTabRun`, one per agent) moves to the new assignment: a handed assignment's record is replaced without cancelling+its queued deliveries (a Reviewer's findings to the Engineer must still arrive). Known limit: once the new task ends, the+agent has no run record while the handed one is open, so the cross-Swarm fence does not cover the handed task; nothing+in it is in the agent's hands then.++**Busy checks moved to `occupiesAgent`:** `work.assign` and `work.resume` AGENT_BUSY, `workerIndex.working`+(awaitingWorkers), the coordinator's idle notice (tidy.ts: its own handed task leaves it idle; a Reviewer or Tester in+someone else's open task is still not idle), `finishWorker` (no "awaiting" mark while another task is in its hands). Light+reads now keep `reviewOf` (parts/light.ts), since `handed` tells a task from a step. Unchanged (they mean "task open"): archive, deletion, steps' `reviewedBuild`, agent stop/release/remove+(stopping an Engineer whose task is in review still waits, as today).++### Design checklist++- growth: one `reopened` object per assignment, cleared at pick-up or the next status; nothing else stored.+- concurrency: every change is in the group's own write (commands, and store.ts pullRequestSeen's transaction).+- read cost: no new reads; the PR watch already reads each open task's PR every minute.+- scale: 10x tasks is 10x reopen checks in the same loops; the watch's pass log line warns first.+- compatibility: old clients see `working`/`review` as today and ignore `reopened`. An older server reading a reopened row+ sees an ordinary working task.+- migration + rollback: none. Rolling back makes `review` busy again; a reopened row is plain `working`.+- audience: reopen is triggered only by server-read GitHub state or a recorded check verdict; no client field sets it.+- identity: N/A because nothing here acts as a person.+- failure: a reopen and a release each post a line in the task to its Engineer (and the release to the coordinator, as+ any loss does); nothing changes silently.+- platforms: backend only.++## Global Constraints++- Owns backend/src/superTabs/ and backend/src/github/ only. Swarm code stays out of cli/src/core.+- No new refusal code. `removedRefusals.test.ts` stays green.+- The 60-minute number lives in one constant (`REOPEN_OWNER_MS`) until the project rules record (#3393) lands.+- Tests never sign the Mac out of the real CLI. Temp files only in mktemp -d folders.++## Review Focus++- Security (token holds): a handed task keeps its hold; a reopen neither ends nor starts one; `githubAssignment` picks the+ in-hand task first; an agent with no task in progress still gets no token.+- A handed Engineer is free in every busy check, and still busy in stop/release.+- A reopen keeps assignment id and run ledger ("built by"); the 60-minute release reaches the lane through the normal loss.++## Task 1: a handed Engineer is free for new work and keeps its push access++**Files:** backend/src/superTabs/handed.ts (new), handed.test.ts (new), model.ts, commands.ts, tidy.ts, store.ts,+github/holds.test.ts (new)++**Interfaces:** `handed(group): boolean`, `occupiesAgent(group): boolean`, `REOPEN_OWNER_MS`.++- [ ] Test: Engineer sets review; assigning it a second task succeeds (AGENT_BUSY before); `awaitingWorkers` lists it; the+ idle notice can name it; work.resume is not refused by a handed task.+- [ ] Test: holds: the handed task still holds, the new task adds one, neither ends; githubAssignment prefers the in-hand task.+- [ ] Code.++## Task 2: a handed task is never lost for its Engineer++**Files:** liveness.ts, handed.test.ts++- [ ] Test: a handed task stays `review` when its Engineer's session stops, its machine goes offline or it hits a limit.+- [ ] Code.++## Task 3: No, red CI or a conflict reopens the task pinned to its owner++**Files:** handed.ts, commands.ts, liveness.ts, store.ts (pullRequestSeen), pullRequestEvents.ts, handed.test.ts++- [ ] Test: a Reviewer's failed check on a handed task reopens it to the same assignment and agent, tells the Engineer, keeps+ the run ledger; the Engineer's own failed check does not.+- [ ] Test: the PR watch reopens on CI red at the head and on a conflict; a green run does not.+- [ ] Test: the Engineer's post or status picks it up; with no pick-up in 60 minutes it is lost (released); a down Engineer+ loses it at once; the next Ready clears `reopened`.+- [ ] Code.diff --git a/docs/plans/2026-11-05-pm-grid-roundtrip-plan.md b/docs/plans/2026-11-05-pm-grid-roundtrip-plan.mdnew file mode 100644index 000000000..027eea3ff--- /dev/null+++ b/docs/plans/2026-11-05-pm-grid-roundtrip-plan.md@@ -0,0 +1,60 @@+# A PM back from a grid model or a move keeps Opus at xhigh — plan++> Way of working: the project's Engineer role (docs/plans plan, then test-first per task, one PR, one review).++**Goal:** A session that kept its launch model (#3219: `RegisteredSession.launchModel`) keeps it after a round trip+through a grid model. On the move home, and on every relaunch after it, a PM launched on Opus at xhigh comes back on+Opus at xhigh, and a person's later Harness pick still wins.++**Architecture:** Two gaps, both found in the #3219 reviews:+1. `lib/launchOverrides.ts` prefers the model remembered when the session left for a grid (`subscriptionModel`, a+ model only, kept after the move home) over the launch model. After one round trip every relaunch loses the effort,+ and a later pick (`setLaunchModel`) loses too. Fix: the launch model outranks the remembered one wherever the engine+ takes launch flags. A launch model with no model of its own still gets the remembered model, and an engine with no+ launch flags still uses the remembered model.+2. `core/agents/retarget.ts` builds the move home's launch source from the grid, the Codex home and the remembered+ model only, so the move home itself drops the launch model. Fix: carry `session.launchModel` on a move home.++Plus a Desktop test that pins the Personal-project PM's own-machine start flags (`personal_lead.dart` `_launch`: Claude+gets `opus`/`xhigh`, Codex none). That code already works, but nothing tested it.++**Tech Stack:** CLI TypeScript (vitest), Desktop Flutter (widget/unit test, memory store, fake sign-in).++**Spec:** task #3449 brief.++## Global Constraints++- Swarm code stays out of `cli/src/core`: `retarget.ts` only carries a generic launch fact.+- No `/model` is typed; flags only. A grid launch never gets launch-model flags.+- The `core/agents` 100% coverage gate (`npm run test:core`) holds.++## Review Focus++- No duplicate model flags (`ANTHROPIC_MODEL` env and `--model`) on one launch.+- An engine without launch flags (Codex) behaves exactly as before.++## Task 1: the launch model outranks the remembered model++**Files:** `cli/src/lib/launchOverrides.ts`, `cli/src/lib/launchOverrides.spec.ts`++- [ ] Failing test: Claude with `subscriptionModel: 'opus'` and `launchModel: opus/xhigh` relaunches with+ `--model opus --effort xhigh` and no `ANTHROPIC_MODEL`; with `launchModel: sonnet/high` (a later pick) it gets+ sonnet. With `launchModel: { model: null, effort: 'xhigh' }` it gets the remembered model and `--effort xhigh`.+ Codex with both keeps its remembered `-m`.+- [ ] Code.++## Task 2: the move home carries the launch model++**Files:** `cli/src/core/agents/retarget.ts`, `cli/src/core/agents/retarget.spec.ts`++- [ ] Failing test: moving a session with `launchModel` home from a grid asks `relaunchOverrides` with a source+ carrying that launch model. A move onto a grid does not.+- [ ] Code.++## Task 3: Desktop pins the Personal PM's launch flags++**Files:** `desktop/test/super_tab_personal_lead_test.dart`++- [ ] Test: a Personal project's first-message start of a Claude Lead asks the machine to create it with+ `model: opus`, `effort: xhigh`; a Codex Lead with neither. It guards existing behaviour, so it is checked+ against a deliberately broken `kLeadModel` to show it fails then.diff --git a/docs/plans/2026-11-05-project-rules-record-plan.md b/docs/plans/2026-11-05-project-rules-record-plan.mdnew file mode 100644index 000000000..cf3153109--- /dev/null+++ b/docs/plans/2026-11-05-project-rules-record-plan.md@@ -0,0 +1,153 @@+# Project rules record Implementation Plan++> **For agentic workers:** this plan is implemented the project's way (project instructions, Engineer): task by task, test+> first, each failing test committed before the code that passes it. No per-task review: the pull request's review step is the+> one independent review.++**Goal:** A project's numbers (release window, release pace, review table, merge train switch, caps, paths, crew, lanes) live+in one schema-checked, versioned record that people (or the project's PM, quoting the person's chat message) change without a+release; every change keeps who, when, the diff and the asking message; Desktop shows it read-only in Project settings.++**Architecture:** A new backend module `superTabs/policy.ts` owns the record's schema, its seed (today's numbers) and its diff.+Each saved revision is one row of a new collection `SuperTabProjectRules` (the document-versioning pattern in one collection:+the newest row is the record, older rows are its history, at most 50 kept). A new command `rules.set` validates, checks the+base revision and who may write, and hands the store one row to create; its `_id` is `stableId(tab, project, revision)`, so two+writers of the same revision collide on the key and one retries into `RULES_STALE`. A new read `GET+/api/super-tabs/:tabId/projects/:projectId/rules` returns the record and its history. Nothing of it enters the state, the+instructions read or any prompt.++**Tech Stack:** TypeScript, zod, Prisma on MongoDB, Fastify (backend); Flutter/Dart (Desktop).++**Spec:** Task #3393's brief (conversation 51b20f862c3b47eb530b1e44); anh Dee's Swarm redesign approval, 2026-11-05.++## Global Constraints++- PR body first line: "Requested by Dee through Harness."+- Owns `backend/src/superTabs/` and `desktop/lib/super_tabs/`; outside them only what wiring needs: `backend/prisma/schema.prisma`+ (the collection), `backend/src/routes/superTabs.ts` (the read route), `backend/src/lib/teamSession.ts` (a Team-account PM+ reads the base revision), each with its test.+- Who may edit: a person who may write the project; the project's own PM only with `askedIn` quoting a person's own chat+ message (not a notice) in a conversation of this project, from the last 24 h (`RULE_MESSAGE_MS`), by a member who still+ reads the project. No other agent, no Buddy, no viewer.+- New refusals get new names: `RULES_EDITOR_REQUIRED`, `RULES_ASKED_IN_REQUIRED`, `RULES_STALE`, `RULES_UNAVAILABLE`. None+ of `removedRefusals.test.ts`'s codes is used; that test stays green. Each refusal's message names the next step.+- The record is at most 16 KB of JSON; unknown keys are refused (strict schema); lists at most 50 entries.+- Seed (revision 0, never stored until a first save): release window 09:00–18:00 Asia/Ho_Chi_Minh; backend at most every+ 120 minutes and never 09:00–10:00 (`backendPause`, Shipper #3405), Desktop/CLI/web after each visible batch; reviews: 1 read+ by default, 2 for sign-in, tokens, crypto, access, Buddy guard, device links, deletion, each with its path globs, test rows by+ where a change runs and the paths that need no test (the review steps' table, #3401 reviewTable.ts); merge train off, every+ 10 minutes (opt-in per project, River via #3402); caps, paths, crew and lanes empty. The record is at most 16 KB.+- For server workers: `currentRules(tx, tabId, projectId)` (policyStore.ts), `requiredReads(rules, files)`,+ `testsFor(rules, files)`, `globMatch` (policy.ts); unreadable files (null) fail closed.+- Desktop tests use a memory store and a fake sign-in; never the real CLI sign-in.++## Design++- Growth: a save that writes revision N deletes revisions ≤ N − 50 of its project; `project.delete` deletes the project's+ rows; Swarm purge lists the collection (`purge.ts`).+- Concurrency: per project and revision: the new row's `_id` is unique, so of two saves on one base one retries (retry.ts+ takes a taken key) and is refused `RULES_STALE` with the current record to merge. The PM check touches the project's Lead+ conversation part, as `instructions.save` does.+- Read cost: one indexed read `(tabId, projectId, revision desc)`, at most 50 rows of ≤ 8 KB plus diff.+- Scale: 10x projects is 10x rows of one small collection; the first warning is the read route's latency.+- Compatibility: older clients never send `rules.set` and never read `/rules`; an older backend answers Desktop's read with a+ 404 without the backend's code, which Desktop shows as "not available on this server".+- Migration + rollback: none; a project with no row reads the seed. Rolling back leaves rows unread.+- Audience: the server checks it: readers of the project read the record; a Buddy reads nothing (the history names who+ asked); writes as above.+- Identity: `writtenBy` is the person's or the PM's id, `askedBy` the person whose words it carries; never the machine owner.+- Failure: a refused save says why and what to do; a missing route or read failure is shown in the dialog.+- Platforms: Desktop's view is plain Flutter widgets, the same on macOS, Windows, Linux and web (route allowed in+ `backend_transport.dart`).++## Review Focus++- A PM quoting an agent's message, a notice, another project's chat, a day-old message, or a person who lost the project:+ refused `RULES_ASKED_IN_REQUIRED` (Task 2 test).+- Two saves on the same base revision: the second refused with the current record (Task 2 command test; Task 3 store key).+- A record with an unknown key, a window that ends before it starts, an unknown time zone, a negative pace, a list over 50:+ refused at parse, nothing stored (Task 1 test).+- Saving the same record again: no new revision (Task 2 test).+- A Buddy reading or writing the rules: refused (Task 2 and Task 3 tests).++---++### Task 1: The record, its seed and its diff++**Files:**+- Create: `backend/src/superTabs/policy.ts`+- Test: `backend/src/superTabs/policy.test.ts`++**Interfaces:**+- Produces: `projectRulesSchema` (zod, strict), `type ProjectRules`, `SEED_RULES: ProjectRules`, `MAX_RULES_BYTES = 8192`,+ `MAX_RULES_REVISIONS = 50`, `rulesDiff(before: ProjectRules, after: ProjectRules): RulesChange[]` where+ `RulesChange = { path: string; before: unknown; after: unknown }` (leaf paths for objects, whole value for lists),+ `rulesEqual(a, b): boolean`.++- [ ] Step 1: failing tests: the seed parses and holds the numbers above; bad values are refused (unknown key, `25:00`,+ end ≤ start, zone `Mars/Base`, pace 0, reads 0, 51 caps, over 8 KB); `rulesDiff` lists `releaseWindow.start` and `reviews.rows`+ changes and nothing for an equal record.+- [ ] Step 2: run `npm test -- src/superTabs/policy.test.ts`: fails (module missing). Commit.+- [ ] Step 3: implement `policy.ts`.+- [ ] Step 4: run it: passes. Commit.++### Task 2: `rules.set`++**Files:**+- Modify: `backend/src/superTabs/commands.ts` (schema, context, case), `backend/src/superTabs/model.ts` (`CommandEffects.projectRules`),+ `backend/src/superTabs/parts/touches.ts`+- Test: `backend/src/superTabs/policy.test.ts`++**Interfaces:**+- Command: `{ type: 'rules.set', projectId, baseRevision: int ≥ 0, rules: ProjectRules, summary: summarySchema, askedIn? }`.+- Context: `projectRules?: { revision: number; rules: ProjectRules } | null` (null: none saved, the seed at revision 0);+ `askedIn` loaded as for `rule.set`.+- Effect: `projectRules: RulesWrite = { projectId, revision, rules, diff, summary, writtenBy: { kind, id }, askedBy, askedIn | null, at }`.+- Result: `{ projectId, revision }`, or `{ projectId, revision, unchanged: true }`.++- [ ] Step 1: failing tests: a person saves revision 1 from the seed with who/when/diff/summary; a stale base is refused+ `RULES_STALE` with the current record; the same record saves nothing; the PM saves only with a person's own message of this+ project from the last day (each wrong `askedIn` refused `RULES_ASKED_IN_REQUIRED`) and records `askedBy` and `askedIn`;+ another agent and a Buddy are refused; a viewer is refused.+- [ ] Step 2: run: fails. Commit.+- [ ] Step 3: implement.+- [ ] Step 4: run with `src/superTabs/removedRefusals.test.ts` and `parts` tests: pass. Commit.++### Task 3: Store, collection and read API++**Files:**+- Modify: `backend/prisma/schema.prisma` (`SuperTabProjectRules`), `backend/src/superTabs/store.ts` (context load, write,+ delete with the project, `projectRules` read), `backend/src/superTabs/purge.ts`, `backend/src/routes/superTabs.ts`,+ `backend/src/lib/teamSession.ts`+- Create: `backend/src/superTabs/policyStore.ts`+- Test: `backend/src/superTabs/policyStore.test.ts`, `backend/src/lib/teamSession.test.ts`++**Interfaces:**+- `readRules(tx, tabId, projectId): Promise<{ revision; rules } | null>`, `writeRules(tx, tabId, write: RulesWrite)` (create, then+ delete ≤ revision − 50), `deleteRules(tx, tabId, projectId)`.+- `store.projectRules(user, tabId, projectId, asAgentId?)` → `{ projectId, revision, rules, seeded, history: [{ revision, summary,+ diff, writtenBy, askedBy, askedIn, at }] }` newest first.+- `GET /api/super-tabs/:tabId/projects/:projectId/rules` (team session: agent scope).++- [ ] Step 1: failing tests: write/read keeps 50 newest; a second create of one revision throws a taken key; the team session+ route reaches `projectRules`.+- [ ] Step 2: run: fails. Commit.+- [ ] Step 3: implement; `npx prisma generate`.+- [ ] Step 4: run: passes; `npm test` (backend unit suite) passes. Commit.++### Task 4: Desktop read-only view++**Files:**+- Create: `desktop/lib/super_tabs/project_rules.dart` (model + dialog)+- Modify: `desktop/lib/super_tabs/view.dart` (Project settings row "Project rules"), `desktop/lib/super_tabs/backend_transport.dart`+- Test: `desktop/test/super_tabs/project_rules_test.dart`, `desktop/test/super_tab_backend_transport_test.dart`++**Interfaces:**+- `SuperTabProjectRules.fromJson`, `superTabRulesPath(tabId, projectId)`, `showSuperTabProjectRules(context, c, projectId)`.++- [ ] Step 1: failing tests: the model reads the seed answer; the dialog shows release window, pace, review table, merge train+ and the history line (who, when, summary, changed fields) in light and dark; a 404 without a code shows "not available";+ the web transport allows `/rules`.+- [ ] Step 2: run: fails. Commit.+- [ ] Step 3: implement.+- [ ] Step 4: run the new tests, `check-ui-style` and `laid_out_list_test`: pass. Commit.diff --git a/docs/plans/2026-11-05-release-window-plan.md b/docs/plans/2026-11-05-release-window-plan.mdnew file mode 100644index 000000000..f49c71002--- /dev/null+++ b/docs/plans/2026-11-05-release-window-plan.md@@ -0,0 +1,54 @@+# Release window guard Implementation Plan++**Goal:** A release outside 09:00-18:00 Asia/Ho_Chi_Minh, or a backend release within 2 hours of the last one, is+refused with the next allowed time. A P0 may release at night with `--urgent "<reason>"`; the reason is recorded and+printed as the one line the releaser posts in the project chat (Dee, 2026-11-05).++**Architecture:** One script, `scripts/release-window.py`, reads its numbers from `scripts/release-window.json`+(zone, window, pace per kind). The four release scripts (backend, CLI, Desktop, web) call it before they tag. The+tag-triggered workflows call it again as their first step, because a hand-pushed tag skips the scripts. An urgent+release writes `Release-Urgent: <reason>` into its tag message, so the workflow can honor the same override and the+reason stays on the tag.++**Tech Stack:** Python 3 stdlib (`zoneinfo`, `unittest`), bash, GitHub Actions YAML.++**Spec:** the task's brief (#3388). Guard name: `RELEASE_WINDOW` (new; not one of the codes #2414 removed).++## Global Constraints++- Refusal names the next allowed time and the next step (`--urgent "<reason>"` for a P0).+- No new refusal for a workflow choice: the guard is the window and the pace, nothing else.+- `--prepare` (Desktop candidate) and `--dry-run` publish nothing, so they are not refused; a dry run reports the verdict.+- Tests never touch the real clock or the real tags: `--now` and a temp git repo.+- Temp files only under `mktemp -d`.++## Review Focus++- A refusal exits non-zero before any tag is created, in all four scripts.+- The workflow check cannot count the tag it is building as "the last release".+- Urgent without a reason is refused; with a reason it is recorded on the tag and printed.++## Tasks++### Task 1: the guard++**Files:** `scripts/release-window.py`, `scripts/release-window.json`, `scripts/tests/test_release_window.py`++**Interfaces:** `check(kind, now, last, config, urgent) -> Verdict`; CLI+`release-window.py --kind K [--now ISO] [--urgent REASON] [--tag TAG] [--repo DIR] [--exclude-tag TAG] [--from-tag TAG] [--advisory]`.+Exit 0 allowed, 2 refused (`RELEASE_WINDOW ...`).++- [ ] Failing tests: inside window allowed; before 09:00, at 18:00 and after refused with next 09:00; backend within 2 h refused with last+2h; pace landing after 18:00 moves to next 09:00; CLI/Desktop/web have no pace; urgent needs a non-blank reason; urgent prints the chat line; zone has no DST shift.+- [ ] Implement.++### Task 2: last release from git, tag override++- [ ] Failing tests (temp git repo): last backend tag time is read; `--exclude-tag` skips the tag being built; `Release-Urgent:` in the tag message is honored with `--from-tag`.+- [ ] Implement.++### Task 3: wire the scripts and workflows++**Files:** `backend/scripts/release-be.sh`, `cli/scripts/release-cli.sh`, `desktop/scripts/release-desktop.sh`, `desktop/scripts/release-web.sh`, `.github/workflows/{production-be-build.yaml,release.yml,release-desktop.yml,release-web.yml}`++- [ ] Failing test: each script and workflow calls the guard before it tags/builds, and a refused guard stops the script (run the script's guard step against a fake `--now`).+- [ ] Implement.diff --git a/scripts/release-window.json b/scripts/release-window.jsonnew file mode 100644index 000000000..46dcdc0f7--- /dev/null+++ b/scripts/release-window.json@@ -0,0 +1,6 @@+{+ "releaseWindow": {"start": "09:00", "end": "18:00", "timeZone": "Asia/Ho_Chi_Minh"},+ "releasePace": {"backendEveryMinutes": 120, "backendPause": {"start": "09:00", "end": "10:00"}},+ "tagGraceMinutes": 30,+ "kinds": ["backend", "cli", "desktop", "web"]+}diff --git a/scripts/release-window.py b/scripts/release-window.pynew file mode 100755index 000000000..a09131d86--- /dev/null+++ b/scripts/release-window.py@@ -0,0 +1,188 @@+#!/usr/bin/env python3+"""RELEASE_WINDOW: refuse a release outside the release window or too soon after the last one.++The numbers are in release-window.json beside this file, in the shape of the project rules record's releaseWindow and+releasePace (window start/end/zone, backend pace in minutes, and the backend's pause inside the window: no backend+release 09:00-10:00 VN, Ken 2026-11-05).++ release-window.py --kind backend # the release scripts, before they tag+ release-window.py --kind backend --urgent "P0: ..." # a P0 at night; prints the line to post in the chat+ release-window.py --kind backend --from-tag TAG --exclude-tag TAG # a tag-triggered workflow++Exit 0: allowed. Exit 2: refused, with the next allowed time on stderr. An urgent release is recorded on its+tag as a `Release-Urgent: <reason>` line, which --from-tag reads, so the workflow honors the same override and+a tag pushed by hand without one is refused.+"""+import argparse+import json+import os+import re+import subprocess+import sys+from collections import namedtuple+from datetime import datetime, time, timedelta, timezone+from pathlib import Path+from zoneinfo import ZoneInfo++CONFIG_PATH = Path(__file__).resolve().parent / "release-window.json"+URGENT_LINE = re.compile(r"^Release-Urgent: (.+)$", re.MULTILINE)++Verdict = namedtuple("Verdict", "allowed next_allowed message urgent_reason chat_line")+++def _clock(text):+ hour, minute = text.split(":")+ return time(int(hour), int(minute))+++def _stamp(moment, zone):+ return moment.astimezone(zone).strftime("%Y-%m-%d %H:%M")+++def _next_opening(moment, start, end):+ """The first instant at or after `moment` (local, aware) that is inside [start, end)."""+ day = moment.date()+ if moment.time() < start:+ return datetime.combine(day, start, tzinfo=moment.tzinfo)+ if moment.time() >= end:+ return datetime.combine(day + timedelta(days=1), start, tzinfo=moment.tzinfo)+ return moment+++def check(kind, now, last, config, urgent=None):+ """Decide whether `kind` may be released at `now`, given the time of the last release of that kind."""+ if now.tzinfo is None:+ raise ValueError("now must carry a time zone")+ if kind not in config["kinds"]:+ raise ValueError(f"unknown release kind {kind!r}; expected one of {', '.join(config['kinds'])}")+ window, pace = config["releaseWindow"], config.get("releasePace", {})+ zone = ZoneInfo(window["timeZone"])+ start, end = _clock(window["start"]), _clock(window["end"])+ local_now = now.astimezone(zone)+ shown = f"{window['start']}-{window['end']}"++ pause = pace.get("backendPause") if kind == "backend" else None+ pause_start, pause_end = (_clock(pause["start"]), _clock(pause["end"])) if pause else (None, None)+ minutes = pace.get("backendEveryMinutes") if kind == "backend" else None++ def in_pause(moment):+ return pause is not None and pause_start <= moment.time() < pause_end++ earliest = local_now+ reasons = []+ if minutes and last is not None:+ paced = last.astimezone(zone) + timedelta(minutes=minutes)+ if paced > earliest:+ earliest = paced+ reasons.append(f"the last {kind} release was at {_stamp(last, zone)} and {kind} releases keep {minutes} minutes apart, "+ f"until {_stamp(paced, zone)}")+ if not (start <= local_now.time() < end):+ reasons.insert(0, f"it is outside {shown}")+ elif in_pause(local_now):+ reasons.insert(0, f"backend releases pause {pause['start']}-{pause['end']}")+ # Settle on the first instant that is in the window and out of the pause (moving one can land in the other).+ allowed_at = earliest+ while True:+ moved = _next_opening(allowed_at, start, end)+ if in_pause(moved):+ moved = datetime.combine(moved.date(), pause_end, tzinfo=moved.tzinfo)+ if moved == allowed_at:+ break+ allowed_at = moved+ allowed = allowed_at == local_now++ if urgent is not None:+ reason = " ".join(urgent.split())+ if not reason:+ return Verdict(False, allowed_at, f'RELEASE_WINDOW: --urgent needs a reason: --urgent "<reason>" (a P0 only).',+ None, None)+ line = f"Urgent {kind} release at {_stamp(now, zone)} VN: {reason}"+ return Verdict(True, local_now, f"urgent: {reason}", reason, line)++ if allowed:+ return Verdict(True, local_now, "ok", None, None)+ message = (+ f"RELEASE_WINDOW: a {kind} release is refused at {_stamp(now, zone)} {window['timeZone']}: "+ f"{'; '.join(reasons)}. Next allowed: {_stamp(allowed_at, zone)} {window['timeZone']}. "+ f'A P0 releases now with --urgent "<reason>".'+ )+ return Verdict(False, allowed_at, message, None, None)+++def _git(repo, *args):+ return subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True, text=True).stdout+++def last_release_time(repo, kind, exclude_tag=None):+ """When the newest `vX.Y.Z_<kind>` tag was made, or None when there is none."""+ pattern = re.compile(rf"^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)_{kind}$")+ out = _git(repo, "for-each-ref", "--format=%(refname:short) %(creatordate:unix)", f"refs/tags/v*_{kind}")+ newest = None+ for row in out.splitlines():+ name, _, stamp = row.partition(" ")+ if name == exclude_tag or not pattern.match(name) or not stamp:+ continue+ moment = datetime.fromtimestamp(int(stamp), tz=timezone.utc)+ if newest is None or moment > newest:+ newest = moment+ return newest+++def tagged_at(repo, tag):+ """When an annotated tag was made, or None for a lightweight tag (its date is the commit's, which anyone can set)."""+ stamp = _git(repo, "tag", "-l", "--format=%(taggerdate:unix)", tag).strip()+ return datetime.fromtimestamp(int(stamp), tz=timezone.utc) if stamp else None+++def urgent_reason_of_tag(repo, tag):+ body = _git(repo, "tag", "-l", "--format=%(contents)", tag)+ found = URGENT_LINE.search(body)+ return found.group(1).strip() if found else None+++def main(argv=None):+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--kind", required=True)+ parser.add_argument("--now", help="ISO time with a zone (tests); default: the clock")+ parser.add_argument("--urgent", help="a P0's reason for releasing outside the window or pace")+ parser.add_argument("--repo", default=".")+ parser.add_argument("--exclude-tag", help="a tag that is the release being built, not the last one")+ parser.add_argument("--from-tag", help="read a Release-Urgent line from this tag's message")+ parser.add_argument("--advisory", action="store_true", help="report a refusal but exit 0 (dry runs)")+ parser.add_argument("--config", default=str(CONFIG_PATH))+ args = parser.parse_args(argv)++ config = json.loads(Path(args.config).read_text())+ now = datetime.fromisoformat(args.now) if args.now else datetime.now(timezone.utc)+ urgent = args.urgent+ if urgent is None and args.from_tag:+ urgent = urgent_reason_of_tag(args.repo, args.from_tag)+ if args.from_tag:+ # A workflow that waited in the CI queue starts after the release was made. A tag made a moment ago is judged+ # when it was made, so a release tagged at 17:55 is not refused at 18:04; an older tag is judged by the clock.+ made = tagged_at(args.repo, args.from_tag)+ if made is not None and timedelta(0) <= now - made <= timedelta(minutes=config.get("tagGraceMinutes", 0)):+ now = made+ last = None+ if args.kind == "backend" and config.get("releasePace", {}).get("backendEveryMinutes"):+ last = last_release_time(args.repo, args.kind, args.exclude_tag)++ try:+ verdict = check(args.kind, now, last, config, urgent)+ except ValueError as error:+ print(f"RELEASE_WINDOW: {error}", file=sys.stderr)+ return 2+ if verdict.chat_line:+ print(verdict.chat_line)+ summary = os.environ.get("GITHUB_STEP_SUMMARY")+ if summary:+ with open(summary, "a") as handle:+ handle.write(verdict.chat_line + "\n")+ if not verdict.allowed:+ print(verdict.message, file=sys.stderr)+ return 0 if args.advisory else 2+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/release-window.sh b/scripts/release-window.shnew file mode 100644index 000000000..4d65d34fa--- /dev/null+++ b/scripts/release-window.sh@@ -0,0 +1,22 @@+# Sourced by the release scripts (backend, CLI, Desktop, web). Bash 3.2-compatible.+#+# release_window_guard KIND runs scripts/release-window.py first, so a release outside the window or too+# soon after the last one is refused before anything is tagged. A script sets URGENT_SET=1 and URGENT="<reason>"+# when its caller passed --urgent, and DRY_RUN=1 for a dry run (which only reports the verdict).+# On success URGENT_TAG_LINE holds the `Release-Urgent: <reason>` line the script puts in its tag's message, so the+# tag workflow honors the same override and the reason stays with the release.+URGENT_SET="${URGENT_SET:-0}"+URGENT="${URGENT:-}"+URGENT_TAG_LINE=""++release_window_guard() {+ local kind="$1" guard args+ guard="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/release-window.py"+ args=(--kind "$kind")+ if [ "$URGENT_SET" -eq 1 ]; then args+=(--urgent "$URGENT"); fi+ if [ "${DRY_RUN:-0}" -eq 1 ]; then args+=(--advisory); fi+ python3 "$guard" "${args[@]}" || return $?+ if [ "$URGENT_SET" -eq 1 ] && [ "${DRY_RUN:-0}" -ne 1 ]; then+ URGENT_TAG_LINE="Release-Urgent: $(printf '%s' "$URGENT" | tr -s '[:space:]' ' ' | sed -e 's/^ //' -e 's/ $//')"+ fi+}diff --git a/scripts/tests/test_desktop_release_prepare.py b/scripts/tests/test_desktop_release_prepare.pyindex 7d110cc94..d087aff36 100644--- a/scripts/tests/test_desktop_release_prepare.py+++ b/scripts/tests/test_desktop_release_prepare.py@@ -29,6 +29,10 @@ class DesktopPrepareTests(unittest.TestCase):source = self.repo / 'desktop/scripts'source.mkdir(parents=True)shutil.copyfile(ROOT / 'desktop/scripts/release-desktop.sh', source / 'release-desktop.sh')+ (self.repo / 'scripts').mkdir()+ # These tests are about other refusals, so the release window must not depend on the clock they run at.+ shutil.copyfile(ROOT / 'scripts/release-window.sh', self.repo / 'scripts/release-window.sh')+ (self.repo / 'scripts/release-window.py').write_text('import sys\nsys.exit(0)\n')self.git('add', '.')self.git('commit', '-qm', 'previous version')self.git('tag', '-a', 'v1.2.54_desktop', '-m', 'previous release')diff --git a/scripts/tests/test_release_contains_last.py b/scripts/tests/test_release_contains_last.pyindex 46e9281bf..979fc2d2a 100644--- a/scripts/tests/test_release_contains_last.py+++ b/scripts/tests/test_release_contains_last.py@@ -42,6 +42,10 @@ class ReleaseContainsLastTests(unittest.TestCase):target = self.repo / scripttarget.parent.mkdir(parents=True, exist_ok=True)shutil.copyfile(ROOT / script, target)+ (self.repo / 'scripts').mkdir()+ # These tests are about other refusals, so the release window must not depend on the clock they run at.+ shutil.copyfile(ROOT / 'scripts/release-window.sh', self.repo / 'scripts/release-window.sh')+ (self.repo / 'scripts/release-window.py').write_text('import sys\nsys.exit(0)\n')self.git('add', '.')self.git('commit', '-qm', 'older')self.older = self.git('rev-parse', 'HEAD')diff --git a/scripts/tests/test_release_window.py b/scripts/tests/test_release_window.pynew file mode 100644index 000000000..b6ba8d665--- /dev/null+++ b/scripts/tests/test_release_window.py@@ -0,0 +1,298 @@+import importlib.util+import io+import json+import os+import subprocess+import tempfile+import unittest+from contextlib import redirect_stderr, redirect_stdout+from datetime import datetime, timedelta, timezone+from pathlib import Path++SCRIPTS = Path(__file__).resolve().parents[1]+ROOT = SCRIPTS.parent+spec = importlib.util.spec_from_file_location("release_window", SCRIPTS / "release-window.py")+rw = importlib.util.module_from_spec(spec)+spec.loader.exec_module(rw)++VN = timezone(timedelta(hours=7))+CONFIG = json.loads((SCRIPTS / "release-window.json").read_text())+++def at(day, hour, minute=0):+ """A VN wall-clock time on 2026-11-<day>, as an aware datetime in UTC (what git and CI report)."""+ return datetime(2026, 11, day, hour, minute, tzinfo=VN).astimezone(timezone.utc)+++def check(kind, now, last=None, urgent=None):+ return rw.check(kind, now, last, CONFIG, urgent)+++class WindowTests(unittest.TestCase):+ def test_config_holds_the_numbers_in_the_shape_of_the_rules_record(self):+ # The project rules record (#3216) keeps releaseWindow and releasePace in this shape; the guard reads it+ # from there once that lands, so these keys are named the same.+ self.assertEqual(CONFIG["releaseWindow"], {"start": "09:00", "end": "18:00", "timeZone": "Asia/Ho_Chi_Minh"})+ self.assertEqual(CONFIG["releasePace"], {"backendEveryMinutes": 120, "backendPause": {"start": "09:00", "end": "10:00"}})++ def test_grace_for_a_queued_workflow_is_data(self):+ self.assertEqual(CONFIG["tagGraceMinutes"], 30)++ def test_inside_the_window_is_allowed_for_every_kind(self):+ for kind in ["cli", "desktop", "web"]:+ for hour, minute in [(9, 0), (12, 30), (17, 59)]:+ self.assertTrue(check(kind, at(5, hour, minute)).allowed, (kind, hour, minute))+ for hour, minute in [(10, 0), (12, 30), (17, 59)]:+ self.assertTrue(check("backend", at(5, hour, minute)).allowed, (hour, minute))++ def test_before_the_window_is_refused_with_todays_opening(self):+ verdict = check("cli", at(5, 8, 59))+ self.assertFalse(verdict.allowed)+ self.assertEqual(verdict.next_allowed, at(5, 9, 0))++ def test_at_closing_time_and_after_is_refused_with_tomorrows_opening(self):+ for hour, minute in [(18, 0), (18, 1), (23, 30)]:+ verdict = check("desktop", at(5, hour, minute))+ self.assertFalse(verdict.allowed, (hour, minute))+ self.assertEqual(verdict.next_allowed, at(6, 9, 0))++ def test_after_midnight_before_nine_opens_the_same_day(self):+ verdict = check("web", at(6, 0, 30))+ self.assertEqual(verdict.next_allowed, at(6, 9, 0))++ def test_window_is_read_in_vietnam_time_not_utc(self):+ # 02:30 UTC is 09:30 in Ho Chi Minh City: inside. 11:30 UTC is 18:30 there: outside.+ self.assertTrue(check("cli", datetime(2026, 11, 5, 2, 30, tzinfo=timezone.utc)).allowed)+ self.assertFalse(check("cli", datetime(2026, 11, 5, 11, 30, tzinfo=timezone.utc)).allowed)++ def test_vietnam_has_no_daylight_shift(self):+ # The US fall-back (2026-11-01) and spring-forward (2026-03-08) move nothing here.+ for month, day in [(3, 7), (3, 9), (10, 31), (11, 2)]:+ inside = datetime(2026, month, day, 9, 0, tzinfo=VN).astimezone(timezone.utc)+ self.assertTrue(check("cli", inside).allowed, (month, day))+ outside = datetime(2026, month, day, 18, 0, tzinfo=VN).astimezone(timezone.utc)+ self.assertFalse(check("cli", outside).allowed, (month, day))++ def test_naive_time_is_rejected(self):+ with self.assertRaises(ValueError):+ check("cli", datetime(2026, 11, 5, 12, 0))+++class BackendPauseTests(unittest.TestCase):+ """Ken, 2026-11-05: no backend release inside 09:00-10:00 VN (the morning peak); apps keep 09:00."""++ def test_backend_is_refused_inside_the_pause_with_the_pause_end(self):+ for hour, minute in [(9, 0), (9, 30), (9, 59)]:+ verdict = check("backend", at(5, hour, minute))+ self.assertFalse(verdict.allowed, (hour, minute))+ self.assertEqual(verdict.next_allowed, at(5, 10, 0))+ self.assertIn("09:00-10:00", verdict.message)++ def test_backend_opens_at_ten(self):+ self.assertTrue(check("backend", at(5, 10, 0)).allowed)++ def test_apps_and_web_are_not_paused(self):+ for kind in ["cli", "desktop", "web"]:+ self.assertTrue(check(kind, at(5, 9, 30)).allowed, kind)++ def test_before_nine_a_backend_release_waits_for_ten(self):+ self.assertEqual(check("backend", at(5, 8, 0)).next_allowed, at(5, 10, 0))++ def test_pace_ending_inside_the_pause_waits_for_its_end(self):+ # Last release 07:30 would allow 09:30, which is paused: the next time is 10:00.+ verdict = check("backend", at(5, 9, 20), last=at(5, 7, 30))+ self.assertEqual(verdict.next_allowed, at(5, 10, 0))++ def test_a_null_pause_turns_it_off(self):+ config = {**CONFIG, "releasePace": {**CONFIG["releasePace"], "backendPause": None}}+ self.assertTrue(rw.check("backend", at(5, 9, 30), None, config, None).allowed)++ def test_urgent_overrides_the_pause(self):+ self.assertTrue(check("backend", at(5, 9, 30), urgent="P0: crash loop").allowed)+++class PaceTests(unittest.TestCase):+ def test_backend_within_two_hours_is_refused_with_the_time_it_opens(self):+ verdict = check("backend", at(5, 12, 0), last=at(5, 10, 30))+ self.assertFalse(verdict.allowed)+ self.assertEqual(verdict.next_allowed, at(5, 12, 30))++ def test_backend_after_two_hours_is_allowed(self):+ self.assertTrue(check("backend", at(5, 12, 30), last=at(5, 10, 30)).allowed)+ self.assertTrue(check("backend", at(5, 15, 0), last=at(5, 10, 30)).allowed)++ def test_pace_that_ends_after_closing_moves_to_the_next_backend_opening(self):+ verdict = check("backend", at(5, 17, 30), last=at(5, 17, 0))+ self.assertFalse(verdict.allowed)+ self.assertEqual(verdict.next_allowed, at(6, 10, 0))++ def test_night_and_pace_together_name_the_later_time(self):+ verdict = check("backend", at(5, 23, 0), last=at(5, 22, 0))+ self.assertEqual(verdict.next_allowed, at(6, 10, 0))++ def test_other_kinds_have_no_pace(self):+ for kind in ["cli", "desktop", "web"]:+ self.assertTrue(check(kind, at(5, 12, 0), last=at(5, 11, 55)).allowed, kind)++ def test_first_ever_backend_release_has_no_pace(self):+ self.assertTrue(check("backend", at(5, 12, 0), last=None).allowed)++ def test_unknown_kind_is_an_error_not_a_pass(self):+ with self.assertRaises(ValueError):+ check("firmware", at(5, 12, 0))++ def test_pace_past_closing_names_the_last_release(self):+ text = check("backend", at(5, 17, 30), last=at(5, 17, 0)).message+ self.assertIn("the last backend release was at 2026-11-05 17:00", text)+ self.assertNotIn("the pace ends outside", text)++ def test_message_names_guard_next_time_and_next_step(self):+ text = check("backend", at(5, 12, 0), last=at(5, 11, 0)).message+ self.assertIn("RELEASE_WINDOW", text)+ self.assertIn("2026-11-05 13:00", text)+ self.assertIn("Asia/Ho_Chi_Minh", text)+ self.assertIn('--urgent "<reason>"', text)+++class UrgentTests(unittest.TestCase):+ def test_urgent_without_a_reason_is_refused(self):+ for reason in ["", " ", None]:+ verdict = check("backend", at(5, 23, 0), urgent="" if reason is None else reason)+ self.assertFalse(verdict.allowed, repr(reason))+ self.assertIn("needs a reason", verdict.message)++ def test_urgent_with_a_reason_allows_night_and_pace(self):+ verdict = check("backend", at(5, 23, 0), last=at(5, 22, 30), urgent="P0: sign-out loop")+ self.assertTrue(verdict.allowed)+ self.assertEqual(verdict.urgent_reason, "P0: sign-out loop")+ self.assertIn("P0: sign-out loop", verdict.chat_line)+ self.assertIn("2026-11-05 23:00", verdict.chat_line)+ self.assertIn("backend", verdict.chat_line)++ def test_urgent_inside_the_window_is_still_recorded(self):+ verdict = check("cli", at(5, 12, 0), urgent="P0: crash on start")+ self.assertTrue(verdict.allowed)+ self.assertEqual(verdict.urgent_reason, "P0: crash on start")++ def test_reason_is_one_line(self):+ verdict = check("cli", at(5, 23, 0), urgent="P0: first\nsecond")+ self.assertNotIn("\n", verdict.chat_line)+++def git(repo, *args, env=None):+ subprocess.run(["git", "-C", repo, *args], check=True, capture_output=True,+ env={**os.environ, "GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@t", "GIT_COMMITTER_NAME": "t",+ "GIT_COMMITTER_EMAIL": "t@t", **(env or {})})+++class GitAndCliTests(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.repo = self.tmp.name+ git(self.repo, "init", "-q")+ git(self.repo, "commit", "-q", "--allow-empty", "-m", "c")++ def tag(self, name, when, message="release"):+ stamp = when.isoformat()+ git(self.repo, "tag", "-a", name, "-m", message, env={"GIT_COMMITTER_DATE": stamp})++ def run_cli(self, *args):+ out, err = io.StringIO(), io.StringIO()+ with redirect_stdout(out), redirect_stderr(err):+ code = rw.main(["--repo", self.repo, *args])+ return code, out.getvalue(), err.getvalue()++ def test_last_release_is_the_newest_tag_of_the_kind(self):+ self.tag("v1.0.1_backend", at(5, 9, 0))+ self.tag("v1.0.2_backend", at(5, 10, 30))+ self.tag("v9.0.1_cli", at(5, 11, 55))+ self.assertEqual(rw.last_release_time(self.repo, "backend"), at(5, 10, 30))++ def test_no_tag_means_no_last_release(self):+ self.assertIsNone(rw.last_release_time(self.repo, "backend"))++ def test_cli_refuses_a_backend_release_within_two_hours_with_exit_2(self):+ self.tag("v1.0.1_backend", at(5, 10, 30))+ code, _, err = self.run_cli("--kind", "backend", "--now", at(5, 12, 0).isoformat())+ self.assertEqual(code, 2)+ self.assertIn("RELEASE_WINDOW", err)+ self.assertIn("2026-11-05 12:30", err)++ def test_cli_allows_a_backend_release_after_two_hours(self):+ self.tag("v1.0.1_backend", at(5, 10, 30))+ code, _, _ = self.run_cli("--kind", "backend", "--now", at(5, 12, 30).isoformat())+ self.assertEqual(code, 0)++ def test_the_tag_being_built_is_not_the_last_release(self):+ self.tag("v1.0.1_backend", at(5, 9, 0))+ self.tag("v1.0.2_backend", at(5, 12, 0))+ code, _, err = self.run_cli("--kind", "backend", "--now", at(5, 12, 1).isoformat(),+ "--exclude-tag", "v1.0.2_backend")+ self.assertEqual(code, 0, err)++ def test_cli_urgent_without_reason_is_refused_and_with_reason_prints_the_chat_line(self):+ now = at(5, 23, 0).isoformat()+ code, _, err = self.run_cli("--kind", "cli", "--now", now, "--urgent", "")+ self.assertEqual(code, 2)+ self.assertIn("needs a reason", err)+ code, out, _ = self.run_cli("--kind", "cli", "--now", now, "--urgent", "P0: crash on start")+ self.assertEqual(code, 0)+ self.assertIn("Urgent cli release", out)+ self.assertIn("P0: crash on start", out)++ def test_tag_message_urgent_line_is_honored_by_the_workflow_check(self):+ self.tag("v1.0.3_backend", at(5, 23, 0), message="backend release\n\nRelease-Urgent: P0: sign-out loop")+ code, out, err = self.run_cli("--kind", "backend", "--now", at(5, 23, 1).isoformat(),+ "--from-tag", "v1.0.3_backend", "--exclude-tag", "v1.0.3_backend")+ self.assertEqual(code, 0, err)+ self.assertIn("P0: sign-out loop", out)++ def test_tag_without_urgent_line_is_refused_at_night(self):+ self.tag("v1.0.3_backend", at(5, 23, 0))+ code, _, err = self.run_cli("--kind", "backend", "--now", at(5, 23, 1).isoformat(),+ "--from-tag", "v1.0.3_backend", "--exclude-tag", "v1.0.3_backend")+ self.assertEqual(code, 2)+ self.assertIn("RELEASE_WINDOW", err)++ def test_a_release_queued_past_closing_is_judged_when_it_was_tagged(self):+ # The script tagged at 17:55 inside the window; the workflow started at 18:04 after a CI queue.+ self.tag("v1.0.1_cli", at(5, 17, 55))+ code, _, err = self.run_cli("--kind", "cli", "--now", at(5, 18, 4).isoformat(),+ "--from-tag", "v1.0.1_cli", "--exclude-tag", "v1.0.1_cli")+ self.assertEqual(code, 0, err)++ def test_a_tag_made_outside_the_window_is_still_refused_when_the_workflow_starts_late(self):+ self.tag("v1.0.1_cli", at(5, 18, 2))+ code, _, err = self.run_cli("--kind", "cli", "--now", at(5, 18, 4).isoformat(),+ "--from-tag", "v1.0.1_cli", "--exclude-tag", "v1.0.1_cli")+ self.assertEqual(code, 2)+ self.assertIn("RELEASE_WINDOW", err)++ def test_a_workflow_queued_longer_than_the_grace_is_judged_now(self):+ self.tag("v1.0.1_cli", at(5, 17, 55))+ code, _, _ = self.run_cli("--kind", "cli", "--now", at(5, 18, 40).isoformat(),+ "--from-tag", "v1.0.1_cli", "--exclude-tag", "v1.0.1_cli")+ self.assertEqual(code, 2)++ def test_a_lightweight_tag_has_no_tagging_time_to_trust(self):+ # Its date is the commit's, which anyone can set: a hand-made tag is judged by the clock.+ git(self.repo, "tag", "v1.0.1_cli")+ code, _, _ = self.run_cli("--kind", "cli", "--now", at(5, 18, 4).isoformat(),+ "--from-tag", "v1.0.1_cli", "--exclude-tag", "v1.0.1_cli")+ self.assertEqual(code, 2)++ def test_a_tag_dated_after_now_is_judged_now(self):+ self.tag("v1.0.1_cli", at(5, 17, 55))+ code, _, _ = self.run_cli("--kind", "cli", "--now", at(5, 17, 50).isoformat(),+ "--from-tag", "v1.0.1_cli", "--exclude-tag", "v1.0.1_cli")+ self.assertEqual(code, 0)++ def test_advisory_reports_but_does_not_fail(self):+ code, _, err = self.run_cli("--kind", "cli", "--now", at(5, 23, 0).isoformat(), "--advisory")+ self.assertEqual(code, 0)+ self.assertIn("RELEASE_WINDOW", err)+++if __name__ == "__main__":+ unittest.main()diff --git a/scripts/tests/test_release_window_wiring.py b/scripts/tests/test_release_window_wiring.pynew file mode 100644index 000000000..53b494bfe--- /dev/null+++ b/scripts/tests/test_release_window_wiring.py@@ -0,0 +1,181 @@+"""The release scripts and tag workflows call the release-window guard before they publish anything."""+import os+import re+import shutil+import subprocess+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+SCRIPT_OF = {+ "backend": "backend/scripts/release-be.sh",+ "cli": "cli/scripts/release-cli.sh",+ "desktop": "desktop/scripts/release-desktop.sh",+ "web": "desktop/scripts/release-web.sh",+}+WORKFLOW_OF = {+ "backend": ".github/workflows/production-be-build.yaml",+ "cli": ".github/workflows/release.yml",+ "desktop": ".github/workflows/release-desktop.yml",+ "web": ".github/workflows/release-web.yml",+}+# The first thing each workflow does with the tag after the guard.+AFTER_GUARD = {+ "backend": "Work out the image tag",+ "cli": "id: resolve",+ "desktop": "id: resolve",+ "web": "Work out the version and image tag",+}+STUB = """#!/usr/bin/env python3+import os, sys+with open(os.environ["STUB_LOG"], "a") as log:+ log.write(" ".join(sys.argv[1:]) + "\\n")+code = int(os.environ.get("STUB_CODE", "0"))+if code:+ print("RELEASE_WINDOW: stub refusal", file=sys.stderr)+if code == 0 and "--urgent" in sys.argv:+ print("Urgent line from the stub")+sys.exit(code)+"""+++def git(cwd, *args):+ return subprocess.run(["git", "-C", str(cwd), *args], check=True, capture_output=True, text=True,+ env={**os.environ, "GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@t",+ "GIT_COMMITTER_NAME": "t", "GIT_COMMITTER_EMAIL": "t@t"}).stdout+++class WorkflowTests(unittest.TestCase):+ def test_each_tag_workflow_checks_the_window_before_it_does_anything_with_the_tag(self):+ for kind, path in WORKFLOW_OF.items():+ text = (ROOT / path).read_text()+ call = re.search(rf"release-window\.py --kind {kind}\b[^\n]*", text)+ self.assertIsNotNone(call, f"{path} never calls the guard")+ self.assertIn('--from-tag "$REF_NAME"', call.group(0), path)+ self.assertIn('--exclude-tag "$REF_NAME"', call.group(0), path)+ self.assertLess(text.index("actions/checkout"), call.start(), f"{path}: no checkout before the guard")+ self.assertLess(call.start(), text.index(AFTER_GUARD[kind]), f"{path}: guard runs too late")++ def test_workflows_guard_only_tag_pushes(self):+ for kind, path in WORKFLOW_OF.items():+ text = (ROOT / path).read_text()+ end = text.index(f"release-window.py --kind {kind}")+ step = text[max(0, end - 700):end]+ self.assertRegex(step, r"github\.event_name == 'push'|github\.ref_type == 'tag'", path)++ def test_a_manual_run_of_a_real_release_is_guarded_too(self):+ # "Actions > Run workflow" publishes to users like a tag does, so it takes the same guard, with a reason input.+ for kind, path, real in [("cli", WORKFLOW_OF["cli"], "harness/cli/metadata.json"),+ ("desktop", WORKFLOW_OF["desktop"], "harness/desktop/metadata.json")]:+ text = (ROOT / path).read_text()+ self.assertRegex(text, r"urgent_reason:\n\s+description:", path)+ marker = text.index("- name: Release window")+ step = text[marker:text.index("run: |", marker)]+ self.assertIn("workflow_dispatch", step, path)+ self.assertIn(real, step, path)+ self.assertIn("urgent_reason", text[marker:marker + 2500], path)+ if kind == "desktop":+ for skip in ("prepare_only", "test_candidate_reuse"):+ self.assertIn(skip, step, path)++ def test_release_notes_do_not_publish_the_urgent_line(self):+ for path in [WORKFLOW_OF["cli"], WORKFLOW_OF["desktop"]]:+ text = (ROOT / path).read_text()+ self.assertIn("Release-Urgent", text, path)++ def test_web_guard_runs_for_a_new_tag_before_it_is_made(self):+ text = (ROOT / SCRIPT_OF["web"]).read_text()+ guard = text.index("release_window_guard web")+ self.assertLess(text.index("TAG_EXISTS=0"), guard)+ self.assertLess(guard, text.index('git tag -a "$TAG"'))+ self.assertIn('Release-Urgent', text + (ROOT / "scripts/release-window.sh").read_text())+++class ScriptTests(unittest.TestCase):+ """Each script is run in a scratch copy of the repository with the guard replaced by a stub."""++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.repo = Path(self.tmp.name) / "repo"+ self.origin = Path(self.tmp.name) / "origin.git"+ subprocess.run(["git", "init", "-q", "--bare", str(self.origin)], check=True)+ self.repo.mkdir()+ git(self.repo, "init", "-q", "-b", "main")+ (self.repo / "scripts").mkdir()+ (self.repo / "scripts/release-window.py").write_text(STUB)+ shutil.copy(ROOT / "scripts/release-window.sh", self.repo / "scripts/release-window.sh")+ for rel in SCRIPT_OF.values():+ target = self.repo / rel+ target.parent.mkdir(parents=True, exist_ok=True)+ shutil.copy(ROOT / rel, target)+ git(self.repo, "add", "-A")+ git(self.repo, "commit", "-q", "-m", "init")+ git(self.repo, "remote", "add", "origin", str(self.origin))+ git(self.repo, "push", "-q", "origin", "main")+ git(self.repo, "fetch", "-q", "origin")+ self.log = Path(self.tmp.name) / "guard.log"++ def run_script(self, kind, *args, code=0):+ # Relative, as `make release-cli` runs it: the script changes directory before it sources the guard.+ env = {**os.environ, "STUB_LOG": str(self.log), "STUB_CODE": str(code), "BRANCH": "main",+ # A CI runner has no git identity, and the backend script makes an annotated tag.+ "GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@t", "GIT_COMMITTER_NAME": "t", "GIT_COMMITTER_EMAIL": "t@t"}+ return subprocess.run(["bash", SCRIPT_OF[kind], *args], capture_output=True, text=True,+ env=env, cwd=self.repo, timeout=60)++ def guard_calls(self):+ return self.log.read_text().splitlines() if self.log.exists() else []++ def test_every_script_stops_with_the_guards_exit_code_before_publishing(self):+ for kind in ["backend", "cli", "desktop"]:+ with self.subTest(kind=kind):+ result = self.run_script(kind, code=2)+ self.assertEqual(result.returncode, 2, result.stdout + result.stderr)+ self.assertIn("RELEASE_WINDOW", result.stderr)+ self.assertTrue(self.guard_calls()[-1].startswith(f"--kind {kind}"), self.guard_calls())+ self.assertEqual(git(self.origin, "tag", "-l").strip(), "")+ self.log.unlink()++ def test_urgent_reason_reaches_the_guard(self):+ for kind in ["backend", "cli", "desktop"]:+ with self.subTest(kind=kind):+ self.run_script(kind, "--urgent", "P0: sign-out loop", code=2)+ self.assertIn("--urgent P0: sign-out loop", self.guard_calls()[-1])+ self.log.unlink()++ def test_urgent_without_a_reason_still_reaches_the_guard_to_be_refused(self):+ for kind in ["backend", "cli", "desktop"]:+ with self.subTest(kind=kind):+ self.run_script(kind, "--urgent", code=2)+ self.assertIn("--urgent", self.guard_calls()[-1])+ self.log.unlink()++ def test_dry_run_asks_the_guard_for_advice_only(self):+ for kind in ["backend", "cli", "desktop"]:+ with self.subTest(kind=kind):+ self.run_script(kind, "--dry-run", code=0)+ self.assertIn("--advisory", self.guard_calls()[0])+ self.log.unlink()++ def test_desktop_candidate_for_prepare_is_not_a_release(self):+ self.run_script("desktop", "--prepare", code=2)+ self.assertEqual(self.guard_calls(), [])++ def test_backend_urgent_release_is_tagged_with_its_reason(self):+ result = self.run_script("backend", "--urgent", "P0: sign-out\nloop", code=0)+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ tag = git(self.origin, "tag", "-l", "v*_backend").split()[0]+ body = git(self.origin, "tag", "-l", "--format=%(contents)", tag)+ self.assertIn("Release-Urgent: P0: sign-out loop", body)++ def test_backend_normal_release_has_no_urgent_line(self):+ result = self.run_script("backend", code=0)+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ tag = git(self.origin, "tag", "-l", "v*_backend").split()[0]+ self.assertNotIn("Release-Urgent", git(self.origin, "tag", "-l", "--format=%(contents)", tag))+++if __name__ == "__main__":+ unittest.main()