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
Swarm: every project's instructions move onto the new base once, no rule lost (#3600) (#3300)
harness-for-autonomous[bot]246ef7c8c7b9
diff --git a/backend/integration/superTabInstructionsRebase.test.ts b/backend/integration/superTabInstructionsRebase.test.tsnew file mode 100644index 000000000..31dd14e57--- /dev/null+++ b/backend/integration/superTabInstructionsRebase.test.ts@@ -0,0 +1,185 @@+import { randomUUID } from 'node:crypto'+import { execFile } from 'node:child_process'+import { promisify } from 'node:util'+import { join } from 'node:path'+import { tmpdir } from 'node:os'+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'+import { PrismaClient } from '@prisma/client'+import type { AuthUser } from '../src/lib/ssoAuth.js'+import { SuperTabStore } from '../src/superTabs/store.js'+import type { Command } from '../src/superTabs/commands.js'+import { instructionsHash } from '../src/superTabs/instructions.js'+import { INSTRUCTIONS_TEMPLATE } from '../src/superTabs/instructionsTemplate.js'+import { attributedRules, droppedRules } from '../src/superTabs/instructionsDiff.js'+import { rebasedDocument } from '../src/superTabs/instructionsRebase.js'+import { rebaseAll, rebaseDone, rebaseUntilDone, REBASE_SUMMARY, REBASE_SWARMS } from '../src/superTabs/migration/rebase.js'+import { logger } from '../src/utils/logger.js'++// Task #3600 (anh Dee, 11-06: "ALL OF THEM"; River: "ship it asap", no preview): after the release every project's+// instructions move onto the new base once, by themselves, with no person's rule lost. A fresh loopback replica set, made here.+let replica: MongoMemoryReplSet+let db: PrismaClient+let store: SuperTabStore+const now = Date.parse('2026-11-06T04:00:00.000Z')+const owner: AuthUser = { sub: '100000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+/** Who asked for the move, named per Swarm: never its owner by default (review round 2 of #3300). */+const DEE = '6a8fe4fcf1a6b5972eed0103'+const config = { engine: 'codex', model: 'fixture-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }+const run = (tab: string, command: Command, asAgentId?: string) => store.execute(owner, tab, { operationId: randomUUID(), command }, asAgentId)++const BEFORE = `# Project instructions++How this project works (Ken, 2026-11-02).++## Roles++### PM++- Talks with people in the project chat.+- Owns the product completely (Dee, 2026-11-03). Its one mission is the positioning:+ - Tell the PM what you want, and your crew ships it.++### Integrator++- Merges and releases, in place of the PM (Ken, 2026-11-05).++## Workflow++1. One accepted request is one task.+2. Findings go straight to the Engineer (Ken, 2026-11-04; Dee, 2026-11-05).++## Talking in the project chat (anh Dee, 2026-11-04)++- Reacts instead of acknowledging.+`++beforeAll(async () => {+ replica = await MongoMemoryReplSet.create({ binary: { version: '7.0.24', downloadDir: join(tmpdir(), 'harness-super-tab-mongodb-binaries') },+ replSet: { count: 1, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })+ const uri = replica.getUri(`rebase_test_${randomUUID().replaceAll('-', '_')}`)+ await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], {+ env: { ...process.env, DATABASE_URL: uri }, timeout: 60000,+ })+ db = new PrismaClient({ datasources: { db: { url: uri } } })+ store = new SuperTabStore(db, () => now)+ await db.user.create({ data: { id: owner.sub, externalId: `fixture-${owner.sub}`, email: owner.email, autonomousEnv: owner.autonomousEnv } })+ await db.machine.create({ data: { machineId: 'test-host', userId: owner.sub, apiKey: 'fixture-only', managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })+})+afterAll(async () => {+ await db?.$disconnect()+ await replica?.stop()+})++/** A Swarm whose first project has BEFORE at revision 2 and a PM, and a second project still on the template. */+async function swarm(id: string = randomUUID()) {+ const tab = (await store.create(owner, id, 'Pilot')).id+ const pm = (await run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId: randomUUID(), name: 'Lead',+ configuration: config, lead: true })).result.agentId as string+ await run(tab, { type: 'instructions.save', projectId: 'lead', baseRevision: 1, text: BEFORE, summary: 'Our process.' })+ const app = (await run(tab, { type: 'project.create', name: 'App', visibility: 'public', brief: '' })).result.projectId as string+ return { tab, pm, app }+}+const projects = async (tab: string) => (await store.read(owner, tab)).state.projects!++describe('every project on the new base, once, by itself', () => {+ it('writes each project\'s new revision with every person\'s rule, keeps the before in its History, and tells its agents', async () => {+ const { tab, pm, app } = await swarm()+ const report = await rebaseAll(db, { now: () => now, swarms: [{ tabId: tab, askedBy: DEE }] })+ expect(report.failed).toEqual([])+ expect(report.held).toEqual([])+ expect(rebaseDone(report)).toBe(true)+ expect(report.written.filter(w => w.tabId === tab).map(w => [w.projectId, w.from, w.to])).toEqual([['lead', 2, 3], [app, 1, 2]])+ const after = await store.instructions(owner, tab, 'lead')+ expect(after).toMatchObject({ revision: 3, text: rebasedDocument(BEFORE).text, hash: instructionsHash(rebasedDocument(BEFORE).text) })+ // The one check that must be right: no person's rule dropped, reworded or left without its person.+ expect(droppedRules(BEFORE, after.text)).toEqual([])+ for (const rule of attributedRules(BEFORE)) expect(after.text.replace(/\s+/g, ' ')).toContain(rule.text)+ expect(after.text).not.toContain('Talks with people in the project chat')+ // The run's record: the before and after both readable in the History, the lines that went listed, written by the Swarm.+ expect((await store.instructionRevision(owner, tab, 'lead', 2)).text).toBe(BEFORE)+ const revision = await store.instructionRevision(owner, tab, 'lead', 3)+ expect(revision).toMatchObject({ text: after.text, summary: REBASE_SUMMARY, writtenBy: { kind: 'system', id: 'rebase' }, askedBy: DEE })+ expect(JSON.stringify(revision)).toContain('Talks with people in the project chat')+ expect((await store.instructions(owner, tab, app)).text).toBe(rebasedDocument(INSTRUCTIONS_TEMPLATE).text)+ // The new revision and hash on the head are what every agent's host compares: its PM is told the instructions changed and+ // reads them again (cli swarmInstructionsSkill.ts), as for any save.+ const head = await projects(tab)+ expect(head.map(p => [p.instructionsRevision, p.instructionsBase])).toEqual([[3, 1], [2, 1]])+ expect((await store.instructions(owner, tab, 'lead', pm)).revision).toBe(3)+ })++ it('runs once: a second run writes nothing, and a later save by a person stays', async () => {+ const { tab } = await swarm()+ await rebaseAll(db, { now: () => now, swarms: [{ tabId: tab, askedBy: DEE }] })+ await run(tab, { type: 'instructions.save', projectId: 'lead', baseRevision: 3, text: `${(await store.instructions(owner, tab, 'lead')).text}\n## This project\n\n- Repository: acme/app.\n`, summary: 'Facts.' })+ const again = await rebaseAll(db, { now: () => now, swarms: [{ tabId: tab, askedBy: DEE }] })+ expect(again.written).toEqual([])+ // A project made after the move starts on the base already (commands.ts project.create): nothing to move.+ const later = (await run(tab, { type: 'project.create', name: 'Later', visibility: 'public', brief: '' })).result.projectId as string+ expect((await rebaseAll(db, { now: () => now, swarms: [{ tabId: tab, askedBy: DEE }] })).written).toEqual([])+ expect((await store.instructions(owner, tab, later)).text).toBe(rebasedDocument(INSTRUCTIONS_TEMPLATE).text)+ expect((await projects(tab))[0]!.instructionsRevision).toBe(4)+ expect((await store.instructions(owner, tab, 'lead')).text).toContain('Repository: acme/app.')+ })++ it('holds back a project whose new document would lose a person\'s rule, writes nothing of it, and says so every run', async () => {+ const { tab, app } = await swarm()+ const error = vi.spyOn(logger, 'error').mockImplementation(() => logger)+ // A builder that drops one rule, as a fault in it would: the job's own check, not the builder's word, decides.+ const faulty = (before: string) => {+ const built = rebasedDocument(before)+ return { ...built, text: built.text.replace(/^.*Merges and releases.*$/m, ''), lost: [] }+ }+ for (let attempt = 0; attempt < 2; attempt++) {+ const report = await rebaseAll(db, { now: () => now, build: faulty, swarms: [{ tabId: tab, askedBy: DEE }] })+ expect(report.held.filter(h => h.tabId === tab)).toEqual([expect.objectContaining({ projectId: 'lead',+ rules: [expect.stringContaining('Merges and releases, in place of the PM (Ken, 2026-11-05).')] })])+ expect(rebaseDone(report)).toBe(false)+ }+ expect(error.mock.calls.filter(call => JSON.stringify(call).includes('would lose') && JSON.stringify(call).includes(tab))).toHaveLength(2)+ error.mockRestore()+ const head = await projects(tab)+ expect(head.find(p => p.id === 'lead')).toMatchObject({ instructionsRevision: 2 })+ expect(head.find(p => p.id === 'lead')!.instructionsBase).toBeUndefined()+ expect((await store.instructions(owner, tab, 'lead')).text).toBe(BEFORE)+ // The other project went on as planned.+ expect(head.find(p => p.id === app)).toMatchObject({ instructionsRevision: 2, instructionsBase: 1 })+ })++ // Review of #3300, Critical: Dee's "ALL OF THEM" is this Swarm's projects. Another team's Swarm is never touched.+ it('moves only the Swarm that asked for it, as asked by the person named for it, and leaves every other Swarm as it was', async () => {+ // Asked by anh Dee, a collaborator there, not by the Swarm's owner (ken15): review round 2 of #3300.+ expect(REBASE_SWARMS).toEqual([{ tabId: 'c51479bd73b59e58176ad9e4', askedBy: '6a8fe4fcf1a6b5972eed0103' }])+ const ours = await swarm()+ const theirs = await swarm()+ // By default it reads only the Swarm that asked, which is none of these: nothing on the server is scanned or written.+ const none = await rebaseAll(db, { now: () => now })+ expect(none).toMatchObject({ swarms: 0, written: [], held: [], failed: [], skipped: [] })+ expect(rebaseDone(none)).toBe(true)+ const report = await rebaseAll(db, { now: () => now, swarms: [{ tabId: ours.tab, askedBy: DEE }] })+ expect(report.swarms).toBe(1)+ expect(report.written.map(w => w.tabId)).toEqual([ours.tab, ours.tab])+ expect((await projects(theirs.tab)).map(p => [p.instructionsRevision, p.instructionsBase])).toEqual([[2, undefined], [1, undefined]])+ expect((await store.instructions(owner, theirs.tab, 'lead')).text).toBe(BEFORE)+ expect((await store.instructionRevision(owner, ours.tab, 'lead', 3)).askedBy).toBe(DEE)+ })++ // Review of #3300, Important 3: the hourly retries end. A held project is tried a bounded number of times, then the job+ // stops, saying so as an error; a Swarm that cannot be read keeps nothing waiting either.+ it('stops after a bounded number of passes while a project stays held back, saying it gave up', async () => {+ const { tab } = await swarm()+ const error = vi.spyOn(logger, 'error').mockImplementation(() => logger)+ const faulty = (before: string) => ({ ...rebasedDocument(before), text: rebasedDocument(before).text.replace(/^.*Merges and releases.*$/m, '') })+ const waits: number[] = []+ const report = await rebaseUntilDone(db, { swarms: [{ tabId: tab, askedBy: DEE }], build: faulty, passes: 3, wait: async ms => { waits.push(ms) } })+ expect(report?.held).toHaveLength(1)+ expect(waits).toHaveLength(2)+ expect(error.mock.calls.some(call => JSON.stringify(call).includes('gave up'))).toBe(true)+ error.mockRestore()+ // Done at once when nothing is held: one pass, no wait.+ const done: number[] = []+ expect(rebaseDone((await rebaseUntilDone(db, { swarms: [{ tabId: tab, askedBy: DEE }], wait: async ms => { done.push(ms) } }))!)).toBe(true)+ expect(done).toEqual([])+ })+})diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex ef8ee0a6c..9a131fb46 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -74,6 +74,7 @@ import { allowedDrops, approvedDropNotice, droppedLines, MAX_APPROVALS, MAX_DROPimport { appendRouting, coordinatorNameOf, routingSummary, FIRST_INSTRUCTIONS, FIRST_SUMMARY, instructionsHash, instructionsTextSchema, legacyRoleName, liveNotes, MAX_NOTES, noteTextSchema, roleNameSchema, summarySchema, type PmNote } from './instructions.js'import { repeatedRules } from './instructionsDiff.js'import { INSTRUCTIONS_TEMPLATE } from './instructionsTemplate.js'+import { BASE_DOCUMENT, BASE_VERSION } from './instructionsRebase.js'import { BUILT_IN_HEADING, tidySaved } from './pmSchedule.js'import { contractRefusal, missingContract } from './taskContract.js'import { DEFAULT_PRIORITY, PRIORITY_DEFAULTED, TASK_PRIORITIES, priorityLine, proposalPriority, titlePriority, type TaskPriority } from './taskPriority.js'@@ -1881,9 +1882,12 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,if (projects.length >= 100) fail('PROJECTS_FULL', 'A swarm can have up to 100 projects.')const leadConversationId = `project-${operationId}`// It starts on a copy of the built-in instructions as revision 1, the team's own to change (design, The built-in template).+ // In a Swarm whose projects moved onto the base (#3600), on the base, marked: one way to start a project (review of #3300).+ const onBase = projects.some(p => (p.instructionsBase ?? 0) >= BASE_VERSION)+ const first = onBase ? { instructionsRevision: 1, instructionsHash: instructionsHash(BASE_DOCUMENT), instructionsBase: BASE_VERSION } : FIRST_INSTRUCTIONSprojects.push({ id: operationId, name: command.name, ownerId: actor.userId, ownerGeneration: person(state, actor.userId).generation, leadConversationId,- visibility: command.visibility, members: [], updateMinutes: 5, skillMode: 'default', ...FIRST_INSTRUCTIONS })- effects.instructions = { projectId: operationId, revision: 1, hash: FIRST_INSTRUCTIONS.instructionsHash, text: INSTRUCTIONS_TEMPLATE,+ visibility: command.visibility, members: [], updateMinutes: 5, skillMode: 'default', ...first })+ effects.instructions = { projectId: operationId, revision: 1, hash: first.instructionsHash, text: onBase ? BASE_DOCUMENT : INSTRUCTIONS_TEMPLATE,summary: FIRST_SUMMARY, writtenBy: { kind: 'person', id: actor.userId }, askedBy: actor.userId, at: context.now }state.conversations.push({ id: leadConversationId, projectId: operationId, title: 'Lead', leadId: null,agentIds: [], archived: false, brief: command.brief, checks: [], assignment: null, lastMessageSequence: 0 })diff --git a/backend/src/superTabs/instructionsRebase.test.ts b/backend/src/superTabs/instructionsRebase.test.tsnew file mode 100644index 000000000..c5c0f0de4--- /dev/null+++ b/backend/src/superTabs/instructionsRebase.test.ts@@ -0,0 +1,167 @@+import { describe, expect, it } from 'vitest'+import { applyCommand } from './commands.js'+import { createSuperTab } from './model.js'+import { instructionsHash } from './instructions.js'+import { projectsOf } from './projects.js'+import { BASE_DOCUMENT, BASE_VERSION, REBASED_INTRO, rebasedDocument } from './instructionsRebase.js'+import { attributedRules, budgetParts, droppedRules } from './instructionsDiff.js'+import { INSTRUCTIONS_TEMPLATE } from './instructionsTemplate.js'++// Task #3600 (anh Dee, 11-06: "update them all and override all of their existing instructions. ALL OF THEM"): every+// project's instructions become only that project's facts and every person's rule word for word in its People notes ("REPLACE+// 100%", River's ruling with anh Dee): all process is the Swarm's built-in PM text (#3603), never copied into a document. The shapes below are the ones the openharness document (revision 79) writes its rules in.+export const BEFORE = `# Project instructions++These instructions say how this project works. A skill named here is fetched each time it is used (Ken, 2026-11-02).++## Roles++### PM++- Talks with people in the project chat and finds out what they want.+- Owns the product completely and works without pause to deliver it (Dee, 2026-11-03). Its one mission is the+ product's positioning:+ - Tell the PM what you want, and your crew ships it.+- Decides, doesn't ask (Ken, 2026-11-04): it decides and reports the result.+- Sets deadlines for today, in hours.++### Engineer++- Does one task, on its own branch (Dee, 2026-11-03). Writes the plan first, as a Markdown file in docs/plans/ (Ken,+ 2026-11-02).++### Integrator++- Merges and releases, in place of the PM (Ken, 2026-11-05).+- Checks a pull request's number and title before merging it.++## Workflow++1. One accepted request is one task.+2. Findings go straight to the Engineer, never through the PM (Ken, 2026-11-04).+ - While a batch pull request is open, main is closed to single merges (Ken, 2026-11-02).++## Product decisions (anh Dee)++- Voice messages play only, as Telegram draws them (anh Dee, 2026-11-04; repeated 2026-11-05 "I already told you NO").++## Talking in the project chat (anh Dee, 2026-11-04)++Every agent, the PM included:+- Writes like a teammate: first person, plain words.+- Reacts instead of acknowledging.++## Rules for every agent++- Swarm code stays out of cli/src/core.+- Never run a test that signs the Mac out of the real CLI (Ken, 2026-11-04).+- Never run a test that signs the Mac out of the real CLI (Ken, 2026-11-04).++## People notes++- Every phone app task runs on Tony's Mac first (Tony, 2026-11-03).+`++const count = (text: string, part: string) => text.split(part).length - 1++describe('a project\'s document on the new base', () => {+ it('keeps every person\'s rule word for word with who gave it, and nothing else of the old text', () => {+ const { text, lost } = rebasedDocument(BEFORE)+ expect(lost).toEqual([])+ // The rule guard itself, as every save is checked: nothing a person gave is dropped, reworded or left without its person.+ expect(droppedRules(BEFORE, text)).toEqual([])+ for (const rule of attributedRules(BEFORE)) expect(text.replace(/\s+/g, ' ')).toContain(rule.text)+ // Lines no person gave are process, which the built-in PM text carries now; no template is copied in.+ for (const line of ['Talks with people in the project chat', 'Sets deadlines for today', 'One accepted request is one task.',+ 'Swarm code stays out of cli/src/core.', 'Checks a pull request\'s number and title']) expect(text).not.toContain(line)+ expect(text).not.toMatch(/^## Roles$/m)+ expect(text).not.toMatch(/^## Workflow$/m)+ expect(INSTRUCTIONS_TEMPLATE).toContain('Says no by default to new features')+ expect(text).not.toContain('Says no by default to new features')+ expect(text.startsWith(`${REBASED_INTRO}\n\n## People notes\n`)).toBe(true)+ })++ it('files each rule in People notes under the section it came from', () => {+ const { text } = rebasedDocument(BEFORE)+ expect(text).toContain('### Roles › PM\n\n- Owns the product completely')+ expect(text).toContain('### Roles › Integrator\n\n- Merges and releases, in place of the PM (Ken, 2026-11-05).')+ expect(text).toContain('### Workflow\n\n2. Findings go straight to the Engineer')+ expect(text).toContain('### Project instructions\n\nThese instructions say how this project works.')+ // A rule already in People notes stays at its top, under no heading of its own.+ expect(text).toContain('## People notes\n\n- Every phone app task runs on Tony\'s Mac first (Tony, 2026-11-03).')+ expect(text).not.toContain('### People notes')+ })++ it('carries an attributed item with its wrapped lines and the items under it, and a section whose heading names a person whole', () => {+ const { text } = rebasedDocument(BEFORE)+ expect(text).toContain(' product\'s positioning:\n - Tell the PM what you want, and your crew ships it.')+ expect(text).toContain(' - While a batch pull request is open, main is closed to single merges (Ken, 2026-11-02).')+ // "(anh Dee, 2026-11-04)" on the heading makes every line under it his.+ expect(text).toContain('### Talking in the project chat (anh Dee, 2026-11-04)\n\nEvery agent, the PM included:\n- Writes like a teammate')+ expect(text).toContain('- Reacts instead of acknowledging.')+ })++ it('keeps an item of several attributions whole, each with its people', () => {+ const { text } = rebasedDocument(BEFORE)+ expect(text).toContain('- Does one task, on its own branch (Dee, 2026-11-03). Writes the plan first, as a Markdown file in docs/plans/ (Ken,\n 2026-11-02).')+ })++ it('writes a rule once: one written twice is kept once', () => {+ const { text } = rebasedDocument(BEFORE)+ expect(count(text, 'Never run a test that signs the Mac out of the real CLI (Ken, 2026-11-04).')).toBe(1)+ })++ it('puts the project\'s own facts under "This project", before People notes, and no section when none are given', () => {+ const facts = 'Repository: github.com/acme/app.\n\n- Tony\'s Mac has the phone.'+ const { text } = rebasedDocument(BEFORE, facts)+ expect(text.startsWith(`${REBASED_INTRO}\n\n## This project\n\n${facts}\n\n## People notes\n`)).toBe(true)+ expect(rebasedDocument(BEFORE).text).not.toContain('## This project')+ expect(rebasedDocument(BEFORE, ' \n').text).not.toContain('## This project')+ expect(rebasedDocument('# Ours\n\n- Ship it.\n').text).toBe(`${REBASED_INTRO}\n`)+ })++ it('is the same document a second time: a second run has nothing to write', () => {+ const once = rebasedDocument(BEFORE, 'A fact.').text+ expect(rebasedDocument(once, 'A fact.').text).toBe(once)+ expect(rebasedDocument(once, 'A fact.').lost).toEqual([])+ })++ it('carries a fenced block that holds a rule whole, and reads a heading in a fence as text', () => {+ const before = '# P\n\n## Routing\n\n```\n## Not a heading (Ken, 2026-11-02)\n- kept as written\n```\n'+ const { text, lost } = rebasedDocument(before)+ expect(lost).toEqual([])+ expect(text).toContain('### Routing\n\n```\n## Not a heading (Ken, 2026-11-02)\n- kept as written\n```')+ })++ it('stays within the core budget, People notes aside', () => {+ const core = budgetParts(rebasedDocument(BEFORE, 'Repository: github.com/acme/app.').text).find(p => p.part === 'core')!+ expect(core.bytes).toBeLessThan(1024)+ })+})+++// Review of #3300: one way to start a project. A Swarm whose projects moved onto the base starts a new one on it too, marked,+// so the job never has to move it and it never runs on the old template meanwhile.+describe('a new project', () => {+ const create = (moved: boolean) => {+ const state = createSuperTab('tab', 'Pilot', { id: 'owner', email: '[email protected]' }, 'prod')+ if (moved) Object.assign(projectsOf(state)[0]!, { instructionsBase: BASE_VERSION })+ const effects = applyCommand(state, { kind: 'person', userId: 'owner', email: '[email protected]' },+ { type: 'project.create', name: 'App', visibility: 'public', brief: '' }, { now: 1000, operationId: 'op-1' })+ return { effects, project: projectsOf(effects.state).find(p => p.id === effects.result.projectId)! }+ }++ it('starts on the base, marked, in a Swarm whose projects moved onto it', () => {+ const { effects, project } = create(true)+ expect(BASE_DOCUMENT).toBe(rebasedDocument(INSTRUCTIONS_TEMPLATE).text)+ expect(project).toMatchObject({ instructionsRevision: 1, instructionsHash: instructionsHash(BASE_DOCUMENT), instructionsBase: BASE_VERSION })+ expect(effects.instructions).toMatchObject({ projectId: project.id, revision: 1, text: BASE_DOCUMENT })+ })++ it('starts on the template, unmarked, in any other Swarm', () => {+ const { effects, project } = create(false)+ expect(project).toMatchObject({ instructionsRevision: 1, instructionsHash: instructionsHash(INSTRUCTIONS_TEMPLATE) })+ expect(project.instructionsBase).toBeUndefined()+ expect(effects.instructions).toMatchObject({ text: INSTRUCTIONS_TEMPLATE })+ })+})diff --git a/backend/src/superTabs/instructionsRebase.ts b/backend/src/superTabs/instructionsRebase.tsnew file mode 100644index 000000000..be2422a8b--- /dev/null+++ b/backend/src/superTabs/instructionsRebase.ts@@ -0,0 +1,142 @@+/**+ * Every project's instructions on the new base, in one approved change (task #3600, anh Dee 11-06: "update them all and+ * override all of their existing instructions. ALL OF THEM"; River's ruling with him: "REPLACE 100%"). All process is the+ * Swarm's built-in PM text (pmSchedule.ts, #3603), never copied into a document. A document keeps only a short intro, the+ * project's own facts (repo, devices, people's areas: given per project by the run) and People notes: every block of the old+ * document that holds a person's rule, word for word with who gave it, filed under the section it came from. The rule guard's+ * own reader (instructionsDiff.ts droppedRules) checks that nothing a person gave is lost; a project that would lose one is+ * refused, never written.+ */+import { attributedRules, droppedRules, type AttributedRule, type DroppedRule } from './instructionsDiff.js'+import { INSTRUCTIONS_TEMPLATE } from './instructionsTemplate.js'++export const REBASED_INTRO = `# Project instructions++How this project works is built into Harness. This document holds only this project's own facts and, in People notes, the+rules its people gave, word for word.`++export interface RebasedDocument {+ text: string+ /** The person's rules the new document carries, in the old document's order. */+ carried: AttributedRule[]+ /** Rules the new document would lose (droppedRules): none, or the project is not written. */+ lost: DroppedRule[]+}++const HEADING = /^ {0,3}(#{1,6})[ \t]+(.+?)(?:[ \t]+#+)?[ \t]*$/+const FENCE = /^ {0,3}(?:```|~~~)/+const LIST_ITEM = /^([ \t]*)(?:[-*+]|\d{1,9}[.)])[ \t]+/+const PEOPLE_NOTES = /^people notes$/i+const indent = (line: string) => /^[ \t]*/.exec(line)![0].length+const holdsRule = (lines: readonly string[]) => attributedRules(lines.join('\n')).length > 0++/** One piece of the old document carried whole: a top-level block (a list item with its wrapped lines and the items under+ * it, a paragraph or a fenced block) under [path], or a section whose heading names a person ([heading]). */+interface Piece { path: string; lines: string[]; section: boolean }++/** [text]'s pieces that hold a person's rule, in document order. A heading in a fence is text. */+function pieces(text: string): Piece[] {+ const lines = text.replace(/\r\n?/g, '\n').split('\n')+ const headings: (string | undefined)[] = []+ const pathOf = () => {+ const below = headings.slice(1).filter((h): h is string => !!h)+ const path = below.length ? below : headings.slice(0, 1).filter((h): h is string => !!h)+ // People notes of an earlier run (or kept by hand) file their rules again under the section they name.+ if (path[0] && PEOPLE_NOTES.test(path[0])) path.shift()+ return path.join(' › ')+ }+ const found: Piece[] = []+ let i = 0+ while (i < lines.length) {+ const line = lines[i]!+ if (!line.trim()) { i++; continue }+ const heading = FENCE.test(line) ? null : HEADING.exec(line)+ if (heading) {+ const level = heading[1]!.length, title = heading[2]!.trim()+ if (holdsRule([title])) {+ // Every line under a heading that names a person is theirs: the section is carried whole, to its next sibling heading.+ const parent = (headings.length = level - 1, pathOf())+ const section = [line]+ let fenced = false+ for (i++; i < lines.length; i++) {+ const next = lines[i]!+ if (FENCE.test(next)) fenced = !fenced+ const inner = fenced || FENCE.test(next) ? null : HEADING.exec(next)+ if (inner && inner[1]!.length <= level) break+ section.push(next)+ }+ // Its heading becomes a People notes subsection; headings under it keep their depth below it.+ const shift = 3 - level+ let inFence = false+ const moved = section.map(l => {+ if (FENCE.test(l)) { inFence = !inFence; return l }+ const h = inFence ? null : HEADING.exec(l)+ return h ? `${'#'.repeat(Math.min(6, Math.max(3, h[1]!.length + shift)))} ${h[2]!.trim()}` : l+ })+ while (moved.length && !moved.at(-1)!.trim()) moved.pop()+ found.push({ path: parent, lines: moved, section: true })+ headings[level - 1] = undefined+ continue+ }+ headings.length = level - 1+ headings[level - 1] = title+ i+++ continue+ }+ const block = [line]+ const base = indent(line), listed = LIST_ITEM.test(line)+ let fenced = FENCE.test(line)+ for (i++; i < lines.length; i++) {+ const next = lines[i]!+ if (fenced) { block.push(next); if (FENCE.test(next)) fenced = false; continue }+ if (!next.trim()) {+ // A blank line ends the block unless what follows is indented under it.+ let k = i + 1+ while (k < lines.length && !lines[k]!.trim()) k+++ if (k < lines.length && listed && indent(lines[k]!) > base && !HEADING.exec(lines[k]!)) { block.push(...lines.slice(i, k)); i = k - 1; continue }+ break+ }+ if (HEADING.exec(next) && !FENCE.test(next)) break+ const item = LIST_ITEM.exec(next)+ if (item && (!listed || item[1]!.length <= base)) break+ if (FENCE.test(next)) fenced = true+ block.push(next)+ }+ if (holdsRule(block)) found.push({ path: pathOf(), lines: block, section: false })+ }+ return found+}++const key = (lines: readonly string[]) => lines.join(' ').replace(/\s+/g, ' ').trim()+/** Pieces joined as written: list items line after line, anything else after a blank line, so no paragraph joins an item. */+function joined(blocks: readonly string[][]): string {+ return blocks.map((lines, k) => (k && !(LIST_ITEM.test(lines[0]!) && LIST_ITEM.test(blocks[k - 1]![0]!)) ? '\n' : '') + lines.join('\n')).join('\n')+}++/** [before]'s document on the new base, with [facts] as its "This project" section. Pure: the same input gives the same text,+ * and a document already on the base with the same facts gives itself. */+export function rebasedDocument(before: string, facts = ''): RebasedDocument {+ const seen = new Set<string>()+ const groups = new Map<string, string[][]>([['', []]])+ const sections: string[][] = []+ for (const piece of pieces(before)) {+ const id = key(piece.lines)+ if (seen.has(id)) continue+ seen.add(id)+ if (piece.section) sections.push(piece.lines)+ else groups.set(piece.path, [...groups.get(piece.path) ?? [], piece.lines])+ }+ const notes = [...groups].filter(([, blocks]) => blocks.length)+ .map(([path, blocks]) => path ? `### ${path}\n\n${joined(blocks)}` : joined(blocks))+ const parts = [REBASED_INTRO]+ if (facts.trim()) parts.push(`## This project\n\n${facts.trim()}`)+ if (notes.length || sections.length) parts.push(['## People notes', ...notes, ...sections.map(lines => lines.join('\n'))].join('\n\n'))+ const text = `${parts.join('\n\n')}\n`+ return { text, carried: attributedRules(before), lost: droppedRules(before, text) }+}++/** The base a project is on once moved (SwarmProject.instructionsBase): migration/rebase.ts moves a project onto it once. */+export const BASE_VERSION = 1+/** What a new project of a Swarm on the base starts as (commands.ts project.create): the template's document moved, so a+ * project made after the move and one moved by it read alike. */+export const BASE_DOCUMENT = rebasedDocument(INSTRUCTIONS_TEMPLATE).textdiff --git a/backend/src/superTabs/migration/rebase.ts b/backend/src/superTabs/migration/rebase.tsnew file mode 100644index 000000000..bfcf2f73d--- /dev/null+++ b/backend/src/superTabs/migration/rebase.ts@@ -0,0 +1,183 @@+/**+ * Every project's instructions onto the new base, once, by themselves after the release (task #3600; anh Dee 11-06: "update+ * them all and override all of their existing instructions. ALL OF THEM"; River: no preview, "ship it asap"). Each project's+ * document becomes instructionsRebase.ts's: a short intro and every person's rule word for word in People notes; all process+ * is the Swarm's built-in PM text. It runs in the singleton worker, a Swarm per transaction, guarded by the head's version as+ * migration/instructions.ts writes: a command in between wins, and the Swarm is tried again on the next pass.+ *+ * The one check that must be right: no person's rule is lost. The job reads that itself with the rule guard's reader+ * (instructionsDiff.ts droppedRules) on the document it would write, never trusting the builder; a project that would lose+ * one is held back, unwritten and unmarked, and logged as an error on every pass until someone acts.+ *+ * Its record is the project's Instructions history: the revision before (the old document) and the new one, written by the+ * Swarm, with every line that went (ruleGuard.ts droppedLines). The new revision and hash on the head are what every agent's+ * host compares, so each PM is told the instructions changed and reads them again, as for any save.+ *+ * Once: a project is marked (`instructionsBase`) when it is on the base, so a later save is never rewritten. A project made+ * after the move starts on the base already (commands.ts project.create).+ *+ * Only the Swarm that asked (review of #3300, Critical): anh Dee's "ALL OF THEM" is this Swarm's projects. Another team's+ * document is theirs; moving it needs an explicit ruling from Dee or Ken, which adds it to REBASE_SWARMS with who asked.+ *+ * Rollback: each project's previous revision is in its History; restoring it is an ordinary save of that text (Desktop's+ * Instructions history, or instructions.save), and the mark keeps this job from moving it again.+ */+import type { Prisma, PrismaClient } from '@prisma/client'+import { clock, guardedWrite, loadAll, reassemble } from '../parts/index.js'+import { swarmTransaction } from '../cache.js'+import type { SuperTabState } from '../model.js'+import { projectsOf } from '../projects.js'+import { instructionsHash, MAX_INSTRUCTIONS_BYTES } from '../instructions.js'+import { INSTRUCTIONS_TEMPLATE } from '../instructionsTemplate.js'+import { instructionsId, writeInstructions } from '../instructionsStore.js'+import { droppedRules } from '../instructionsDiff.js'+import { droppedLines } from '../ruleGuard.js'+import { BASE_VERSION, rebasedDocument, type RebasedDocument } from '../instructionsRebase.js'+import { logger } from '../../utils/logger.js'+import { sleeper } from './dropLegacyJob.js'++type Transaction = Prisma.TransactionClient+const TRANSACTION = { maxWait: 5_000, timeout: 60_000 }+export { BASE_VERSION }+/** A Swarm this job moves, and the member who asked for it, recorded as the History's asker. */+export interface RebaseSwarm { tabId: string; askedBy: string }+/** autonomous.ai, where anh Dee (a collaborator; the Swarm's owner is ken15) asked for it in task #3600 (review round 2 of+ * #3300: never the owner by default, who did not ask). */+export const REBASE_SWARMS: readonly RebaseSwarm[] = [{ tabId: 'c51479bd73b59e58176ad9e4', askedBy: '6a8fe4fcf1a6b5972eed0103' }]+export const REBASE_SUMMARY = 'Moved onto the new base: the process is built into Harness; every person\'s rule is kept word for word in People notes.'+/** Between two passes while any project is held back or any Swarm failed or waits for its split. */+export const RETRY_MS = 3_600_000+/** Passes before the job gives up on what it could not move, saying so: a day of hourly tries. */+export const MAX_PASSES = 24+/** Lets a starting worker finish its own startup first. */+export const START_DELAY_MS = 60_000++export interface RebaseReport {+ swarms: number+ /** Projects given a new revision. */+ written: Array<{ tabId: string; projectId: string; from: number; to: number; rules: number }>+ /** Projects already on the base's text: marked, nothing written. */+ unchanged: number+ /** Projects not moved, and why: a rule it would lose, a document past 64 KB, or a stored document that cannot be read. */+ held: Array<{ tabId: string; projectId: string; why: string; rules?: string[] }>+ failed: Array<{ tabId: string; error: string }>+ /** Swarms still in one row: moved once they are split. */+ skipped: string[]+}++export interface RebaseOptions {+ now?: () => number+ /** The document builder; tests pass a faulty one to prove the job's own check holds the project back. */+ build?: (before: string) => RebasedDocument+ /** The Swarms to move and who asked: REBASE_SWARMS unless a test names its own. */+ swarms?: readonly RebaseSwarm[]+}++/** Whether nothing is left to move: every project of every Swarm on the base. */+export const rebaseDone = (report: RebaseReport): boolean => !report.held.length && !report.failed.length && !report.skipped.length++async function rebaseSwarm(tx: Transaction, { tabId, askedBy }: RebaseSwarm, now: number, build: (before: string) => RebasedDocument, report: RebaseReport): Promise<void> {+ const parts = await loadAll(tx, tabId)+ const state = reassemble(parts) as SuperTabState+ const projects = projectsOf(state)+ const writes: Array<{ projectId: string; askedBy: string; revision: number; before: string; text: string; rules: number }> = []+ const held: RebaseReport['held'] = []+ const marked = new Set<string>()+ for (const project of projects) {+ if ((project.instructionsBase ?? 0) >= BASE_VERSION) continue+ const revision = project.instructionsRevision ?? 0+ const stored = revision ? await tx.superTabInstructions.findUnique({ where: { id: instructionsId(tabId, project.id) } }) : null+ if (revision && stored?.revision !== revision) { held.push({ tabId, projectId: project.id, why: 'its stored document does not match its revision' }); continue }+ const before = stored?.text ?? INSTRUCTIONS_TEMPLATE+ const { text, carried } = build(before)+ const lost = droppedRules(before, text)+ if (lost.length) {+ held.push({ tabId, projectId: project.id, why: `its new document would lose ${lost.length} of its people's rules`, rules: lost.map(rule => rule.text) })+ continue+ }+ if (Buffer.byteLength(text) > MAX_INSTRUCTIONS_BYTES) { held.push({ tabId, projectId: project.id, why: 'its people\'s rules alone pass 64 KB' }); continue }+ marked.add(project.id)+ // Asked by the member named for this Swarm (anh Dee), never its owner or a project's owner (review rounds 1 and 2 of #3300).+ if (text !== before) writes.push({ projectId: project.id, askedBy, revision, before, text, rules: carried.length })+ }+ if (marked.size) {+ const written = new Map(writes.map(w => [w.projectId, w]))+ // A Swarm from before projects keeps its one project only in `projectsOf`: it is written out, as any project command does.+ const next = projects.map(({ progress: _progress, ...project }) => {+ if (!marked.has(project.id)) return project+ const write = written.get(project.id)+ return { ...project, instructionsBase: BASE_VERSION, ...write ? { instructionsRevision: write.revision + 1, instructionsHash: instructionsHash(write.text) } : {} }+ })+ await guardedWrite(tx, tabId, { op: 'update', kind: 'head', key: 'head', seen: parts.head.version, data: { ...parts.head.data!, projects: next },+ head: { groupCounter: parts.groupCounter, visibilityEpoch: parts.visibilityEpoch, sequenceBase: parts.sequenceBase } }, clock.next())+ for (const write of writes) {+ await writeInstructions(tx, tabId, { projectId: write.projectId, revision: write.revision + 1, hash: instructionsHash(write.text), text: write.text,+ summary: REBASE_SUMMARY, writtenBy: { kind: 'system', id: 'rebase' }, askedBy: write.askedBy, at: now,+ dropped: droppedLines(write.before, write.text, [], []) })+ }+ }+ report.written.push(...writes.map(w => ({ tabId, projectId: w.projectId, from: w.revision, to: w.revision + 1, rules: w.rules })))+ report.unchanged += marked.size - writes.length+ report.held.push(...held)+}++/** One pass over the named Swarms: each project not on the base yet is moved, or held back and said why. A Swarm not on this+ * server (a test or staging database) has nothing to move. */+export async function rebaseAll(db: PrismaClient, { now = Date.now, build = before => rebasedDocument(before), swarms = REBASE_SWARMS }: RebaseOptions = {}): Promise<RebaseReport> {+ const report: RebaseReport = { swarms: 0, written: [], unchanged: 0, held: [], failed: [], skipped: [] }+ for (const swarm of swarms) {+ const row = await db.superTab.findUnique({ where: { id: swarm.tabId }, select: { id: true, format: true } })+ if (!row) continue+ if (row.format !== 2) { report.skipped.push(row.id); continue }+ report.swarms+++ // A Swarm's own pass is all or nothing: a failure leaves its documents as they were, and its report rows out.+ const own: RebaseReport = { ...report, written: [], unchanged: 0, held: [] }+ try {+ await swarmTransaction(db, tx => rebaseSwarm(tx, swarm, now(), build, own), TRANSACTION)+ report.written.push(...own.written)+ report.unchanged += own.unchanged+ report.held.push(...own.held)+ } catch (error) {+ report.failed.push({ tabId: row.id, error: error instanceof Error ? error.message : String(error) })+ }+ }+ // Said loudly, each pass: a project held back keeps its old document, and its PM works against old process text, until+ // someone fixes it (backend AGENTS.md rule 4).+ for (const held of report.held) {+ logger.error(`[instructions-rebase] project held back: ${held.why}. It keeps its old instructions until this is fixed; tried again every hour, a day at most.`,+ { tabId: held.tabId, projectId: held.projectId, ...held.rules ? { rules: held.rules.length } : {} })+ }+ for (const failed of report.failed) logger.error('[instructions-rebase] Swarm not moved; tried again every hour.', failed)+ return report+}++/** Passes until nothing is left to move, at most [passes], [wait]ing RETRY_MS between; then it gives up on what is left,+ * saying so as an error. Returns the last pass's report (null when stopped before one). */+export async function rebaseUntilDone(db: PrismaClient, { passes = MAX_PASSES, wait = sleeper(), signal, ...options }: RebaseOptions & {+ passes?: number; wait?: (ms: number) => Promise<void>; signal?: AbortSignal } = {}): Promise<RebaseReport | null> {+ let report: RebaseReport | null = null+ for (let pass = 1; pass <= passes && !signal?.aborted; pass++) {+ try {+ report = await rebaseAll(db, options)+ logger.info('[instructions-rebase] pass', { pass, swarms: report.swarms, written: report.written.length, unchanged: report.unchanged,+ held: report.held.length, failed: report.failed.length, skipped: report.skipped.length })+ if (rebaseDone(report)) return report+ } catch (error) {+ logger.error('[instructions-rebase] pass failed', { pass, error: error instanceof Error ? error.message : String(error) })+ }+ if (pass < passes) await wait(RETRY_MS)+ }+ if (!signal?.aborted) {+ logger.error(`[instructions-rebase] gave up after ${passes} passes: what is left keeps its old instructions until someone fixes it and restarts the worker.`,+ { held: report?.held.map(h => ({ tabId: h.tabId, projectId: h.projectId, why: h.why })) ?? [], failed: report?.failed ?? [], skipped: report?.skipped ?? [] })+ }+ return report+}++/** Starts the move in the background after [delayMs]; the returned function stops it. */+export function startInstructionsRebase(db: PrismaClient, delayMs = START_DELAY_MS): () => void {+ const control = new AbortController()+ const wait = sleeper(control.signal)+ void wait(delayMs).then(() => rebaseUntilDone(db, { wait, signal: control.signal }))+ return () => control.abort()+}diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.tsindex cc09edd18..b2de5726e 100644--- a/backend/src/superTabs/projects.ts+++ b/backend/src/superTabs/projects.ts@@ -89,6 +89,8 @@ export interface SwarmProject {* from before instructions until the migration writes its document; it runs on the built-in template meanwhile. */instructionsRevision?: numberinstructionsHash?: string+ /** The base its instructions were moved onto once (migration/rebase.ts, task #3600): a later save is never rewritten. */+ instructionsBase?: number/** Moves on each note the coordinator keeps or a member removes (instructions.ts), so an open panel knows to read them. */notesRevision?: number/** Moves when its repository's GitHub access may have changed: someone allowed it, GitHub sent someone back afterdiff --git a/backend/src/worker.ts b/backend/src/worker.tsindex c97d56c60..4f37b5671 100644--- a/backend/src/worker.ts+++ b/backend/src/worker.ts@@ -20,6 +20,7 @@ import { releaseSchema } from './lib/db/schemaRelease.js'import { startSwarmSweeps } from './superTabs/sweeps.js'import { requeueCompactedAgents } from './superTabs/agentTombstones.js'import { startLegacyDrop } from './superTabs/migration/dropLegacyJob.js'+import { startInstructionsRebase } from './superTabs/migration/rebase.js'import { startDeliverySettle } from './superTabs/deliverySettle.js'import { startDeliveryRepush } from './superTabs/deliveryRepush.js'import { startDeliveryCompaction } from './superTabs/deliveryCompaction.js'@@ -81,6 +82,7 @@ async function start(): Promise<void> {let stopSweeps = (): void => {}let stopLegacyDrop = (): void => {}+ let stopInstructionsRebase = (): void => {}let stopArchive = (): void => {}let stopPullRequestWatch = (): void => {}let stopTimeChecks = (): void => {}@@ -105,6 +107,7 @@ async function start(): Promise<void> {productUsagePeopleRollupService.stop()stopSweeps()stopLegacyDrop()+ stopInstructionsRebase()stopArchive()stopPullRequestWatch()stopTimeChecks()@@ -161,6 +164,8 @@ async function start(): Promise<void> {stopSweeps = startSwarmSweeps(prisma, undefined, () => swarms.workspaces.finishRemovals(), now => swarms.leaveOverdueDecisions(now))// The dead old state of migrated Swarms goes by itself, a few at a time (superTabs/migration/dropLegacyJob.ts).stopLegacyDrop = startLegacyDrop(prisma)+ // Every project's instructions move onto the new base once, by themselves (superTabs/migration/rebase.ts, task #3600).+ stopInstructionsRebase = startInstructionsRebase(prisma)// Finished groups archive once GitHub says their pull requests are merged or closed; without the app, only groups that// link none do (superTabs/archive.ts).const githubConfig = githubAppConfig(env), githubApp = githubConfig ? new GitHubApp(githubConfig) : nulldiff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.tsindex 095790ea4..ba86adbb4 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/superTabScorecard.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/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/superTabTimeChecks.test.ts', 'integration/superTabReleases.test.ts', 'integration/superTabReviewSteps.test.ts', 'integration/superTabMergeTrain.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', 'integration/crewDispatch.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/superTabInstructionsRebase.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/superTabTimeChecks.test.ts', 'integration/superTabReleases.test.ts', 'integration/superTabReviewSteps.test.ts', 'integration/superTabMergeTrain.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', 'integration/crewDispatch.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/docs/plans/2026-11-06-instructions-rebase-plan.md b/docs/plans/2026-11-06-instructions-rebase-plan.mdnew file mode 100644index 000000000..87804dfa7--- /dev/null+++ b/docs/plans/2026-11-06-instructions-rebase-plan.md@@ -0,0 +1,68 @@+# Every project's instructions on the new base — Implementation Plan++> Written by the project's Engineer by the writing-plans skill, as the project instructions say: the Engineer implements it+> task by task, test first, and the pull request's review step is its one independent review.++**Goal:** Every project's instructions move onto the new base once, by themselves, after the backend release (anh Dee 11-06:+"ALL OF THEM"; River's rulings the same day: "REPLACE 100%", no preview, no approval step, one review). Each document+becomes a short intro and every person's rule word for word in People notes; all process is the Swarm's built-in PM text+(#3603). No person's rule may be lost: that is the one check that must be right.++**Architecture:** A pure builder, `instructionsRebase.ts rebasedDocument`, carries every block of the old document that holds+an attributed rule (an item with its wrapped lines and nested items, a paragraph, a fenced block, or a whole section whose+heading names a person) into People notes, filed under its old section. A worker job, `migration/rebase.ts`, moves each+project not yet marked, one Swarm per transaction guarded by the head's version (as migration/instructions.ts writes),+checks with the rule guard's own reader (`droppedRules`) that the document it would write keeps every rule, writes the new+revision as the Swarm, and marks the project (`instructionsBase`) so it never runs on it again. A project that would lose+a rule is held back, unwritten, and logged as an error every hourly pass.++**Tech Stack:** TypeScript, Prisma (MongoDB), vitest; MongoMemoryReplSet for the job's test.++**Spec:** task #3600's brief and River's rulings in its conversation (35059e6f472ab0db037bba90).++## Global Constraints++- Every attributed rule, "(Name, date)" as instructionsDiff.ts reads it, stays word for word with who gave it, checked by+ the job itself on what it writes; a project that would lose one is not written.+- Runs once per project: marked when on the base; a later save is never rewritten.+- The record: the Instructions history keeps the revision before and the new one, written by the Swarm (`system`,+ `rebase`), with every line that went (ruleGuard.ts droppedLines).+- Each PM is told through the new revision and hash, as for any save (the CLI host's "instructions changed" notice).+- A document stays within 64 KB; the size budget is not enforced here (openharness keeps ~22 KB of rules; later saves may+ only shrink People notes, ruleGuard.ts refuseOverBudget).+- Only the Swarm that asked (autonomous.ai, REBASE_SWARMS), recorded as asked by anh Dee (a collaborator there; the owner is+ ken15, who did not ask): another team's document is moved only on+ an explicit ruling from Dee or Ken (review of #3300, Critical).+- A Swarm on the base starts each new project on the base, marked (commands.ts project.create): one way to start a project.+- At most 24 hourly passes; then the job gives up on what is left, saying so as an error.++## Design++- Growth: one revision per project, once; revisions stay capped at 50 per project (instructionsStore.ts).+- Concurrency: one Swarm per transaction, head version guarded: a command in between wins and the Swarm is retried next pass.+- Read cost: one Swarm read per pass; one pass per worker start, then hourly (a day at most) only while something is held back.+- Scale: 10x Swarms is 10x passes of one transaction each; the pass log's counts warn first.+- Compatibility: `instructionsBase` is a new optional project field; old readers ignore it.+- Migration + rollback: this is the migration; rollback is an ordinary save of each project's previous revision from its+ History, and the mark keeps the job from moving it again. A project already at 50 revisions drops its oldest, never the+ one before the move.+- Audience: nothing new is exposed; the History is read by who reads the project.+- Identity: written by the Swarm (`system`), asked by the member REBASE_SWARMS names for the Swarm (anh Dee), never its owner.+- Failure: a held project or failed Swarm is logged as an error every pass, with why; nothing is written for it.+- Platforms: server only.++## Review Focus++- A rule in an item of several attributions, nested under an unattributed item, or under a heading that names a person.+- A rule already in People notes, or written twice: kept once.+- A project with no document yet (revision 0) or still on the template.+- A save between the job's read and write: the head guard makes it retry.+- A faulty builder: the job's own check holds the project back.++---++### Task 1: Build one project's document — `instructionsRebase.ts`, tested in `instructionsRebase.test.ts` (done)+### Task 2: The run-once job — `migration/rebase.ts`, wired in `worker.ts`, tested in `integration/superTabInstructionsRebase.test.ts`+- [x] Failing test: writes each project with every rule, keeps the before in its History; runs once; holds back a project a+ faulty builder would make lose a rule, and logs it every pass.+- [x] Job, marker field (`projects.ts instructionsBase`), worker start and stop.