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
perf(swarm): copy less Swarm state per request (DB roadmap 2.6)
MAC4525e62aad92
diff --git a/backend/integration/profiledReads.test-support.ts b/backend/integration/profiledReads.test-support.tsnew file mode 100644index 000000000..19452a781--- /dev/null+++ b/backend/integration/profiledReads.test-support.ts@@ -0,0 +1,15 @@+import type { PrismaClient } from '@prisma/client'++/** The operations MongoDB served on the collections `collections` matches while `run` ran (its profiler, every operation). */+export async function profiledReads<T>(db: PrismaClient, collections: RegExp, run: () => Promise<T>): Promise<{ value: T; reads: number }> {+ await db.$runCommandRaw({ profile: 2 })+ const since = new Date()+ try {+ const value = await run()+ const rows = await db.$runCommandRaw({ find: 'system.profile', filter: { ts: { $gte: { $date: since.toISOString() } },+ ns: { $regex: collections.source } } }) as { cursor: { firstBatch: unknown[] } }+ return { value, reads: rows.cursor.firstBatch.length }+ } finally {+ await db.$runCommandRaw({ profile: 0 })+ }+}diff --git a/backend/integration/superTabCache.test.ts b/backend/integration/superTabCache.test.tsindex 7c9965c19..15dedd522 100644--- a/backend/integration/superTabCache.test.ts+++ b/backend/integration/superTabCache.test.ts@@ -21,6 +21,7 @@ import { migrateSwarm } from '../src/superTabs/migration/migrate.js'import type { SuperTabState } from '../src/superTabs/model.js'import { writeLegacySwarm } from '../scripts/swarm-parts/legacy.js'import { outsider as outsiderActor, owner as ownerActor, peer as peerActor, richSwarm } from '../src/superTabs/read/fixture.test-support.js'+import { profiledReads } from './profiledReads.test-support.js'// The per-process Swarm cache (superTabs/cache.ts, Stability Roadmap 2.2) on a fresh loopback replica set; Redis is// MemoryStamps, one store of stamps every "pod" here shares. This suite never reads DATABASE_URL or an existing database.@@ -145,18 +146,7 @@ async function privateScene() {const groupKeys = (read: { groups: Array<{ key: string }> }) => read.groups.map(g => g.key)/** The part collections' reads MongoDB served while `run` ran (its profiler, every operation). */-async function partReads<T>(run: () => Promise<T>): Promise<{ value: T; reads: number }> {- await db.$runCommandRaw({ profile: 2 })- const since = new Date()- try {- const value = await run()- const rows = await db.$runCommandRaw({ find: 'system.profile', filter: { ts: { $gte: { $date: since.toISOString() } },- ns: { $regex: '\\.Swarm(Head|Member|Agent|Group|Machine|Start|Progress)$' } } }) as { cursor: { firstBatch: unknown[] } }- return { value, reads: rows.cursor.firstBatch.length }- } finally {- await db.$runCommandRaw({ profile: 0 })- }-}+const partReads = <T>(run: () => Promise<T>) => profiledReads(db, /\.Swarm(Head|Member|Agent|Group|Machine|Start|Progress)$/, run)describe('reads through the cache', () => {it('reads a Swarm whose stamp did not move without asking Mongo for its parts', async () => {diff --git a/backend/integration/superTabLiveness.test.ts b/backend/integration/superTabLiveness.test.tsindex 30539bb1f..a0f783cb2 100644--- a/backend/integration/superTabLiveness.test.ts+++ b/backend/integration/superTabLiveness.test.ts@@ -15,6 +15,7 @@ import type { MachineObservation } from '../src/superTabs/machines.js'import * as parts from '../src/superTabs/parts/index.js'import { assignmentRows, poolRows, rosterRows } from './hostRows.test-support.js'import { beforeFirstWrite } from './interleave.test-support.js'+import { profiledReads } from './profiledReads.test-support.js'import { SwarmReads } from '../src/superTabs/read/service.js'// Work never sits with a dead owner: an active assignment whose agent died, stalled or hit a limit becomes lost within@@ -779,6 +780,29 @@ describe('a machine\'s report', () => {})})+// A report never reads its projects' report progress (projectUpdates.ts): only commands and native events note reports.+describe('machine reports and report progress', () => {+ it('reads no report progress and leaves its part as it was, also when the report loses a task', async () => {+ const f = await swarm()+ await f.execute({ type: 'message.send', conversationId: f.group, text: 'Parser done', replyTo: null, recipientIds: [] })+ const before = await db.swarmProgress.findFirst({ where: { tabId: f.tab, deleted: false } })+ expect(before).not.toBeNull()+ const { reads } = await profiledReads(db, /\.SwarmProgress$/, async () => {+ // The tab's first report, so it runs the liveness sweep too.+ await f.observe('test-host', [f.harness.worker])+ // The worker's machine is silent past its grace: this report loses its task and writes the group and the agent.+ f.clock.now += 2 * MINUTE + 5_000+ await f.observe('lead-host', [f.harness.lead])+ })+ expect(reads).toBe(0)+ expect((await f.assignment()).status).toBe('lost')+ const after = await db.swarmProgress.findFirst({ where: { tabId: f.tab, deleted: false } })+ expect(after!.version).toBe(before!.version)+ expect(after!.data).toEqual(before!.data)+ expect(after!.changedAt).toEqual(before!.changedAt)+ })+})+// After a release every machine went offline for about 2 minutes while its CLI updated: 16 tasks were lost, their agents came// back, and every assignment to the same agent was refused as busy for good, even after the Lead cancelled the lost task.describe('an agent whose task was lost', () => {diff --git a/backend/src/superTabs/cloneData.test.ts b/backend/src/superTabs/cloneData.test.tsnew file mode 100644index 000000000..f02b3e533--- /dev/null+++ b/backend/src/superTabs/cloneData.test.ts@@ -0,0 +1,87 @@+import { describe, expect, it } from 'vitest'+import { freeze } from './cache.js'+import { cloneData } from './cloneData.js'+import { reassemble, split } from './parts/index.js'+import { fullSwarm, NOW, richSwarm, swarm } from './read/fixture.test-support.js'+import type { SuperTabState } from './model.js'++const isObject = (value: unknown): value is object => typeof value === 'object' && value !== null++/** Fails if any object is reached twice: on such a value a plain copy and structuredClone would differ. */+function reachedOnce(value: unknown, seen = new Set<object>(), path = '(root)'): void {+ if (!isObject(value)) return+ if (seen.has(value)) throw new Error(`reached twice at ${path}`)+ seen.add(value)+ for (const [key, item] of Object.entries(value)) reachedOnce(item, seen, `${path}.${key}`)+}++/** Fails if the copy holds any object of the source at the same place. */+function sharesNothing(source: unknown, copy: unknown, path = '(root)'): void {+ if (!isObject(source)) return+ if (source === copy) throw new Error(`shared at ${path}`)+ for (const [key, item] of Object.entries(source)) sharesNothing(item, (copy as Record<string, unknown>)[key], `${path}.${key}`)+}++/** The bench's default Swarm size (integration/bench/README.md): 200 groups and 20 workers, each working on one. */+function benchSized(): SuperTabState {+ const s = swarm()+ s.add('lead-harness', 'lead', true)+ const groups = Array.from({ length: 200 }, (_, i) => s.group(`Group ${i}`))+ for (let i = 0; i < 20; i++) {+ const worker = s.add(`worker-${i}`, groups[i]!)+ s.run({ type: 'work.assign', conversationId: groups[i]!, agentId: worker })+ }+ return s.state+}++const states = (): Array<[string, SuperTabState]> => [+ ['the rich fixture', richSwarm().state],+ ['a bench-sized Swarm', benchSized()],+ ['a reassembled state', reassemble(split(richSwarm().state, { tabId: 'tab', version: 1, now: NOW }), { share: true })],+ ['the full fixture', fullSwarm().state],+ ['the full fixture reassembled', reassemble(split(fullSwarm().state, { tabId: 'tab', version: 1, now: NOW }), { share: true })],+]++describe('cloneData', () => {+ it('copies every fixture state as structuredClone does, sharing nothing', () => {+ for (const [name, state] of states()) {+ expect(() => reachedOnce(state), name).not.toThrow()+ const copy = cloneData(state)+ expect(copy, name).toStrictEqual(structuredClone(state))+ expect(() => sharesNothing(state, copy), name).not.toThrow()+ }+ })++ it('keeps undefined values and copies a Date as a new Date', () => {+ const input = { a: undefined, at: new Date(NOW), list: [1, 'x', null, true] }+ const copy = cloneData(input)+ expect(copy).toStrictEqual(input)+ expect('a' in copy).toBe(true)+ expect(copy.at).toBeInstanceOf(Date)+ expect(copy.at).not.toBe(input.at)+ expect(copy.at.getTime()).toBe(NOW)+ })++ it('keeps an own __proto__ key as a key, as structuredClone does', () => {+ const input = JSON.parse('{"x":{"__proto__":{"p":1},"ok":2}}') as { x: Record<string, unknown> }+ const copy = cloneData(input)+ expect(JSON.stringify(copy)).toBe(JSON.stringify(structuredClone(input)))+ expect(Object.getPrototypeOf(copy.x)).toBe(Object.prototype)+ })++ it('returns a writable copy of frozen data', () => {+ const frozen = structuredClone(richSwarm().state)+ freeze(frozen)+ const copy = cloneData(frozen)+ expect(Object.isFrozen(copy)).toBe(false)+ expect(Object.isFrozen(copy.conversations[0])).toBe(false)+ expect(() => { copy.conversations[0]!.title = 'changed' }).not.toThrow()+ })++ it('throws on values it cannot copy, naming where they are', () => {+ expect(() => cloneData({ agents: [{ extra: new Map() }] })).toThrow(/cannot copy a Map at agents\.0\.extra/)+ expect(() => cloneData({ s: new Set() })).toThrow(/cannot copy a Set at s/)+ expect(() => cloneData({ c: new (class Thing {})() })).toThrow(/cannot copy a Thing at c/)+ expect(() => cloneData({ f: () => 1 })).toThrow(/cannot copy a function at f/)+ })+})diff --git a/backend/src/superTabs/cloneData.ts b/backend/src/superTabs/cloneData.tsnew file mode 100644index 000000000..93de0542a--- /dev/null+++ b/backend/src/superTabs/cloneData.ts@@ -0,0 +1,48 @@+/** A deep copy of plain data (objects, arrays, primitives, Dates), faster than `structuredClone` on Swarm state. Any other+ * value (a Map, Set, class instance or function) throws with its path, so a new kind of value fails loudly, never mangled. */+export function cloneData<T>(value: T): T {+ try {+ return copy(value)+ } catch (error) {+ if (error !== UNCOPYABLE) throw error+ const found = uncopyable(value, [])!+ throw new TypeError(`cloneData: cannot copy a ${found.kind} at ${found.path.join('.') || '(root)'}`)+ }+}++/** Thrown while copying; the path is found afterwards, so a successful copy never pays for it. */+const UNCOPYABLE = Symbol('uncopyable')++const plain = (value: object): boolean => {+ const prototype = Object.getPrototypeOf(value)+ return prototype === Object.prototype || prototype === null+}++function copy<T>(value: T): T {+ if (typeof value !== 'object' || value === null) {+ if (typeof value === 'function' || typeof value === 'symbol') throw UNCOPYABLE+ return value+ }+ if (Array.isArray(value)) return value.map(copy) as T+ if (value instanceof Date) return new Date(value.getTime()) as T+ if (!plain(value)) throw UNCOPYABLE+ const out: Record<string, unknown> = {}+ for (const key of Object.keys(value)) {+ const item = copy((value as Record<string, unknown>)[key])+ // An own `__proto__` key stays a key: assigned, it would set the copy's prototype instead.+ if (key === '__proto__') Object.defineProperty(out, key, { value: item, enumerable: true, writable: true, configurable: true })+ else out[key] = item+ }+ return out as T+}++function uncopyable(value: unknown, path: string[]): { kind: string; path: string[] } | null {+ if (typeof value === 'function' || typeof value === 'symbol') return { kind: typeof value, path }+ if (typeof value !== 'object' || value === null || value instanceof Date) return null+ if (!Array.isArray(value) && !plain(value)) return { kind: value.constructor?.name || 'object', path }+ for (const [key, item] of Object.entries(value)) {+ const found = uncopyable(item, [...path, key])+ if (found) return found+ }+ return null+}diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.tsindex 165a7b517..21ca71636 100644--- a/backend/src/superTabs/commands.test.ts+++ b/backend/src/superTabs/commands.test.ts@@ -8,6 +8,7 @@ import type { RouteDecision } from './routeRecord.js'import { startFinished } from './parts/write.js'import { agentTarget, broken } from './rules.js'import { DEFAULT_ROUTING_POLICY, effectivePolicy } from './routingPolicy.js'+import { NOW, owner as richOwner, richSwarm } from './read/fixture.test-support.js'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]' }@@ -4134,3 +4135,11 @@ describe('a settling start names the model its agent runs', () => {expect(() => commandSchema.parse({ type: 'agent.startSettled', startId, warning: null, model: 'gpt-6.1-sol' })).toThrow()})})++describe('the state a command works on', () => {+ it('fails loudly on a state value it cannot copy', () => {+ expect(() => applyCommand({ ...richSwarm().state, stray: new Map() } as never, richOwner,+ { type: 'message.send', conversationId: 'lead', text: 'hi', replyTo: null, recipientIds: [] }, { now: NOW, operationId: 'op' }))+ .toThrow(/cannot copy a Map at stray/)+ })+})diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 6a6f698ca..f1f38223e 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -23,6 +23,7 @@ import { reviewCapacityNotice } from './reviewCapacity.js'import { digestStartsAfter, knownTimeZone } from './digest.js'import { credentialResult, redactCredentials, type CredentialKind } from './credentials.js'import { dirtyGroups, reportGroups, summarize } from './projectUpdates.js'+import { cloneData } from './cloneData.js'import { workspaceCan, type WorkspaceRole } from './workspaces.js'import { fixedOriginal, LEDGER_WEEKS, PULL_REQUEST_URL, recordAsked, recordFix, recordDecision, recordMerged, recordPost, recordProposal, recordReview, recordRun, recordStatus,recordReportedModel, recordVerdict } from './leaderboard/record.js'@@ -570,7 +571,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma// (Oct 2026: a Harness access token in a shared Lead chat). The sender's result says what went.const removed: CredentialKind[] = []const command = withoutCredentials(commandSchema.parse(input), removed)- const state = structuredClone(original)+ const state = cloneData(original)syncLeads(state)numberConversations(state)placeRules(state)diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex 846da2e38..2336be2ec 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -1,4 +1,5 @@import { createHash } from 'node:crypto'+import { cloneData } from './cloneData.js'import { lostReasonWithoutMachine } from './lostReason.js'import type { RouteDecisionEffect } from './routeRecord.js'import { agentDisplayName, assignAgentDisplayNames } from './agentNames.js'@@ -658,14 +659,18 @@ export function createSuperTab(id: string, name: string, owner: { id: string; em/** Pending invitations are management data, not part of the shared conversation. */export function visibleState(state: SuperTabState, actor: Actor, now = Date.now()): SuperTabState {author(state, actor)- const visible = structuredClone(state)+ // The copy leaves out what no reader gets and no step below reads: the owner-only sharing, the hosts' slot claims, released+ // and closing sessions (only that machine's host roster lists them: read/hostRows.ts; a removed private agent's session is+ // not every member's), and overlap alerts. Nor a dormant conversation: it is read on demand, never in a whole-Swarm read+ // (spec, Archive); a command may still load one.+ const { sharing: _sharing, harnessReservations: _reservations, releasedHarnesses: _released, overlapAlerts: _alerts, closingSessions: _closing,+ ...kept } = state+ const visible = cloneData({ ...kept, conversations: state.conversations.filter(c => !c.dormant) })// A Buddy-only machine is no machine of the Swarm to anyone, its own person included (machines.ts buddyOnly): their Buddy// shows as a Buddy, and their machine stays theirs. Machines, status and the leaderboard's lent hours all read this.if (visible.machines) visible.machines = visible.machines.filter(m => !m.buddyOnly)// Nor its id, which a Buddy's row carries (machineHiddenFrom).visible.agents = visible.agents.map(a => machineHiddenFrom(state, actor, a) ? agentWithoutMachine(a) : a)- // A dormant conversation is read on demand, never in a whole-Swarm read (spec, Archive); a command may still load one.- visible.conversations = visible.conversations.filter(c => !c.dormant)syncLeads(visible)// People and Leads read the Leads conversation; it is not there for any other agent.if (actor.kind === 'agent' && !ledProject(visible, actor.agentId)) {@@ -682,12 +687,6 @@ export function visibleState(state: SuperTabState, actor: Actor, now = Date.now(if (target.limitedUntil && Date.parse(target.limitedUntil) <= now) target.limitedUntil = null}visible.buddies = true- delete visible.sharing- delete visible.harnessReservations- delete visible.releasedHarnesses- delete visible.overlapAlerts- // Only that machine's host roster lists them (read/hostRows.ts); a removed private agent's session is not every member's.- delete visible.closingSessions// A failing privacy check's detail is its contributor's: an error from the check can name paths on their Mac. Everyone// else reads which item failed (machines.ts teamWorkRefusal).for (const pool of visible.machines ?? []) {diff --git a/backend/src/superTabs/native.ts b/backend/src/superTabs/native.tsindex 3f15cb911..fc62b3142 100644--- a/backend/src/superTabs/native.ts+++ b/backend/src/superTabs/native.ts@@ -8,6 +8,7 @@ import { activeWork, agent, appendPullRequestUrls, author, conversation, fail, iimport { accessInputs, canReadGroup, groupProject, readConversation, watchersLost } from './projects.js'import { mayDrive } from './terminal.js'import { noteProjectReports } from './projectUpdates.js'+import { cloneData } from './cloneData.js'import { numberMessages, type Touch } from './parts/commit.js'import { redactCredentials } from './credentials.js'import type { DeliveriesWaiting } from './store.js'@@ -201,7 +202,7 @@ export class SuperTabNativeStore {const event = nativeEventSchema.parse(input)return this.deps.transaction(async tx => {const { loaded, record, binding, team } = await this.hosted(tx, user, tabId, contextId)- const state = structuredClone(loaded.state)+ const state = cloneData(loaded.state)const target = agent(state, record.agentId), group = conversation(state, record.conversationId)const eventId = stableId('native-event', contextId, event.turnId, event.kind), requestHash = digest(event)const prior = await tx.superTabOperation.findUnique({ where: { id: eventId } })diff --git a/backend/src/superTabs/parts/load.ts b/backend/src/superTabs/parts/load.tsindex 27d32329e..76de6c052 100644--- a/backend/src/superTabs/parts/load.ts+++ b/backend/src/superTabs/parts/load.ts@@ -72,11 +72,12 @@ export function loadActive(tx: Transaction, tabId: string,* checks read, whole, since it may write them: running work, the Lead conversations, the unfinished starts' conversations,* the conversations of agents stored with no project (projects.ts agentProjectId), and the private chats of this machine's* working agents (leaderboard/lent.ts accrueLent). A busy Swarm's finished conversations, briefs and checks were ~1.1 MB- * read every 15 s per machine; the commit compares only what was loaded, so the others stay as they are.+ * read every 15 s per machine; the commit compares only what was loaded, so the others stay as they are. No project's report+ * progress either: only commands and native events note reports (projectUpdates.ts), so none is loaded or committed.*/export async function loadObserved(tx: Transaction, tabId: string, machineId: string): Promise<SwarmParts> {const live = { deleted: false }- const loaded = await assemble(tx, tabId, { member: live, agent: live, machine: live, progress: live, start: { ...live, finishedAt: null }, group: [] })+ const loaded = await assemble(tx, tabId, { member: live, agent: live, machine: live, progress: null, start: { ...live, finishedAt: null }, group: [] })const { projects, leadsConversationId } = loaded.head.data!// A head that never stored the Leads conversation's id finds it where model.ts syncLeads would make it.const leads = [...projects ? projects.map(p => p.leadConversationId) : ['lead'], leadsConversationId ?? stableId(tabId, 'leads')]diff --git a/backend/src/superTabs/read/fixture.test-support.ts b/backend/src/superTabs/read/fixture.test-support.tsindex cee1a84a3..be5fe165a 100644--- a/backend/src/superTabs/read/fixture.test-support.ts+++ b/backend/src/superTabs/read/fixture.test-support.ts@@ -1,6 +1,7 @@/** Test support only: a Swarm built through real commands, for the read views and the migration tests. */import { applyCommand, type Command, type CommandContext } from '../commands.js'import { createSuperTab, type Actor, type AgentConfiguration, type SuperTabState } from '../model.js'+import { buddyChatId } from '../buddies.js'export const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: '100000000000000000000001', email: '[email protected]' }export const peer: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: '100000000000000000000002', email: '[email protected]' }@@ -47,3 +48,41 @@ export function richSwarm(now = NOW) {// Not a spread: `state` stays a live getter.return Object.assign(s, { lead, worker, secret, web, done, secretGroup, assignmentId })}++/** `richSwarm`, plus everything `visibleState` filters or drops: peer in the private project, a machine whose reading lists a+ * gone session and a failed privacy check, peer's Buddy and its chat, a dormant conversation, report progress, and the+ * owner-only and host-only records (sharing, reservations, released and closing sessions, overlap alerts). */+export function fullSwarm(now = NOW) {+ const s = richSwarm(now)+ s.run({ type: 'project.sharing', projectId: s.secret, visibility: 'private', memberIds: [peer.userId] })+ s.contribute('host')+ const machineOwnerId = `${owner.userId}-machine`+ // A function, not one object: a stored state never holds one object twice (cloneData.test.ts reachedOnce).+ const tokens = () => ({ 'test-model': { input: 10, output: 5, cacheRead: 0, cacheWrite: 0 } })+ s.edit(state => {+ state.machines!.find(m => m.machineId === 'host')!.observation = { generation: 'g1', receivedAt: now, sessionKind: 'team',+ resources: { cpuPercent: 1, memoryTotalBytes: 8, memoryUsedBytes: 1, diskFreeBytes: 8, diskTotalBytes: 8, projectDiskFreeBytes: 8,+ deviceType: null, chip: null, os: null, gpuPercent: null },+ tools: {}, quotas: [], runningHarnessIds: ['worker-harness', 'gone-harness'], stoppedHarnessIds: [],+ harnessTokens: { 'worker-harness': tokens(), 'gone-harness': tokens() },+ privacy: { mode: 'account', passed: false, item: 'disk-encryption', detail: '/Users/owner/secret', checkedAt: now, seenAt: now } }+ })+ const generation = s.state.people.find(p => p.id === peer.userId)!.generation+ const projectId = s.state.projects![0]!.id+ const buddy = 'buddy', buddyChat = buddyChatId(projectId, { id: peer.userId, generation })+ s.edit(state => {+ state.agents.push({ id: buddy, projectId, machineId: 'host', harnessId: 'buddy-harness', machineOwnerId, contributorId: peer.userId,+ membershipGeneration: generation, name: 'Buddy', configuration: config, buddyOf: { personId: peer.userId, generation } })+ state.conversations.push({ id: buddyChat, kind: 'buddy', projectId, title: 'Buddy', leadId: null, agentIds: [buddy], archived: false,+ brief: '', checks: [], assignment: null, lastMessageSequence: 0, audience: { people: [{ id: peer.userId, generation }] } })+ Object.assign(state.conversations.find(c => c.id === s.done)!, { archived: true, dormant: true })+ for (const project of state.projects!) project.progress = { since: now, summarizedFloor: 0, summarized: {}, requestedFloor: 0, requested: {} }+ state.sharing = { revision: 1, generation: 'sharing-1', access: { mode: 'invited', role: 'collaborator' } }+ state.harnessReservations = [{ machineId: 'host', harnessId: 'worker-harness', generation: 'g1', renewed: false }]+ state.releasedHarnesses = [{ machineId: 'host', harnessId: 'old-harness' }]+ state.overlapAlerts = ['a:b']+ state.closingSessions = [{ agentId: 'removed-agent', machineId: 'host', harnessId: 'old-harness', machineOwnerId }]+ })+ // Not a spread: `state` stays a live getter.+ return Object.assign(s, { buddy, buddyChat })+}diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 02a94c84c..a3ba7b053 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -30,6 +30,7 @@ import { lostReasonWithoutMachine } from './lostReason.js'import { LEAD_NAME } from './leadStart.js'import { confidentialSessions, otherRegistrations, recordConfidential } from './confidential.js'import { answersRequest, dirtyGroups, noteProjectReports, projectUpdateRequest, UNANSWERED_REQUEST_MS } from './projectUpdates.js'+import { cloneData } from './cloneData.js'import { digestDue, digestMessageId, digestRequest, digestSince } from './digest.js'import { judgedMachines, loseTasks, sweepForLead, sweepLiveness, SWEEP_EVERY_MS, unpurgedNotice } from './liveness.js'import { archivable, archiveLine, ASLEEP_FIELDS, asleepMatch, reviewClosable, reviewCloseLine, reviewPullRequests, stopIdleWorkers, stoppedMachines, type GroupActivity } from './tidy.js'@@ -884,7 +885,7 @@ export class SuperTabStore {async setWorkspaceVisibility(user: AuthUser, tabId: string, visibility: 'invite-only' | 'workspace') {this.personOnly(user)return transaction(this.db, async tx => {- const loaded = await this.load(tx, user, tabId), state = structuredClone(loaded.state)+ const loaded = await this.load(tx, user, tabId), state = cloneData(loaded.state)await outsiderRefusal(state, user.sub, async () => {if (!state.workspaceId) fail('WORKSPACE_REQUIRED', `This Swarm has no ${WORKSPACE_LABEL} yet.`, 409)const own = await tx.swarmWorkspaceMember.findUnique({ where: { id: memberId(state.workspaceId, user.sub) } })@@ -900,7 +901,7 @@ export class SuperTabStore {async workspaceJoin(user: AuthUser, tabId: string, operationId: string) {this.personOnly(user)return transaction(this.db, async tx => {- const loaded = await this.load(tx, user, tabId), state = structuredClone(loaded.state)+ const loaded = await this.load(tx, user, tabId), state = cloneData(loaded.state)await outsiderRefusal(state, user.sub, async () => {if (!state.workspaceId || state.workspaceVisibility !== 'workspace') fail('FORBIDDEN', 'This Swarm is not open to its Workspace.', 403)await requireWorkspaceRole(tx, state.workspaceId, user.sub, 'swarm.joinOpen')@@ -947,7 +948,7 @@ export class SuperTabStore {this.personOnly(user)const request = saveSharingSchema.parse(input)return transaction(this.db, async tx => {- const loaded = await this.load(tx, user, tabId), state = structuredClone(loaded.state)+ const loaded = await this.load(tx, user, tabId), state = cloneData(loaded.state)requireSharingOwner(state, user.sub)const receiptId = stableId('swarm-sharing', tabId, user.sub, request.operationId), requestHash = hash(request)const prior = await tx.superTabOperation.findUnique({ where: { id: receiptId } })@@ -981,7 +982,7 @@ export class SuperTabStore {this.personOnly(user)const request = joinSwarmSchema.parse(input)return transaction(this.db, async tx => {- const loaded = await this.load(tx, user, tabId), state = structuredClone(loaded.state)+ const loaded = await this.load(tx, user, tabId), state = cloneData(loaded.state)// Recheck the current grant before an old receipt. Disabling, replacing, or// changing access can never revive a removed membership through a retry.const sharing = authorizeSwarmJoin(state, user.email, request.token)@@ -2418,7 +2419,7 @@ export class SuperTabStore {const owned = await tx.machine.findFirst({ where: { machineId, userId: user.sub, autonomousEnv: user.autonomousEnv, ...machineAlive } })await this.hostFor(tx, user, machineId, owned)// Only the conversations its checks read (parts/load.ts loadObserved): the whole Swarm was ~1.1 MB a report (#876).- const loaded = loadedFrom(await this.row(tx, user, tabId), await loadObserved(tx, tabId, machineId)), state = structuredClone(loaded.state)+ const loaded = loadedFrom(await this.row(tx, user, tabId), await loadObserved(tx, tabId, machineId)), state = cloneData(loaded.state)await this.hostFor(tx, user, machineId, owned, state)const pool = await strangerRefusal(state, user.sub, () => {const found = machineContribution(state, machineId)@@ -2672,7 +2673,7 @@ export class SuperTabStore {const groupIds = [...new Set([...finished.map(g => g.key), ...asked.map(d => d.conversationId)])]if (groupIds.length) loaded = await this.ensure(tx, loaded, { groupIds })}- const state = structuredClone(loaded.state)+ const state = cloneData(loaded.state)if (sentAlready) {const project = projectOf(state, led!.id)project.digest = { ...project.digest!, lastOn: due! }@@ -2898,7 +2899,7 @@ export class SuperTabStore {const row = await tx.superTab.findUnique({ where: { id: tabId }, select: SWARM_ROW })if (!row) return 'skipped'const loaded = await loadRow(tx, requireParts(row), { groupIds: [at.chat.id] })- const state = structuredClone(loaded.state)+ const state = cloneData(loaded.state)const place = reflectionPlace(state, projectId)if (!place) return 'skipped'const { project, chat, lead } = place@@ -2959,7 +2960,7 @@ export class SuperTabStore {return transaction(this.db, async tx => {const row = await tx.superTab.findUnique({ where: { id: tabId }, select: SWARM_ROW })if (!row) return false- const loaded = await loadRow(tx, requireParts(row), { groupIds: reviewOf ? [groupId, reviewOf] : [groupId] }), state = structuredClone(loaded.state)+ const loaded = await loadRow(tx, requireParts(row), { groupIds: reviewOf ? [groupId, reviewOf] : [groupId] }), state = cloneData(loaded.state)const group = state.conversations.find(c => c.id === groupId)const now = this.now()if (!group) return false@@ -3013,8 +3014,8 @@ export class SuperTabStore {let ended: WorkHold[] = []const done = await transaction(this.db, async tx => {ended = []- const loaded = await this.load(tx, user, tabId), state = structuredClone(loaded.state)- const before = { agents: state.agents, conversations: structuredClone(state.conversations) }+ const loaded = await this.load(tx, user, tabId), state = cloneData(loaded.state)+ const before = { agents: state.agents, conversations: cloneData(state.conversations) }const group = state.conversations.find(c => c.assignment?.id === assignmentId)const assignment = await strangerRefusal(state, user.sub, () => {const found = group?.assignmentdiff --git a/backend/src/superTabs/visibleState.test.ts b/backend/src/superTabs/visibleState.test.tsnew file mode 100644index 000000000..b4f299e84--- /dev/null+++ b/backend/src/superTabs/visibleState.test.ts@@ -0,0 +1,166 @@+import { describe, expect, it } from 'vitest'+import { freeze } from './cache.js'+import { agentForBuddy, agentWithoutMachine, author, awaitingWorkers, groupWithoutMachines, isLeads, machineHiddenFrom, numberConversations,+ otherProjectsWork, seenMachineIds, syncLeads, visibleState, withSeenRequirement, type Actor, type Agent, type Person, type SuperTabState } from './model.js'+import { assignAgentDisplayNames } from './agentNames.js'+import { withAvatarView } from './profile.js'+import { swarmUsernames } from './usernames.js'+import { downSince, expireRemovals, startPreparing } from './machines.js'+import { publicReason, readsRawReason } from './startFailure.js'+import { agentProjectId, agentSetRole, canReadAgent, canReadGroup, canReadProject, ledProject, placeRules, projectsOf, skillSetOf } from './projects.js'+import { fullSwarm, NOW, outsider, owner, peer } from './read/fixture.test-support.js'++// visibleState before DB roadmap 2.6: the reference for the reader test below. Delete once that PR has merged.+function visibleStateBefore(state: SuperTabState, actor: Actor, now = Date.now()): SuperTabState {+ author(state, actor)+ const visible = structuredClone(state)+ // A Buddy-only machine is no machine of the Swarm to anyone, its own person included (machines.ts buddyOnly): their Buddy+ // shows as a Buddy, and their machine stays theirs. Machines, status and the leaderboard's lent hours all read this.+ if (visible.machines) visible.machines = visible.machines.filter(m => !m.buddyOnly)+ // Nor its id, which a Buddy's row carries (machineHiddenFrom).+ visible.agents = visible.agents.map(a => machineHiddenFrom(state, actor, a) ? agentWithoutMachine(a) : a)+ // A dormant conversation is read on demand, never in a whole-Swarm read (spec, Archive); a command may still load one.+ visible.conversations = visible.conversations.filter(c => !c.dormant)+ syncLeads(visible)+ // People and Leads read the Leads conversation; it is not there for any other agent.+ if (actor.kind === 'agent' && !ledProject(visible, actor.agentId)) {+ visible.conversations = visible.conversations.filter(c => !isLeads(c))+ delete visible.leadsConversationId+ }+ assignAgentDisplayNames(visible.agents)+ const led = actor.kind === 'agent' ? ledProject(visible, actor.agentId) : undefined+ if (led) visible.otherProjectsWork = otherProjectsWork(visible, led)+ for (const target of visible.agents) {+ const since = downSince(state, target, now)+ if (since) target.downSince = since+ delete target.downNamed+ if (target.limitedUntil && Date.parse(target.limitedUntil) <= now) target.limitedUntil = null+ }+ visible.buddies = true+ delete visible.sharing+ delete visible.harnessReservations+ delete visible.releasedHarnesses+ delete visible.overlapAlerts+ // Only that machine's host roster lists them (read/hostRows.ts); a removed private agent's session is not every member's.+ delete visible.closingSessions+ // A failing privacy check's detail is its contributor's: an error from the check can name paths on their Mac. Everyone+ // else reads which item failed (machines.ts teamWorkRefusal).+ for (const pool of visible.machines ?? []) {+ const privacy = pool.observation?.privacy+ if (privacy && 'detail' in privacy && !(actor.kind === 'person' && actor.userId === pool.contributorId)) delete (privacy as { detail?: string }).detail+ }+ expireRemovals(visible, now)+ // A read never hands out the cleanup records it just applied (read/hostRows.ts delivers them to the machine's host).+ delete visible.machineCleanups+ delete visible.parkedConversations+ numberConversations(visible)+ delete visible.retiredConversationNumber+ delete visible.groupCounter+ delete visible.sequenceBase+ placeRules(visible)+ if (visible.rules) visible.rules = visible.rules.filter(r => projectsOf(state).some(p => p.id === r.projectId && canReadProject(state, actor, p)))+ if (visible.projects) {+ visible.projects = visible.projects.filter(p => canReadProject(state, actor, p))+ visible.conversations = visible.conversations.filter(c => isLeads(c) || canReadGroup(state, actor, c))+ visible.agents = visible.agents.filter(a => canReadAgent(state, actor, a))+ for (const group of visible.conversations.filter(isLeads)) group.agentIds = group.agentIds.filter(id => visible.agents.some(a => a.id === id))+ visible.starts = visible.starts?.filter(s => visible.conversations.some(c => c.id === s.request.conversationId))+ if (!visible.projects.some(p => p.id === 'lead')) {+ delete visible.project+ visible.machines = visible.machines?.filter(m => m.scope === 'swarm')+ }+ const harnesses = new Set([...visible.agents.map(a => a.harnessId), ...(visible.starts ?? []).flatMap(s => s.harnessId ? [s.harnessId] : [])])+ for (const pool of visible.machines ?? []) {+ if (!pool.observation) continue+ pool.observation.runningHarnessIds = pool.observation.runningHarnessIds.filter(id => harnesses.has(id))+ pool.observation.stoppedHarnessIds = pool.observation.stoppedHarnessIds.filter(id => harnesses.has(id))+ if (pool.observation.harnessProgress) pool.observation.harnessProgress = Object.fromEntries(Object.entries(pool.observation.harnessProgress).filter(([id]) => harnesses.has(id)))+ // Each attempt's tokens are read through the cost summary (costs/read.ts), never from the machine's raw counts.+ delete pool.observation.harnessTokens+ if (pool.observation.stoppedReservations) pool.observation.stoppedReservations = pool.observation.stoppedReservations.filter(r => harnesses.has(r.harnessId))+ if (pool.observation.preparingStartIds) pool.observation.preparingStartIds = pool.observation.preparingStartIds.filter(id => visible.starts?.some(s => s.id === id))+ }+ for (const start of visible.starts ?? []) if (startPreparing(state, start, now)) start.preparing = true+ visible.invitations = visible.invitations.filter(i => visible.conversations.some(c => c.id === i.conversationId))+ }+ for (const project of projectsOf(visible)) for (const target of awaitingWorkers(visible, project.id)) target.workDecision = 'awaiting'+ for (const project of visible.projects ?? []) project.skillSet = skillSetOf(project)+ // An uploaded avatar's stored key stays on the server; readers get a link with each parts read (avatarLinks.ts).+ // Each person as the Swarm names them (usernames.ts), their default included.+ const names = swarmUsernames(state)+ visible.people = visible.people.map(p => ({ ...withAvatarView(p), username: names.get(p.id) })) as Person[]+ visible.agents = visible.agents.map(withAvatarView) as Agent[]+ // On Custom every agent shows the role it runs, null when its kind has none; elsewhere a role id means nothing yet.+ for (const target of visible.agents) {+ const home = projectsOf(state).find(p => p.id === agentProjectId(state, target))+ if (home && skillSetOf(home) === 'custom') target.roleId = agentSetRole(state, home, target)?.id ?? null+ else delete target.roleId+ }+ if (actor.kind !== 'person' || actor.userId !== state.ownerId) visible.invitations = []+ for (const start of visible.starts ?? []) {+ if (start.error && !readsRawReason(actor, start, state.conversations.find(c => c.id === start.request.conversationId))) start.error = publicReason(start.error)+ }+ // A Buddy brainstorms; where agents run and how work is routed are none of its business (buddies.ts). A start names the+ // machine and the folder on it, so it reads none, though it reads their workgroups.+ if (actor.kind === 'agent' && state.agents.some(a => a.id === actor.agentId && a.buddyOf)) {+ visible.machines = []+ visible.starts = []+ visible.agents = visible.agents.map(a => agentForBuddy(a, actor.agentId))+ visible.conversations = visible.conversations.map(groupWithoutMachines)+ // A project's repository names the machine and folder it was made from; the address is all a Buddy needs (security+ // review 2 of #2115).+ for (const project of visible.projects ?? []) if (project.repository) project.repository = { repositoryUrl: project.repository.repositoryUrl } as typeof project.repository+ // Where its Product Manager runs names the machine and its start: a Buddy reads how it stands, and why it failed, which+ // names no machine (leadStart.ts leadStartFailed; Diego, 10-30).+ for (const project of visible.projects ?? []) {+ const lead = project.lead+ if (lead) project.lead = { status: lead.status, ...(lead.reason !== undefined ? { reason: lead.reason } : {}) } as typeof lead+ }+ if (visible.project) visible.project = { repositoryUrl: visible.project.repositoryUrl } as typeof visible.project+ delete visible.rules+ delete visible.routingPolicy+ }+ const seen = seenMachineIds(visible)+ visible.conversations = visible.conversations.map(c => withSeenRequirement(c, seen))+ return visible+}++const stranger: Actor = { kind: 'person', userId: '100000000000000000000009', email: '[email protected]' }+const agentActor = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: `${owner.userId}-machine` })+const s = fullSwarm()+const readers: Array<[string, Actor]> = [['the owner', owner], ['a member of the private project', peer], ['a member outside it', outsider],+ ['a Buddy', agentActor(s.buddy)], ['a worker', agentActor(s.worker)], ['a Lead', agentActor(s.lead)]]++describe('visibleState', () => {+ it('exercises what it compares', () => {+ const state = s.state+ for (const field of ['sharing', 'harnessReservations', 'releasedHarnesses', 'overlapAlerts', 'closingSessions'] as const) expect(state[field], field).toBeDefined()+ expect(state.conversations.some(c => c.dormant)).toBe(true)+ expect(visibleStateBefore(state, owner, NOW).projects!.some(p => p.progress)).toBe(true)+ expect(visibleStateBefore(state, peer, NOW).projects!.map(p => p.id)).toContain(s.secret)+ expect(visibleStateBefore(state, outsider, NOW).projects!.map(p => p.id)).not.toContain(s.secret)+ expect(visibleStateBefore(state, agentActor(s.buddy), NOW).machines).toEqual([])+ })++ it.each(readers)('reads the same as before for %s', (_name, actor) => {+ const now = visibleState(s.state, actor, NOW), before = visibleStateBefore(s.state, actor, NOW)+ expect(now).toStrictEqual(before)+ expect(JSON.stringify(now)).toBe(JSON.stringify(before))+ })++ it('refuses someone outside the Swarm as before', () => {+ const code = (read: () => unknown) => { try { read(); return null } catch (error) { return (error as { code?: string }).code } }+ expect(code(() => visibleState(s.state, stranger, NOW))).toBe(code(() => visibleStateBefore(s.state, stranger, NOW)))+ expect(code(() => visibleState(s.state, stranger, NOW))).toBeTruthy()+ })++ it('reads a frozen, shared state as before and leaves it untouched', () => {+ const frozen = structuredClone(s.state)+ freeze(frozen)+ for (const actor of [owner, agentActor(s.worker)]) expect(visibleState(frozen, actor, NOW)).toStrictEqual(visibleStateBefore(structuredClone(s.state), actor, NOW))+ })++ it('fails loudly on a value it cannot copy', () => {+ expect(() => visibleState({ ...s.state, stray: new Map() } as never, owner, NOW)).toThrow(/cannot copy a Map at stray/)+ })+})