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.
Copy less Swarm state per request (DB roadmap 2.6) Implementation Plan
For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (
- [ ]) syntax for tracking.
Goal: A machine report stops reading SwarmProgress, visibleState copies only what it returns, and the
remaining whole-state copies use a plain-data copy instead of structuredClone, with every reply and write unchanged.
Architecture: One new leaf module, backend/src/superTabs/cloneData.ts, copies plain data and throws on anything
else. parts/load.ts loadObserved passes progress: null to assemble, so a report loads and commits no progress part.
model.ts visibleState removes the five pruned fields and dormant conversations before copying, and leaves every
other step in its current order. An old copy of visibleState in the test file is the reference: the new output must
match it for every kind of reader.
Tech Stack: TypeScript, Prisma on MongoDB, vitest, mongodb-memory-server (integration).
Spec: docs/superpowers/specs/2026-10-30-swarm-state-copies-design.md. Its decisions are final, including no
copy-on-write.
Global Constraints
- Branch
perf/swarm-state-copies, based onmain17056adb6. Before Task 1, rungit fetch origin main. Ifmainhas moved, rebase onto it. - Fresh worktree: run
npm ciandnpx prisma generateonce inbackend/before the first test. - All commands run from
backend/.- Unit:
npx vitest run <file>. If a test needs the credential key, usenpm test -- <file>instead, which sets it. - Integration:
npx vitest run --config vitest.super-tabs.config.ts <file>. - Types:
npm run typecheck.
- Unit:
- Some tests already fail on
main. Before calling a failure a regression, run the same file on a clean worktree atorigin/mainand compare the failing test names. - Kill only processes you started. Never
pkillmongod or vitest by pattern: other sessions share this Mac. - Don't commit or push until Ken asks. Each task ends with a checkpoint (
git status --short), not a commit. - Remove dead code, including the deletes in
visibleStatethat the pruned copy makes redundant. - Every reply, every stored write and every message stays byte for byte the same.
- Spec 1 (
perf/swarm-changes-shared-light-read) is independent and changes other files. Don't touch its files. - The spec's line numbers are from 2bbcad4c4 and have moved. This plan names methods instead of lines.
Review Focus
- Frozen shared input. The read cache gives
visibleStatedeep-frozen state that other requests share (cache.ts freeze). The new code must never write to its input, and its copy must be writable. Covered by Task 1 (a copy of frozen data can be changed) and Task 3 (visibleStateon a frozen state matches the reference). - Key order in replies. Deep equality ignores key order, but JSON bytes, and any ETag computed from them, do
not. The pruned copy must keep
conversationsin its original key position. Covered by Task 3, which also comparesJSON.stringifyoutput for each reader. - A report that writes while progress is not loaded. When a report loses a task, it writes group, agent and message parts. It must not remove or rewrite the progress part, which it never loaded. Covered by Task 2's second report.
- Non-plain values at runtime. If a state ever holds a
Date,BufferorMap,cloneDatafails the request wherestructuredClonewould not. Dates are supported. Task 4 runs the full Super Tab integration suite on real Mongo data to cover every replaced path. - Shared references.
structuredClonekeeps two references to one object as one object.cloneDatamakes two separate copies. A loaded state shares no objects (reassemblebuilds each record once). Task 1 checks that no object is reached twice in the fixture states and in a reassembled state.
Task 1: cloneData
Files:
- Create:
backend/src/superTabs/cloneData.ts - Test:
backend/src/superTabs/cloneData.test.ts
Interfaces:
Produces:
export function cloneData<T>(value: T): Tinbackend/src/superTabs/cloneData.ts. The module has no imports, so model, commands, native and store can all import it without a cycle.Step 1: Write the failing tests in
cloneData.test.ts:Test-only helpers:
reachedOnce(value): walks the value and fails if it reaches any object twice.sharesNothing(source, copy): walks both side by side and fails if any object in the copy is===to the one at the same path in the source.
States under test, built with
swarm,richSwarmandNOWfromread/fixture.test-support.ts:richSwarm().state.- A Swarm at the bench's default size:
swarm(), plus a Lead, 200 groups made withs.group, and 20 workers, each assigned one group withwork.assign. reassemble(split(richSwarm().state, { tabId: 'tab', version: 1, now: NOW }), { share: true }), which is how a loaded state is built.
Tests:
it('copies every fixture state as structuredClone does, sharing nothing'): for each state,reachedOnce(state);expect(cloneData(state)).toStrictEqual(structuredClone(state));sharesNothing(state, cloneData(state)).
it('keeps undefined values and copies a Date as a new Date'): the input is{ a: undefined, at: new Date(NOW), list: [1, 'x', null, true] }.toStrictEqualthe input;'a' in copyis true;copy.at instanceof Date,copy.at !== input.at, andcopy.at.getTime() === NOW.
it('returns a writable copy of frozen data'): callfreeze(fromcache.js) onstructuredClone(richSwarm().state). Then:Object.isFrozen(copy)is false, and so isObject.isFrozen(copy.conversations[0]);copy.conversations[0].title = 'changed'doesn't throw.
it('throws on values it cannot copy, naming where they are'). Each case uses its own expectation:Input Expected error { agents: [{ extra: new Map() }] }toThrow(/cannot copy a Map at agents\.0\.extra/){ s: new Set() }toThrow(/cannot copy a Set at s/){ c: new (class Thing {})() }toThrow(/cannot copy a Thing at c/){ f: () => 1 }toThrow(/cannot copy a function at f/)
Step 2: Run the tests and see them fail. Run
npx vitest run src/superTabs/cloneData.test.ts. Expected: it fails because./cloneData.jscannot be resolved.Step 3: Implement
cloneData<T>(value: T): T.- Primitives (including
undefined,nullandbigint) are returned as they are. - A
Datebecomesnew Date(value.getTime()). - An array becomes
value.map(cloneData). - An object whose prototype is
Object.prototypeornullbecomes an ordinary object. Copy its own enumerable keys in order, including keys whose value isundefined. - Anything else throws
TypeError('cloneData: cannot copy a <kind> at <path>').<kind>is the constructor's name, ortypeoffor functions and symbols.<path>is the dot-joined keys and indexes from the root, or(root). - Build the path only while the error unwinds. Don't carry it through every call: this function runs on about 650 KB of state per command.
- Add a two-line doc comment: plain data only, and why it throws.
- Primitives (including
Step 4: Run the tests and see them pass. Run
npx vitest run src/superTabs/cloneData.test.ts. Expected: 4 tests pass.Step 5: Checkpoint.
git status --shortlists only the two new files.
Task 2: Machine reports do not load progress
Files:
- Modify:
backend/src/superTabs/parts/load.ts(loadObserved, and its doc comment) - Create:
backend/integration/profiledReads.test-support.ts - Modify:
backend/integration/superTabCache.test.ts(partReadsuses the shared helper) - Test:
backend/integration/superTabLiveness.test.ts
Interfaces:
Produces:
export async function profiledReads<T>(db: PrismaClient, collections: RegExp, run: () => Promise<T>): Promise<{ value: T; reads: number }>. Move the body ofsuperTabCache.test.ts partReadsinto it unchanged, withcollectionsin place of the fixednsregex. InsuperTabCache.test.ts,partReads(run)becomesprofiledReads(db, /\.Swarm(Head|Member|Agent|Group|Machine|Start|Progress)$/, run). Keep thepartReadsname there as a one-line wrapper so its call sites don't change.Step 1: Write the failing test in
superTabLiveness.test.ts, in a newdescribe('machine reports and report progress'). Use the file'sswarm()helper.it('reads no report progress and leaves its part as it was, also when the report loses a task'):- Post a message in the workgroup:
f.execute({ type: 'message.send', conversationId: f.group, text: 'Parser done', replyTo: null, recipientIds: [] }). - Read the stored part:
before = await db.swarmProgress.findFirst({ where: { tabId: f.tab, deleted: false } }).expect(before).not.toBeNull(). This guards the precondition: the command must have written a progress part. - Run a quiet report,
f.observe('test-host', [f.harness.worker]). This is the tab's first report, so it also runs the liveness sweep. - Move the clock
f.clock.now += 2 * MINUTE + 5_000and reportf.observe('lead-host', [f.harness.lead]). This loses the worker's task and writes parts. - Wrap steps 3 and 4, and nothing else, in
profiledReads(db, /\.SwarmProgress$/, …). Expectreadsto be0. - Outside the profiled block, because a read loads progress, check that
(await f.assignment()).statusis'lost'. - Read the part again as
after. Expectafter!.version,after!.dataandafter!.changedAtto equalbefore!'s.
- Post a message in the workgroup:
Step 2: Run the test and see it fail. Run
npx vitest run --config vitest.super-tabs.config.ts integration/superTabLiveness.test.ts -t "report progress". Expected: it fails onreads(≥ 1, fromloadObserved'sSwarmProgress.findMany).Step 3: Implement. In
loadObserved, passprogress: nulltoassembleinstead ofprogress: live. Add one sentence to its doc comment: a report never reads project progress (only commands and native events note reports), so none is loaded and none is committed.Step 4: Run the tests and see them pass. Run
npx vitest run --config vitest.super-tabs.config.ts integration/superTabLiveness.test.ts integration/superTabCache.test.ts. Expected: the new test passes. Any other failure also appears on cleanmain.Step 5: Checkpoint.
git status --shortadds only this task's four files.
Task 3: visibleState copies a pruned state
Files:
- Modify:
backend/src/superTabs/model.ts(visibleState) - Modify:
backend/src/superTabs/read/fixture.test-support.ts(newfullSwarm) - Modify:
backend/src/superTabs/cloneData.test.ts(addfullSwarmstates) - Create:
backend/src/superTabs/visibleState.test.ts
Interfaces:
Consumes:
cloneData(Task 1).Produces:
export function fullSwarm(now = NOW)infixture.test-support.ts. It returns everythingrichSwarmreturns, plusbuddy(the Buddy agent's id) andbuddyChat(its chat's id).statestays a live getter.Step 1: Add
fullSwarm. It isrichSwarm(now)plus the following. Values that aren't pinned are free.Private project member: run
{ type: 'project.sharing', projectId: s.secret, visibility: 'private', memberIds: [peer.userId] }. Nowpeeris a member of Secret andoutsideris a member outside it.Machine: run
s.contribute('host'). Withs.edit, give its pool anobservation:- shaped like
teamRouting.test.ts's machine builder, withreceivedAt: now; runningHarnessIds: ['worker-harness', 'gone-harness'];harnessTokensfor both harnesses;privacy: { mode: 'account', passed: false, item: 'disk-encryption', detail: '/Users/owner/secret', checkedAt: now, seenAt: now }.
- shaped like
Buddy: with
s.edit, add a Buddy agent forpeerin the Swarm's first project, built the waybuddies.test.ts setup()does it:buddyOf: { personId: peer.userId, generation: <peer's generation in state.people> };machineOwnerId: \${owner.userId}-machine``.
Also add its
kind: 'buddy'chat, withaudienceset to peer.Dormant: set the
s.doneconversation toarchived: true, dormant: true.Progress: give both projects
progress: { since: now, summarizedFloor: 0, summarized: {}, requestedFloor: 0, requested: {} }.The five pruned fields:
sharing: { revision: 1, generation: 'sharing-1', access: { mode: 'invited', role: 'collaborator' } }harnessReservations: [{ machineId: 'host', harnessId: 'worker-harness', generation: 'g1', renewed: false }]releasedHarnesses: [{ machineId: 'host', harnessId: 'old-harness' }]overlapAlerts: ['a:b']closingSessions: [{ agentId: 'removed-agent', machineId: 'host', harnessId: 'old-harness', machineOwnerId: \${owner.userId}-machine` }]`
Step 2: Write the tests in
visibleState.test.ts.Reference. Copy today's
visibleStatebody verbatim,structuredCloneincluded, asvisibleStateBefore(state, actor, now). Import its helpers from their modules; all of them are exported. Header comment: "visibleState before DB roadmap 2.6: the reference for the reader test below. Delete once that PR has merged."Readers. Use the fixture's
owner,peerandoutsider. Also:stranger = { kind: 'person', userId: '100000000000000000000009', email: '[email protected]' };- the Buddy, worker and Lead as agent actors, each with
machineOwnerId: \${owner.userId}-machine``.
it('exercises what it compares'): guards that the fixture covers each case.- Before reading, the input state has all five pruned fields and a dormant conversation.
visibleStateBeforeforownerreturns a project withprogress.- It returns the Secret project for
peerbut not foroutsider. - For the Buddy, it returns
machinesas[].
it.each(readers)('reads the same as before for %s'): for each named reader, check bothexpect(visibleState(s.state, actor, NOW)).toStrictEqual(visibleStateBefore(s.state, actor, NOW));expect(JSON.stringify(visibleState(…))).toBe(JSON.stringify(visibleStateBefore(…))).
For
stranger, both functions throw an error with the samecode.it('reads a frozen, shared state as before and leaves it untouched'): deep-copyfullSwarm().statewithstructuredClone, thenfreezeit fromcache.js. Forownerand the worker, the output matchesvisibleStateBeforeon an unfrozen copy.it('fails loudly on a value it cannot copy'):visibleState({ ...s.state, stray: new Map() } as never, owner, NOW)throws/cannot copy a Map at stray/.
Step 3: Run the tests. Run
npx vitest run src/superTabs/visibleState.test.ts. Expected: every reader test passes, because the old body is still in place. Onlyfails loudly…fails, becausestructuredClonecopies aMap.Step 4: Implement. At the top of
visibleState, right afterauthor(state, actor):- Destructure the five pruned fields out of
statewith_-prefixed names, asparts/shape.ts splitdoes withprogress. - Set
visible = cloneData({ ...kept, conversations: state.conversations.filter(c => !c.dormant) }). Becauseconversationsis already a key ofkept, it keeps its key position. - Delete the later
visible.conversations = visible.conversations.filter(c => !c.dormant)line and the fivedelete visible.<field>lines. Move their comments, including theclosingSessionsone, onto the prune.
Leave every other line and its order unchanged, including
projects[].progress.- Destructure the five pruned fields out of
Step 5: Add
fullSwarm().statetocloneData.test.ts's fixture states. Also add its reassembled form.Step 6: Run the tests and see them pass. Run
npx vitest run src/superTabs/visibleState.test.ts src/superTabs/cloneData.test.ts src/superTabs/read src/superTabs/buddies.test.ts src/superTabs/profile.test.ts src/superTabs/terminal.test.ts. Expected: all pass. Any other failure also appears on cleanmain.Step 7: Checkpoint.
git status --shortadds only this task's files.
Task 4: cloneData for the remaining whole-state copies
Files:
- Modify:
backend/src/superTabs/commands.ts(applyCommand) - Modify:
backend/src/superTabs/native.ts(append) - Modify:
backend/src/superTabs/store.ts. The methods aresetWorkspaceVisibility,workspaceJoin,saveSharing,join,observeMachine,fullDeliveries,postReflection,archiveFinishedandstopped.stoppedhas two copies:state, andbefore.conversations. - Test:
backend/src/superTabs/commands.test.ts
Interfaces:
Consumes:
cloneData(Task 1).Step 1: Write the failing test in
commands.test.ts:it('fails loudly on a state value it cannot copy'):applyCommand({ ...richSwarm().state, stray: new Map() } as never, owner, { type: 'message.send', conversationId: 'lead', text: 'hi', replyTo: null, recipientIds: [] }, { now: NOW, operationId: 'op' }). Useowner,richSwarmandNOWfromread/fixture.test-support.ts.- Expected: throws
/cannot copy a Map at stray/.
Step 2: Run it and see it fail. Run
npx vitest run src/superTabs/commands.test.ts -t "cannot copy". Expected: FAIL, because nothing throws.Step 3: Implement. Replace
structuredClonewithcloneDatain the methods listed above.Keep
structuredCloneon single values:commands.ts: the command copy,previousAttemptsandconfiguration;autoReview.ts:configuration.
Don't touch
parts/shape.tsormigration/: those are migration and rollback paths, outside the spec.Step 4: Verify that no whole-state copy is left. Run
grep -n "structuredClone(\(original\|loaded.state\|state.conversations\|state\))" src/superTabs/*.ts. Expected: no output.Step 5: Run the tests and see them pass. Run these together:
npm run typecheck;npx vitest run src/superTabs;npx vitest run --config vitest.super-tabs.config.ts, the full Super Tab integration suite. The replaced copies sit on every write path.
Expected: typecheck is clean. Each failing test also fails, by the same name, on clean
main.Step 6: Checkpoint.
git status --shortadds onlycommands.ts,native.ts,store.tsandcommands.test.ts.
Task 5: Report
Step 1: Write the report for Ken with:
- the plan's path;
- each test command run, with its pass/fail counts, and which failures also fail on clean
main; git diff --statand a one-line summary per file;- the spec corrections below.
Then wait for Ken before committing or pushing.
Spec corrections found while planning
- Line numbers have moved since 2bbcad4c4.
noteProjectReportsis now called atstore.ts:1382, not 1347.observeMachine's copy is atstore.ts:2342. The other store copies are at 886, 902, 949, 983, 2596, 2822, 2883, 2937 and 2938. This plan names methods instead of lines. - The spec's "a bench Swarm" for the
cloneDatatest can't run in a unit test: the bench starts its own Mongo replica set and seeds through the store. Task 1 builds a Swarm of the bench's default size (200 groups, 20 workers) from the read fixture instead. - The spec's per-reader test asks for deep equality. This plan also compares JSON bytes, because deep equality ignores key order and replies are serialized (Review Focus 2).