The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Merge batch 10-29 ag: 5 reviewed PRs (#2165, #2173, #2176, #2193, #2167) (#2227)
0xken159e6313f5e79d
diff --git a/backend/.gitignore b/backend/.gitignoreindex 0d7af1a82..8d4798805 100644--- a/backend/.gitignore+++ b/backend/.gitignore@@ -2,3 +2,4 @@ node_modulesdist.tsbuildinfo.env+atlas-snapshotsdiff --git a/backend/integration/atlasSnapshot.test.ts b/backend/integration/atlasSnapshot.test.tsnew file mode 100644index 000000000..cc9de2fd1--- /dev/null+++ b/backend/integration/atlasSnapshot.test.ts@@ -0,0 +1,267 @@+import { createHash, randomUUID } from 'node:crypto'+import { createServer, type IncomingMessage, type Server } from 'node:http'+import { mkdtemp, readFile, writeFile, mkdir } from 'node:fs/promises'+import { join } from 'node:path'+import { tmpdir } from 'node:os'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'+import { MongoClient } from 'mongodb'+import { assertReadOnly, compareSnapshots, redactUrl, runSnapshot, secondaryUrl } from '../scripts/atlas-snapshot.js'++// The Atlas snapshot script (DB roadmap Phase 1) against a fake Atlas Admin API and a two-node loopback replica set.+// It never reads DATABASE_URL, and nothing here reaches Atlas or any shared database.++const GROUP = 'g1'+const KEYS = { publicKey: 'pub-key', privateKey: 'priv-secret' }+const SERVICE = { clientId: 'svc-id', clientSecret: 'svc-secret' }+const NOW = Date.parse('2026-10-29T08:00:00Z')+const md5 = (s: string) => createHash('md5').update(s).digest('hex')++type Seen = { method: string; path: string; query: URLSearchParams; accept?: string; auth?: string }++const PROCESSES = [+ { id: 'autonomous-code-prod-shard-00-00.x.mongodb.net:27017', hostname: 'autonomous-code-prod-shard-00-00.x.mongodb.net', port: 27017, typeName: 'REPLICA_PRIMARY', userAlias: 'autonomous-code-prod-shard-00-00.x.mongodb.net' },+ { id: 'autonomous-code-prod-shard-00-01.x.mongodb.net:27017', hostname: 'autonomous-code-prod-shard-00-01.x.mongodb.net', port: 27017, typeName: 'REPLICA_SECONDARY', userAlias: 'autonomous-code-prod-shard-00-01.x.mongodb.net' },+ { id: 'other-cluster-shard-00-00.x.mongodb.net:27017', hostname: 'other-cluster-shard-00-00.x.mongodb.net', port: 27017, typeName: 'REPLICA_PRIMARY', userAlias: 'other-cluster-shard-00-00.x.mongodb.net' },+]++/** Two points a metric: CPU 40 then 80 on the primary, so the average is 60 and the peak 80. */+function measurements(processId: string, metrics: string[]) {+ const primary = processId === PROCESSES[0]!.id+ const values: Record<string, [number, number]> = {+ PROCESS_NORMALIZED_CPU_USER: primary ? [30, 70] : [5, 5], PROCESS_NORMALIZED_CPU_KERNEL: primary ? [10, 10] : [1, 1],+ OPCOUNTER_QUERY: [600, 800], NETWORK_BYTES_OUT: [10_000_000, 20_000_000], QUERY_TARGETING_SCANNED_OBJECTS_PER_RETURNED: [2, 3],+ }+ return { processId, granularity: 'PT5M', measurements: metrics.map(name => ({ name, units: 'SCALAR',+ dataPoints: (values[name] ?? [1, null]).map((value, i) => ({ timestamp: new Date(NOW - (2 - i) * 300_000).toISOString(), value })) })) }+}++const slowLine = (ms: number, at: number, email: string) => JSON.stringify({ t: { $date: new Date(at).toISOString() }, s: 'I', c: 'COMMAND', msg: 'Slow query',+ attr: { type: 'command', ns: 'prod.users', command: { find: 'users', filter: { email, autonomousEnv: 'prod' }, $db: 'prod' }, planSummary: 'IXSCAN { email: 1 }',+ keysExamined: 1, docsExamined: 1, nreturned: 1, durationMillis: ms } })++function fakeAtlas(mode: 'digest' | 'service') {+ const seen: Seen[] = []+ const nonce = randomUUID()+ const server = createServer(async (req: IncomingMessage, res) => {+ const url = new URL(req.url!, 'http://x')+ seen.push({ method: req.method!, path: url.pathname, query: url.searchParams, accept: req.headers.accept, auth: req.headers.authorization })+ const send = (status: number, body: unknown, headers: Record<string, string> = {}) => { res.writeHead(status, { 'content-type': 'application/json', ...headers }); res.end(JSON.stringify(body)) }+ if (url.pathname === '/api/oauth/token') {+ const ok = mode === 'service' && req.headers.authorization === `Basic ${Buffer.from(`${SERVICE.clientId}:${SERVICE.clientSecret}`).toString('base64')}`+ return ok ? send(200, { access_token: 'tok-1', expires_in: 3600, token_type: 'Bearer' }) : send(401, { error: 'bad client' })+ }+ if (mode === 'service' && req.headers.authorization !== 'Bearer tok-1') return send(401, { error: 'no token' })+ if (mode === 'digest') {+ const auth = req.headers.authorization ?? ''+ const field = (name: string) => new RegExp(`${name}="?([^",]+)"?`).exec(auth)?.[1]+ const ha1 = md5(`${KEYS.publicKey}:MMS Public API:${KEYS.privateKey}`), ha2 = md5(`${req.method}:${field('uri')}`)+ const expected = md5(`${ha1}:${nonce}:${field('nc')}:${field('cnonce')}:auth:${ha2}`)+ if (!auth.startsWith('Digest ') || field('username') !== KEYS.publicKey || field('response') !== expected || field('uri') !== req.url) {+ return send(401, { error: 'auth' }, { 'www-authenticate': `Digest realm="MMS Public API", domain="", nonce="${nonce}", algorithm=MD5, qop="auth", stale=false` })+ }+ }+ if (req.headers.accept !== 'application/vnd.atlas.2023-01-01+json') return send(406, { error: 'version' })+ const processPath = /^\/api\/atlas\/v2\/groups\/g1\/processes\/([^/]+)\/(measurements|performanceAdvisor\/slowQueryLogs)$/.exec(url.pathname)+ if (url.pathname === '/api/atlas/v2/groups/g1/processes') return send(200, { results: PROCESSES, totalCount: PROCESSES.length })+ if (processPath?.[2] === 'measurements') return send(200, measurements(decodeURIComponent(processPath[1]!), url.searchParams.getAll('m')))+ if (processPath?.[2] === 'performanceAdvisor/slowQueryLogs') {+ const primary = decodeURIComponent(processPath[1]!) === PROCESSES[0]!.id+ return send(200, { slowQueries: primary ? [+ { namespace: 'prod.users', line: slowLine(30_000, NOW - 3_600_000, '[email protected]') },+ { namespace: 'prod.users', line: slowLine(40_000, NOW - 3_600_000 + 10_000, '[email protected]') },+ { namespace: 'prod.users', line: slowLine(500, NOW - 60_000, '[email protected]') },+ { namespace: 'prod.x', line: 'not json' },+ ] : [] })+ }+ send(404, { error: 'not found' })+ })+ return { server, seen }+}++const listen = (server: Server) => new Promise<string>(resolve => server.listen(0, '127.0.0.1', () => {+ const address = server.address() as { port: number }+ resolve(`http://127.0.0.1:${address.port}`)+}))++let replica: MongoMemoryReplSet+let uri: string++beforeAll(async () => {+ // The second member can never be elected, so the first stays primary and the second a secondary for the whole file.+ replica = await MongoMemoryReplSet.create({ binary: { version: '7.0.24', downloadDir: join(tmpdir(), 'harness-super-tab-mongodb-binaries') },+ instanceOpts: [{ replicaMemberConfig: { priority: 1 } }, { replicaMemberConfig: { priority: 0 } }],+ replSet: { count: 2, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })+ await replica.waitUntilRunning()+ uri = replica.getUri(`atlas_snapshot_${randomUUID().replaceAll('-', '_')}`)+ const client = await MongoClient.connect(uri)+ try {+ const db = client.db()+ // A fresh set briefly refuses writes even once its primary says it is writable, and the second member may still+ // be syncing: retry each seed write until it lands, then wait until the second member is a secondary.+ const deadline = Date.now() + 60_000+ const settled = async <T>(write: () => Promise<T>): Promise<T> => {+ for (;;) {+ try { return await write() } catch (error) {+ if (Date.now() > deadline || (error as { code?: number }).code !== 10107) throw error+ await new Promise(resolve => setTimeout(resolve, 100))+ }+ }+ }+ // Upserts by fixed ids, so a write that was refused after it partly applied lands once when retried.+ const upserts = (docs: { _id: string }[]) => docs.map(doc => ({ replaceOne: { filter: { _id: doc._id }, replacement: doc, upsert: true } }))+ await settled(() => db.collection<{ _id: string }>('product_usage_receipts').bulkWrite(upserts(Array.from({ length: 50 }, (_, i) => ({ _id: `r${i}`, expiresAt: new Date(NOW) }))), { writeConcern: { w: 2 } }))+ await settled(() => db.collection('product_usage_receipts').createIndex({ expiresAt: 1 }))+ await settled(() => db.collection<{ _id: string }>('SwarmGroup').bulkWrite(upserts([{ _id: 'g', tabId: 't', note: 'x'.repeat(100) } as { _id: string }]), { writeConcern: { w: 2 } }))+ for (;;) {+ const { members } = await db.admin().command({ replSetGetStatus: 1 }) as { members: { stateStr: string }[] }+ if (members.every(m => m.stateStr === 'PRIMARY' || m.stateStr === 'SECONDARY')) break+ if (Date.now() > deadline) throw new Error('The second member never became a secondary')+ await new Promise(resolve => setTimeout(resolve, 100))+ }+ } finally {+ await client.close()+ }+})+afterAll(async () => { await replica?.stop() })++async function snapshot(mode: 'digest' | 'service', extra: Partial<NodeJS.ProcessEnv> = {}) {+ const { server, seen } = fakeAtlas(mode)+ const base = await listen(server)+ const out = await mkdtemp(join(tmpdir(), 'atlas-snapshot-test-'))+ const env: NodeJS.ProcessEnv = { ATLAS_BASE_URL: base, ATLAS_GROUP_ID: GROUP, ATLAS_CLUSTER: 'autonomous-code-prod', MONGO_READONLY_URL: uri,+ ...mode === 'digest' ? { ATLAS_PUBLIC_KEY: KEYS.publicKey, ATLAS_PRIVATE_KEY: KEYS.privateKey } : { ATLAS_CLIENT_ID: SERVICE.clientId, ATLAS_CLIENT_SECRET: SERVICE.clientSecret },+ ...extra }+ const printed: string[] = []+ try {+ const result = await runSnapshot({ env, out, label: 'before', now: NOW, print: line => printed.push(line) })+ return { result, seen, out, printed }+ } finally {+ server.close()+ }+}++describe('runSnapshot', () => {+ it('saves the cluster metrics, a slow log with shapes only and the sizes from a secondary, with API keys', async () => {+ const { result, seen, out, printed } = await snapshot('digest')+ expect(result).toEqual({ ok: true, skipped: [], failed: [] })+ // Only the named cluster's processes, a day at 5-minute points, every metric the roadmap lists.+ const asked = seen.filter(s => s.path.endsWith('/measurements') && s.auth?.startsWith('Digest '))+ expect(asked.map(s => decodeURIComponent(s.path.split('/')[7]!)).sort()).toEqual([PROCESSES[0]!.id, PROCESSES[1]!.id])+ expect(asked[0]!.query.get('granularity')).toBe('PT5M')+ expect(asked[0]!.query.get('period')).toBe('P1D')+ expect(asked[0]!.query.getAll('m')).toEqual(expect.arrayContaining(['PROCESS_NORMALIZED_CPU_USER', 'OPCOUNTER_QUERY', 'DOCUMENT_METRICS_RETURNED',+ 'NETWORK_BYTES_OUT', 'QUERY_TARGETING_SCANNED_OBJECTS_PER_RETURNED', 'OP_EXECUTION_TIME_READS', 'SYSTEM_MEMORY_AVAILABLE', 'CONNECTIONS']))+ const slowAsked = seen.find(s => s.path.endsWith('/slowQueryLogs') && s.auth?.startsWith('Digest '))!+ expect(slowAsked.query.get('since')).toBe(String(NOW - 86_400_000))+ expect(slowAsked.query.get('duration')).toBe('86400000')++ const summary = JSON.parse(await readFile(join(out, 'summary.json'), 'utf8'))+ expect(summary.label).toBe('before')+ // CPU is user + kernel: (30+10, 70+10) → average 60, peak 80.+ expect(summary.primary.PROCESS_CPU).toEqual({ average: 60, peak: 80, latest: 80 })+ expect(summary.primary.OPCOUNTER_QUERY).toEqual({ average: 700, peak: 800, latest: 800 })+ // 30 s and 40 s in the same minute, then 0.5 s: 70.5 s in all, 70 s in the worst minute; the unreadable line counted.+ expect(summary.slowOps).toMatchObject({ count: 3, unreadable: 1, totalSeconds: 70.5, peakSecondsPerMinute: 70 })+ expect(summary.slowOps.top[0]).toMatchObject({ ns: 'prod.users', op: 'find', shape: '{"autonomousEnv":"?","email":"?"}', count: 3, seconds: 70.5 })+ expect(summary.sizes.collections[0]).toMatchObject({ name: 'product_usage_receipts', count: 50, nindexes: 2 })++ const slowFile = await readFile(join(out, 'slow-queries.json'), 'utf8')+ expect(slowFile).not.toMatch(/alice|bob|carol/)+ const sizes = JSON.parse(await readFile(join(out, 'sizes.json'), 'utf8'))+ // Mongo names the member that answered by this machine's name; its port tells which one it was.+ const port = (address: string) => Number(address.split(':').at(-1))+ const members = replica.servers.filter(s => s.instanceInfo).map(s => s.instanceInfo!.port)+ expect(members).toContain(port(sizes.readFrom))+ expect(port(sizes.readFrom)).not.toBe(port(sizes.primary))+ const markdown = await readFile(join(out, 'summary.md'), 'utf8')+ expect(markdown).toContain('| Process CPU (%) | 60 | 80 | 80 |')+ expect(printed.join('\n')).toContain(out)+ expect(printed.join('\n')).not.toMatch(/priv-secret|pub-key/)+ })++ it('signs in with a service account when one is set', async () => {+ const { result, seen } = await snapshot('service')+ expect(result.ok).toBe(true)+ expect(seen.filter(s => s.path === '/api/oauth/token')).toHaveLength(1)+ expect(seen.filter(s => s.path.startsWith('/api/atlas/')).every(s => s.auth === 'Bearer tok-1')).toBe(true)+ })++ it('says which parts it skipped when their settings are missing, and still saves the rest', async () => {+ const { result, out } = await snapshot('digest', { ATLAS_PUBLIC_KEY: undefined, ATLAS_PRIVATE_KEY: undefined })+ expect(result).toEqual({ ok: true, skipped: ['atlas: set ATLAS_CLIENT_ID and ATLAS_CLIENT_SECRET, or ATLAS_PUBLIC_KEY and ATLAS_PRIVATE_KEY'], failed: [] })+ const summary = JSON.parse(await readFile(join(out, 'summary.json'), 'utf8'))+ expect(summary.sizes.collections.length).toBeGreaterThan(0)+ expect(summary.skipped).toEqual(result.skipped)+ })++ it('fails the run when a part fails, without printing the database password', async () => {+ const { result } = await snapshot('digest', { MONGO_READONLY_URL: 'mongodb://reader:[email protected]:1/prod?serverSelectionTimeoutMS=300' })+ expect(result.ok).toBe(false)+ expect(result.failed).toHaveLength(1)+ expect(result.failed[0]).toMatch(/^sizes: /)+ expect(result.failed[0]).not.toContain('hunter2')+ })++ it('refuses a cluster name that matches no process, naming the ones it saw', async () => {+ const { result } = await snapshot('digest', { ATLAS_CLUSTER: 'no-such-cluster' })+ expect(result.ok).toBe(false)+ expect(result.failed[0]).toContain('autonomous-code-prod-shard-00-00')+ })+})++describe('safety checks', () => {+ it('always reads from a secondary, whatever the URL asked', () => {+ expect(secondaryUrl('mongodb+srv://r:[email protected]/prod?readPreference=primary&retryWrites=true'))+ .toBe('mongodb+srv://r:[email protected]/prod?readPreference=secondary&retryWrites=false')+ })++ it('hides the password of a URL', () => {+ expect(redactUrl('failed mongodb+srv://reader:[email protected]/prod')).toBe('failed mongodb+srv://reader:***@cluster.x.mongodb.net/prod')+ })++ const status = (actions: string[], users = [{ user: 'reader', db: 'admin' }]) => ({ authInfo: { authenticatedUsers: users,+ authenticatedUserPrivileges: [{ resource: { db: '', collection: '' }, actions }] } })++ it('accepts a user that can only read', () => {+ expect(() => assertReadOnly(status(['find', 'listCollections', 'collStats', 'dbStats', 'listIndexes', 'killCursors']), 'cluster.x.mongodb.net')).not.toThrow()+ })++ it('accepts the read-only role a monitoring user also has', () => {+ expect(() => assertReadOnly(status(['find', 'listDatabases', 'changeStream', 'dbHash', 'planCacheRead', 'listSearchIndexes', 'serverStatus',+ 'replSetGetStatus', 'getLog', 'top', 'indexStats', 'connPoolStats', 'hostInfo', 'inprog']), 'cluster.x.mongodb.net')).not.toThrow()+ })++ it('refuses a user that can do more than read, naming what it could do', () => {+ expect(() => assertReadOnly(status(['find', 'insert', 'update', 'dropCollection']), 'cluster.x.mongodb.net'))+ .toThrow('Refused: this user can do more than read (dropCollection, insert, update). Use the read-only user.')+ })++ it('refuses a root user, emptycapped, and any permission it does not know as read-only', () => {+ expect(() => assertReadOnly(status(['anyAction']), 'cluster.x.mongodb.net')).toThrow('(anyAction)')+ expect(() => assertReadOnly(status(['find', 'emptycapped']), 'cluster.x.mongodb.net')).toThrow('(emptycapped)')+ expect(() => assertReadOnly(status(['find', 'someFutureAction']), 'cluster.x.mongodb.net')).toThrow('(someFutureAction)')+ })++ it('refuses a remote database without sign-in, and allows one only on this computer', () => {+ expect(() => assertReadOnly(status([], []), 'cluster.x.mongodb.net')).toThrow(/without signing in/)+ expect(() => assertReadOnly(status([], []), '127.0.0.1')).not.toThrow()+ })+})++describe('compareSnapshots', () => {+ it('shows each number before and after with its change', async () => {+ const dir = await mkdtemp(join(tmpdir(), 'atlas-compare-test-'))+ const write = async (name: string, cpu: number, slow: number) => {+ await mkdir(join(dir, name))+ await writeFile(join(dir, name, 'summary.json'), JSON.stringify({ label: name, takenAt: '2026-10-29T08:00:00.000Z',+ primary: { PROCESS_CPU: { average: cpu, peak: cpu * 2, latest: cpu } }, slowOps: { count: 1, totalSeconds: slow, peakSecondsPerMinute: slow, unreadable: 0, top: [] },+ sizes: { collections: [], dataBytes: 100, indexBytes: 50 } }))+ return join(dir, name)+ }+ const table = compareSnapshots(JSON.parse(await readFile(join(await write('before', 40, 60), 'summary.json'), 'utf8')),+ JSON.parse(await readFile(join(await write('after', 10, 6), 'summary.json'), 'utf8')))+ expect(table).toContain('| Process CPU (%), average | 40 | 10 | -75% |')+ expect(table).toContain('| Slow operations, seconds | 60 | 6 | -90% |')+ })+})diff --git a/backend/integration/bench/queryStatsOverhead.ts b/backend/integration/bench/queryStatsOverhead.tsnew file mode 100644index 000000000..819c5a2a7--- /dev/null+++ b/backend/integration/bench/queryStatsOverhead.ts@@ -0,0 +1,110 @@+import { execFile } from 'node:child_process'+import { promisify } from 'node:util'+import { join } from 'node:path'+import { performance } from 'node:perf_hooks'+import { PrismaClient } from '@prisma/client'+import { POOL_DEFAULTS, withPoolDefaults } from '../../src/lib/databaseUrl.js'+import { createQueryStats, runWork, startQueryStats, withQueryStats } from '../../src/lib/queryStats.js'+import { localDatabase } from './mongo.js'+import { percentile } from './metrics.js'++/**+ * What the query hook (src/lib/queryStats.ts) costs, for the DB roadmap Phase 1 PR. Each round runs the same load in two+ * fresh processes against one loopback replica set: `plain`, the client as it was, and `hook`, the client with the hook,+ * its per-minute stats running, and every iteration named as a request (which turns on Node's async context tracking for+ * the whole process, as the server does). Processes alternate, so drift on a busy machine hits both alike.+ *+ * npx tsx integration/bench/queryStatsOverhead.ts [--rounds 5] [--iterations 600] [--concurrency 8]+ *+ * Never reads DATABASE_URL or any existing database.+ */++type Result = { mode: string; queries: number; cpuUsPerQuery: number; wallMs: number; perSecond: number; listP50Ms: number; listP95Ms: number }++const arg = (name: string, fallback: number) => {+ const at = process.argv.indexOf(`--${name}`)+ return at >= 0 ? Number(process.argv[at + 1]) : fallback+}++const PEOPLE = 40+const email = (i: number) => `bench-${i}@example.invalid`++async function child(mode: 'plain' | 'hook', uri: string, iterations: number, concurrency: number): Promise<void> {+ const base = new PrismaClient({ datasources: { db: { url: withPoolDefaults(uri, POOL_DEFAULTS) } } })+ const db = mode === 'hook' ? withQueryStats(base) : base+ const stop = mode === 'hook' ? startQueryStats({ reportMs: 3_600_000, log: () => {}, warn: () => {} }) : () => {}+ const named = <T>(fn: () => Promise<T>) => mode === 'hook' ? runWork('http GET /bench', fn) : fn()+ const listMs: number[] = []+ // One iteration is a request's worth of reads: one person by a unique key, a page of 20 whole documents, a count.+ const iteration = (i: number) => named(async () => {+ await db.user.findUnique({ where: { email: email(i % PEOPLE) } })+ const started = performance.now()+ await db.user.findMany({ where: { autonomousEnv: 'prod' }, take: 20 })+ listMs.push(performance.now() - started)+ await db.user.count({ where: { role: 'user' } })+ })+ const load = async (n: number) => {+ let next = 0+ await Promise.all(Array.from({ length: concurrency }, async () => { while (next < n) await iteration(next++) }))+ }+ await load(200)+ listMs.length = 0+ const cpu = process.cpuUsage(), wall = performance.now()+ await load(iterations)+ const used = process.cpuUsage(cpu), wallMs = performance.now() - wall+ stop()+ await base.$disconnect()+ const queries = iterations * 3+ const result: Result = { mode, queries, cpuUsPerQuery: (used.user + used.system) / queries, wallMs, perSecond: queries / (wallMs / 1000),+ listP50Ms: percentile(listMs, 50)!, listP95Ms: percentile(listMs, 95)! }+ console.log(JSON.stringify(result))+}++/** The bookkeeping alone, in this process: what one record costs without any database. */+function recordCost(): number {+ const stats = createQueryStats({ log: () => {}, warn: () => {} })+ const rows = Array.from({ length: 20 }, (_, i) => ({ id: `id-${i}`, email: email(i), name: 'x'.repeat(2000), role: 'user' }))+ const args = { where: { autonomousEnv: 'prod', OR: [{ role: 'user' }, { email: { in: ['a', 'b'] } }] }, take: 20 }+ const n = 200_000+ const started = performance.now()+ for (let i = 0; i < n; i++) stats.record('User', 'findMany', args, 1, rows)+ return (performance.now() - started) * 1000 / n+}++async function main(): Promise<void> {+ const rounds = arg('rounds', 5), iterations = arg('iterations', 600), concurrency = arg('concurrency', 8)+ const local = await localDatabase()+ try {+ // Documents about the size of a Swarm row, so a page is ~40 KB and the sampled serialization has real work to do.+ await local.db.user.createMany({ data: Array.from({ length: PEOPLE }, (_, i) => ({ email: email(i), externalId: `bench-${i}`, autonomousEnv: 'prod',+ name: 'x'.repeat(2000) })) })+ const results: Result[] = []+ for (let round = 0; round < rounds; round++) {+ for (const mode of round % 2 ? ['hook', 'plain'] : ['plain', 'hook']) {+ const { stdout } = await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/tsx'),+ [process.argv[1]!, '--child', mode, '--uri', local.uri, '--iterations', String(iterations), '--concurrency', String(concurrency)],+ { env: { ...process.env, DATABASE_URL: 'mongodb://127.0.0.1:1/never-used' }, maxBuffer: 1 << 20 })+ results.push(JSON.parse(stdout.trim().split('\n').at(-1)!) as Result)+ }+ }+ const median = (mode: string, key: keyof Result) => percentile(results.filter(r => r.mode === mode).map(r => r[key] as number), 50)!+ const keys = ['cpuUsPerQuery', 'perSecond', 'listP50Ms', 'listP95Ms'] as const+ const table = keys.map(key => {+ const plain = median('plain', key), hook = median('hook', key)+ return `| ${key} | ${plain.toFixed(1)} | ${hook.toFixed(1)} | ${((hook / plain - 1) * 100).toFixed(1)}% |`+ })+ console.log([`Rounds: ${rounds}, ${iterations} iterations × 3 queries, concurrency ${concurrency}, medians.`, '',+ '| Metric | Plain | Hook | Change |', '|---|---|---|---|', ...table, '',+ `Bookkeeping alone (shape, totals, every 8th result's size estimated; 20 rows of 2 KB): ${recordCost().toFixed(2)} µs a query.`,+ '', 'Rounds:', ...results.map(r => JSON.stringify(r))].join('\n'))+ } finally {+ await local.stop()+ }+}++if (process.argv.includes('--child')) {+ const at = process.argv.indexOf('--child')+ await child(process.argv[at + 1] as 'plain' | 'hook', process.argv[process.argv.indexOf('--uri') + 1]!, arg('iterations', 600), arg('concurrency', 8))+} else {+ await main()+}diff --git a/backend/integration/plans.test-support.ts b/backend/integration/plans.test-support.tsnew file mode 100644index 000000000..36ef5f865--- /dev/null+++ b/backend/integration/plans.test-support.ts@@ -0,0 +1,55 @@+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 { MongoMemoryReplSet } from 'mongodb-memory-server-core'+import { PrismaClient } from '@prisma/client'+import { PROFILE_STAGES, profileEntry, queryShape, type ProfileEntry } from './bench/profile.js'++/** A fresh loopback replica set with the schema pushed; never DATABASE_URL. */+export async function planDatabase(prefix: string): Promise<{ replica: MongoMemoryReplSet; db: PrismaClient }> {+ const 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(`${prefix}_${randomUUID().replaceAll('-', '_')}`)+ await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], {+ env: { ...process.env, DATABASE_URL: uri }, timeout: 60000,+ })+ return { replica, db: new PrismaClient({ datasources: { db: { url: uri } } }) }+}++/** Every operation `run` sends, as the profiler records it. */+export async function profiled(db: PrismaClient, run: () => Promise<unknown>): Promise<ProfileEntry[]> {+ await db.$runCommandRaw({ profile: 0 })+ await db.$runCommandRaw({ drop: 'system.profile' }).catch(() => {})+ await db.$runCommandRaw({ create: 'system.profile', capped: true, size: 64 * 1024 * 1024 })+ await db.$runCommandRaw({ profile: 2, slowms: 0 })+ try {+ await run()+ } finally {+ await db.$runCommandRaw({ profile: 0 })+ }+ const reply = await db.$runCommandRaw({ aggregate: 'system.profile', pipeline: [+ { $project: { ...PROFILE_STAGES[0]!.$project, 'command.hint': 1 } }], cursor: { batchSize: 100000 } }) as unknown as+ { cursor: { firstBatch: ProfileEntry[] } }+ return reply.cursor.firstBatch.map(profileEntry)+}++/** What an entry filtered on: an aggregate's first $match, a find's filter, or an update's query. */+export function filterOf(entry: ProfileEntry): unknown {+ return (entry.command?.pipeline as Array<{ $match?: unknown }> | undefined)?.[0]?.$match ?? entry.command?.filter ?? entry.command?.q+}++/** The profiled operations on one collection whose filter mentions every field of `fields` and none of `not`. */+export function reads(entries: ProfileEntry[], collection: string, fields: string[], not: string[] = []): ProfileEntry[] {+ const mentions = (shape: string, field: string) => shape.includes(`"$${field}"`) || shape.includes(`"${field}":`)+ return entries.filter(e => e.ns.endsWith(`.${collection}`)).filter(e => {+ const filter = filterOf(e)+ if (filter === undefined) return false+ const shape = queryShape(filter)+ return fields.every(f => mentions(shape, f)) && !not.some(f => mentions(shape, f))+ })+}++export const plan = (rows: ProfileEntry[]) => rows.map(r => ({ plan: r.planSummary, docsExamined: r.docsExamined, keysExamined: r.keysExamined,+ returned: r.nreturned, hint: r.command?.hint }))diff --git a/backend/integration/queryStats.test.ts b/backend/integration/queryStats.test.tsnew file mode 100644index 000000000..e75112348--- /dev/null+++ b/backend/integration/queryStats.test.ts@@ -0,0 +1,135 @@+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, beforeEach, expect, it } from 'vitest'+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'+import { PrismaClient } from '@prisma/client'+import { createQueryStats, runWork, startQueryStats, withQueryStats, type QueryStats } from '../src/lib/queryStats.js'++// The query hook on a real client (DB roadmap Phase 1). A fresh loopback replica set; never DATABASE_URL.+let replica: MongoMemoryReplSet+let base: PrismaClient+let db: PrismaClient+let stats: QueryStats+let infos: Record<string, unknown>[] = []+let warns: Record<string, unknown>[] = []++type Row = { op: string; shape: string; route: string; n: number; ms: number; docs: number; bytes: number; errors: number }+const flushed = (): Row[] => { stats.flush(); return infos.at(-1)!.top as Row[] }++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(`query_stats_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,+ })+ base = new PrismaClient({ datasources: { db: { url: uri } } })+ db = withQueryStats(base, () => stats)+})+afterAll(async () => {+ await base?.$disconnect()+ await replica?.stop()+})+beforeEach(() => {+ infos = []; warns = []+ stats = createQueryStats({ pod: 'test', sampleEvery: 1, log: (_m, c) => infos.push(c), warn: (_m, c) => warns.push(c) })+})++const person = () => {+ const id = randomUUID()+ return { email: `person-${id}@example.com`, externalId: `fixture-${id}`, autonomousEnv: 'prod' }+}++it('records a query under its model.action, filter shape and route, with its count, time, documents and bytes', async () => {+ const someone = person()+ await db.user.create({ data: someone })+ const found = await runWork('http GET /api/users/:id', async () => await db.user.findMany({ where: { email: someone.email } }))+ expect(found).toHaveLength(1)+ const row = flushed().find(r => r.op === 'User.findMany')!+ expect(row).toMatchObject({ shape: '{"email":"?"}', route: 'http GET /api/users/:id', n: 1, docs: 1, errors: 0 })+ expect(row.bytes).toBe(JSON.stringify(found).length)+ expect(row.ms).toBeGreaterThanOrEqual(0)+ const create = infos.at(-1)!.top as Row[]+ expect(create.find(r => r.op === 'User.create')).toMatchObject({ shape: '', route: 'background', n: 1, docs: 1 })+ expect(JSON.stringify(infos)).not.toContain(someone.email)+})++it('logs a slow query with its filter keys and no values', async () => {+ const someone = person()+ await db.user.create({ data: someone })+ stats = createQueryStats({ pod: 'test', slowMs: 150, log: (_m, c) => infos.push(c), warn: (_m, c) => warns.push(c) })+ // Server-side JavaScript that sleeps makes the query itself slow: the hook times the database, not a fake clock.+ await runWork('web-ws swarm_changes', async () => await db.user.findRaw({ filter: { email: someone.email, $where: 'sleep(200) || true' } }))+ await db.user.findMany({ where: { email: someone.email } })+ expect(warns).toHaveLength(1)+ expect(warns[0]).toMatchObject({ op: 'User.findRaw', shape: '{"$where":"?","email":"?"}', route: 'web-ws swarm_changes', docs: 1, error: false })+ expect(warns[0]!.ms as number).toBeGreaterThanOrEqual(150)+ expect(JSON.stringify(warns)).not.toContain(someone.email)+ expect(JSON.stringify(warns)).not.toContain('sleep')+ stats.flush()+ expect(infos.at(-1)).toMatchObject({ slowQueries: 1 })+})++it('counts a failed query as an error and still throws it to the caller', async () => {+ const someone = person()+ await db.user.create({ data: someone })+ await expect(db.user.create({ data: { ...someone, externalId: `other-${randomUUID()}` } })).rejects.toThrow()+ const rows = flushed().filter(r => r.op === 'User.create')+ expect(rows).toEqual([expect.objectContaining({ n: 2, errors: 1 })])+})++it('records raw commands by their collection and command', async () => {+ const someone = person()+ await db.user.create({ data: someone })+ await runWork('job sweepSwarms', async () => await db.$runCommandRaw({ find: 'users', filter: { email: someone.email } }))+ const row = flushed().find(r => r.op === 'users.$runCommandRaw find')!+ expect(row).toMatchObject({ shape: '{"email":"?"}', route: 'job sweepSwarms', n: 1, docs: 1 })+})++it('times queries and records nothing when no stats are running', async () => {+ const quiet = withQueryStats(base, () => undefined)+ await expect(quiet.user.count()).resolves.toBeGreaterThanOrEqual(0)+})++it('keeps each route apart when queries from two routes run in the same tick', async () => {+ const [a, b] = [person(), person()]+ await db.user.create({ data: a }); await db.user.create({ data: b })+ // Prisma batches findUnique calls of one tick into one engine request; each must still count for its own route.+ await Promise.all([+ runWork('http GET /api/a', async () => await db.user.findUnique({ where: { email: a.email } })),+ runWork('http GET /api/b', async () => await db.user.findUnique({ where: { email: b.email } })),+ ])+ const rows = flushed().filter(r => r.op === 'User.findUnique')+ expect(rows.map(r => [r.route, r.n, r.docs]).sort()).toEqual([['http GET /api/a', 1, 1], ['http GET /api/b', 1, 1]])+})++it('never fails a query because its stats failed, and says so once', async () => {+ const someone = person()+ await db.user.create({ data: someone })+ const broken: QueryStats = { record() { throw new Error('stats bug') }, flush() {} }+ const problems: string[] = []+ const guarded = withQueryStats(base, () => broken, (message, context) => problems.push(`${message} ${String(context.error)}`))+ await expect(guarded.user.findUnique({ where: { email: someone.email } })).resolves.toMatchObject({ email: someone.email })+ await expect(guarded.user.create({ data: someone })).rejects.toThrow(/Unique constraint/)+ expect(problems).toEqual(['query stats failed stats bug'])+})++it('logs every interval once started, flushes the last window on stop, and records nothing after it', async () => {+ // The default getter: what server.ts and worker.ts get from startQueryStats.+ const hooked = withQueryStats(base)+ const lines: Record<string, unknown>[] = []+ const stop = startQueryStats({ reportMs: 50, log: (_m, c) => lines.push(c), warn: () => {} })+ await runWork('job sweepSwarms', async () => await hooked.user.count())+ while (!lines.some(l => (l.top as Row[]).some(r => r.op === 'User.count' && r.route === 'job sweepSwarms'))) await new Promise(resolve => setTimeout(resolve, 10))+ await hooked.user.count({ where: { role: 'admin' } })+ stop()+ const last = lines.at(-1)!.top as Row[]+ expect(last.find(r => r.op === 'User.count')).toMatchObject({ shape: '{"role":"?"}', route: 'background', n: 1 })+ const after = lines.length+ await hooked.user.count()+ await new Promise(resolve => setTimeout(resolve, 120))+ expect(lines).toHaveLength(after)+})diff --git a/backend/integration/superTabEvidence.test.ts b/backend/integration/superTabEvidence.test.tsnew file mode 100644index 000000000..278eefcc0--- /dev/null+++ b/backend/integration/superTabEvidence.test.ts@@ -0,0 +1,272 @@+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 } 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 type { MachineObservation } from '../src/superTabs/machines.js'+import type { TokensByModel } from '../src/superTabs/costs/tokens.js'+import { DAY_MS, weekStart } from '../src/superTabs/leaderboard/week.js'+import { EVIDENCE_RETENTION_MS, readEvidence } from '../src/superTabs/evidence/store.js'+import { poolRows } from './hostRows.test-support.js'+import { groupProject } from '../src/superTabs/projects.js'+import { sweepSwarms } from '../src/superTabs/sweeps.js'++// Evidence routing (Ken, 2026-10-29): each Swarm keeps per model and kind of job what its attempts cost and how they went.+let replica: MongoMemoryReplSet+let db: PrismaClient+const owner: AuthUser = { sub: '300000000000000000000011', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const host: AuthUser = { sub: '300000000000000000000013', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const config = { engine: 'claude', model: 'opus', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }+const MINUTE = 60_000+const plan = [{ engine: 'claude', known: true, windows: [{ name: '5-hour', usedPercent: 10, resetsAt: null }] }]+const opus = (input: number, output: number): TokensByModel => ({ 'claude-opus-5-5': { input, output, cacheRead: 0, cacheWrite: 0 } })+const TASK_TEXT = 'Replace the zebra-quartz parser'+const T0 = Date.UTC(2026, 9, 6, 9)++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(`swarm_evidence_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 } } })+ for (const user of [owner, host]) await db.user.create({ data: { id: user.sub, externalId: `fixture-${user.sub}`, email: user.email, autonomousEnv: user.autonomousEnv } })+ for (const machineId of ['ev-lead-host', 'ev-test-host']) {+ await db.machine.create({ data: { machineId, userId: host.sub, apiKey: `fixture-${machineId}`, managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })+ await db.machineShare.create({ data: { machineId, ownerId: host.sub, autonomousEnv: 'prod', emails: [owner.email] } })+ }+})+afterAll(async () => {+ await db?.$disconnect()+ await replica?.stop()+})++/** A Swarm whose Lead routes groups that own backend code to workers on host's second machine. */+async function swarm() {+ let now = T0+ const store = new SuperTabStore(db, () => now, null)+ const tab = (await store.create(owner, randomUUID(), 'Evidence', 'public')).id+ const execute = (command: Command, user = owner, asAgentId?: string) => store.execute(user, tab, { operationId: randomUUID(), command }, asAgentId)+ const invitation = await execute({ type: 'invite.create', email: host.email, role: 'collaborator', conversationId: 'lead' })+ await execute({ type: 'invite.accept', inviteId: invitation.result.inviteId as string }, host)+ for (const [machineId, name] of [['ev-lead-host', 'Lead Mac'], ['ev-test-host', 'Worker Mac']]) {+ await execute({ type: 'machine.contribute', machineId: machineId!, name: name!, cwd: '/repo', engines: ['claude'], maxAgents: 8 }, host)+ }+ const generations = new Map<string, string>()+ for (const machineId of ['ev-lead-host', 'ev-test-host']) generations.set(machineId, (await poolRows(store, host, machineId)).find(p => p.tabId === tab)!.machine.generation)+ const leadHarness = randomUUID(), workers = new Map<string, { agentId: string; harness: string }>()+ const add = async (conversationId: string, machineId: string, harnessId: string, name: string, lead = false) => String((await execute({ type: 'agent.add',+ conversationId, machineId, harnessId, name, configuration: config, lead })).result.agentId)+ const lead = await add('lead', 'ev-lead-host', leadHarness, 'Lead', true)+ const observe = (machineId: string, running: string[], extra: Partial<MachineObservation> = {}) => store.observeMachine(host, tab, machineId, {+ generation: generations.get(machineId)!, resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9, diskFreeBytes: 120e9,+ diskTotalBytes: 500e9, projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Fixture', os: 'macOS', gpuPercent: null },+ quotas: plan, tools: {}, runningHarnessIds: running, stoppedHarnessIds: [], ...extra })+ /** Both machines report; each worker's session with these totals. */+ const beat = async (tokens: TokensByModel) => {+ await observe('ev-lead-host', [leadHarness])+ const harnesses = [...workers.values()].map(w => w.harness)+ await observe('ev-test-host', harnesses, { harnessTokens: Object.fromEntries(harnesses.map(h => [h, tokens])),+ harnessProgress: Object.fromEntries(harnesses.map(h => [h, now])) })+ }+ /** A group that owns backend code, reviewed by an independent check, with its own worker. */+ const group = async (title = TASK_TEXT) => {+ const id = String((await execute({ type: 'conversation.create', title, task: { goal: TASK_TEXT, changes: TASK_TEXT, constraints: 'None',+ owns: ['backend/src/parser'] }, checks: [{ description: 'Reviewed', independent: true }] } as Command)).result.conversationId)+ const harness = randomUUID()+ workers.set(id, { agentId: await add(id, 'ev-test-host', harness, `Worker ${workers.size}`), harness })+ return id+ }+ const worker = (id: string) => workers.get(id)!.agentId+ const route = async (id: string) => {+ const decision = { assessment: { difficulty: 'medium', risk: 'low', why: 'Parser work.', size: 'medium', kind: 'parser' },+ candidates: [{ id: 'c0', kind: 'member', agentId: worker(id), machineId: 'ev-test-host', engine: 'claude', model: 'opus', effort: 'high',+ quality: 3, cost: 3, title: 'Worker', label: 'Worker' }],+ excluded: [], floor: 1, notes: false, pick: 'c0', via: 'only', p: null, belowFloor: false, why: 'Only candidate.' }+ return String((await execute({ type: 'route.record', conversationId: id, decision } as Command, host, lead)).result.routeDecisionId)+ }+ const assign = async (id: string) => String((await execute({ type: 'work.assign', conversationId: id, agentId: worker(id), routeDecisionId: await route(id) } as Command,+ host, lead)).result.assignmentId)+ /** The owner gives the review's verdict. */+ const review = async (id: string, assignmentId: string, passed: boolean) => {+ const checkId = (await store.read(owner, tab)).state.conversations.find(c => c.id === id)!.checks[0]!.id+ await execute({ type: 'work.check', conversationId: id, assignmentId, checkId, passed, evidence: 'rev abc' } as Command)+ }+ const done = (id: string, assignmentId: string, tokens?: TokensByModel) =>+ execute({ type: 'work.status', conversationId: id, assignmentId, status: 'done', result: 'Shipped.', ...(tokens ? { tokens } : {}) } as Command, host, worker(id))+ const merged = (id: string, pr: string, extra: Record<string, unknown> = {}) =>+ execute({ type: 'conversation.merged', conversationId: id, pullRequestUrl: pr, ...extra } as Command)+ const evidence = (since = T0 - DAY_MS) => readEvidence(db, tab, since)+ return { store, tab, execute, lead, group, worker, beat, assign, review, done, merged, evidence,+ clock: { get now() { return now }, set now(value: number) { now = value } } }+}++describe('a Swarm\'s evidence per model and kind of job', () => {+ it('counts a finished attempt once under its model and kind: first review, rework, ship, tokens and cost', async () => {+ const f = await swarm(), g = await f.group()+ await f.beat(opus(1_000, 0))+ const a = await f.assign(g)+ await f.review(g, a, false)+ await f.review(g, a, true)+ f.clock.now += 30 * MINUTE+ await f.done(g, a, opus(1_001_000, 100_000))+ const read = await f.evidence()+ expect(read.models).toHaveLength(1)+ expect(read.models[0]).toMatchObject({ engine: 'claude', model: 'opus', kind: 'backend', attempts: 1, firstReviews: 1, firstReviewPassed: 0,+ firstReviewPassRate: 0, reworkRounds: 1, shipped: 1, averageMinutesToShip: 30, tokensInput: 1_000_000, tokensOutput: 100_000,+ tokensKnown: 1, costKnown: 1, costUnknown: 0, spend: 0, recent: [false] })+ // 1,000,000 input at $4 and 100,000 output at $20 per million.+ expect(read.models[0]!.apiCost).toBeCloseTo(6, 6)+ expect(read.models[0]!.costPerShipped).toBeCloseTo(6, 6)+ const state = (await f.store.read(owner, f.tab)).state+ const projectId = groupProject(state, state.conversations.find(c => c.id === g)!).id+ expect(read.weeks).toEqual([expect.objectContaining({ projectId, engine: 'claude', model: 'opus', kind: 'backend', week: weekStart(T0), attempts: 1 })])+ })++ // Review of #2173: each row keeps its project, so the report can show a reader only the projects they see; Swarm-wide totals+ // are the sum over projects.+ it('sums every project by default, reads only the projects asked for, and merges their last ten by time', async () => {+ const f = await swarm(), week = weekStart(T0)+ const row = (projectId: string, attempts: number) => db.superTabModelEvidence.create({ data: { id: `${f.tab}-${projectId}`, tabId: f.tab, projectId,+ engine: 'claude', model: 'opus', kind: 'backend', week: new Date(week), attempts, shipped: attempts, updatedAt: new Date(T0) } })+ const recent = (projectId: string, results: Array<[number, boolean]>) => db.superTabModelRecent.create({ data: { id: `${f.tab}-r-${projectId}`, tabId: f.tab,+ projectId, engine: 'claude', model: 'opus', kind: 'backend', results: results.map(([at, passed], i) => ({ a: `${projectId}-${i}`, at, passed })), updatedAt: new Date(T0) } })+ await row('p1', 2)+ await row('p2', 5)+ await recent('p1', [[1, true], [3, true], [5, true], [7, true], [9, true], [11, true]])+ await recent('p2', [[2, false], [4, false], [6, false], [8, false], [10, false], [12, false]])+ const all = await f.evidence()+ expect(all.models.map(m => [m.attempts, m.shipped])).toEqual([[7, 7]])+ expect(all.models[0]!.recent).toEqual([true, false, true, false, true, false, true, false, true, false])+ expect(all.weeks.map(w => [w.projectId, w.attempts])).toEqual([['p1', 2], ['p2', 5]])+ const one = await readEvidence(db, f.tab, T0 - DAY_MS, ['p1'])+ expect(one.models.map(m => [m.attempts, m.recent.length])).toEqual([[2, 6]])+ expect(one.weeks.map(w => w.projectId)).toEqual(['p1'])+ expect((await readEvidence(db, f.tab, T0 - DAY_MS, [])).models).toEqual([])+ })++ it('prunes every Swarm\'s rows past 180 days in the hourly sweep, with no write in that Swarm', async () => {+ const f = await swarm(), other = await swarm(), now = T0 + 400 * DAY_MS+ const cut = weekStart(now - EVIDENCE_RETENTION_MS)+ for (const tabId of [f.tab, other.tab]) {+ for (const [name, week] of [['old', cut - 7 * DAY_MS], ['kept', cut]] as const) {+ await db.superTabModelEvidence.create({ data: { id: `${tabId}-sweep-${name}`, tabId, projectId: 'p1', engine: 'claude', model: 'opus', kind: 'docs',+ week: new Date(week), attempts: 1, updatedAt: new Date(week) } })+ }+ for (const [name, at] of [['old', now - EVIDENCE_RETENTION_MS - DAY_MS], ['kept', now - EVIDENCE_RETENTION_MS + DAY_MS]] as const) {+ await db.superTabModelRecent.create({ data: { id: `${tabId}-sweep-r-${name}`, tabId, projectId: 'p1', engine: 'claude', model: `opus-${name}`, kind: 'docs',+ results: [], updatedAt: new Date(at) } })+ }+ }+ const result = await sweepSwarms(db, now)+ expect(result.evidenceExpired).toBeGreaterThanOrEqual(4)+ for (const tabId of [f.tab, other.tab]) {+ expect((await db.superTabModelEvidence.findMany({ where: { tabId, id: { startsWith: `${tabId}-sweep` } } })).map(r => r.id)).toEqual([`${tabId}-sweep-kept`])+ expect((await db.superTabModelRecent.findMany({ where: { tabId, id: { startsWith: `${tabId}-sweep` } } })).map(r => r.id)).toEqual([`${tabId}-sweep-r-kept`])+ }+ })++ it('moves the ship to the recorded merge and counts a fix after merge, without counting the attempt twice', async () => {+ const f = await swarm(), g = await f.group()+ await f.beat(opus(0, 0))+ const a = await f.assign(g)+ await f.review(g, a, true)+ f.clock.now += 60 * MINUTE+ await f.done(g, a, opus(10, 1))+ // The merge recorded later, at 40 minutes: the request shipped then.+ await f.merged(g, 'https://github.com/o/r/pull/1', { mergedAt: new Date(T0 + 40 * MINUTE).toISOString() })+ expect((await f.evidence()).models[0]).toMatchObject({ attempts: 1, shipped: 1, averageMinutesToShip: 40, fixesAfterMerge: 0, recent: [true] })+ const fix = await f.group('Follow-up')+ f.clock.now += 3 * DAY_MS+ await f.merged(fix, 'https://github.com/o/r/pull/2', { fixes: 'https://github.com/o/r/pull/1' })+ expect((await f.evidence()).models[0]).toMatchObject({ attempts: 1, shipped: 1, fixesAfterMerge: 1 })+ })++ it('counts a cancelled attempt\'s cost against its model, and ships only the attempt that shipped', async () => {+ const f = await swarm(), g = await f.group()+ await f.beat(opus(0, 0))+ const first = await f.assign(g)+ await f.beat(opus(1_000_000, 0))+ await f.execute({ type: 'work.cancel', conversationId: g, assignmentId: first, reason: 'Again.' } as Command, host, f.lead)+ const second = await f.assign(g)+ await f.review(g, second, true)+ await f.done(g, second, opus(1_500_000, 0))+ expect((await f.evidence()).models[0]).toMatchObject({ attempts: 2, shipped: 1, firstReviews: 1, costKnown: 2, costUnknown: 0 })+ // Cost per shipped change is all attempts' cost over what shipped: $4 + $2.+ expect((await f.evidence()).models[0]!.costPerShipped).toBeCloseTo(6, 6)+ })++ it('adds up attempts that finish at the same moment in different groups', async () => {+ const f = await swarm(), groups = [await f.group(), await f.group(), await f.group()]+ await f.beat(opus(0, 0))+ const attempts = []+ for (const g of groups) {+ attempts.push(await f.assign(g))+ await f.review(g, attempts.at(-1)!, true)+ }+ await Promise.all(groups.map((g, i) => f.done(g, attempts[i]!, opus(100, 10))))+ expect((await f.evidence()).models[0]).toMatchObject({ attempts: 3, shipped: 3 })+ })++ it('keeps the last ten first reviews, newest last', async () => {+ const f = await swarm()+ await f.beat(opus(0, 0))+ for (let i = 0; i < 12; i++) {+ const g = await f.group()+ const a = await f.assign(g)+ await f.review(g, a, i % 3 !== 0)+ if (i % 3 === 0) await f.review(g, a, true)+ f.clock.now += MINUTE+ await f.done(g, a)+ await f.execute({ type: 'agent.release', agentId: f.worker(g), decision: 'stop' } as Command, host, f.lead)+ }+ // Attempts 0, 3, 6 and 9 failed; the last ten are attempts 2 to 11.+ expect((await f.evidence()).models[0]!.recent).toEqual([true, false, true, true, false, true, true, false, true, true])+ })++ it('deletes rows older than 180 days on the next write, and reads only its own Swarm\'s rows', async () => {+ const f = await swarm(), other = await swarm()+ const old = (tabId: string, week: number, id: string) => db.superTabModelEvidence.create({ data: { id, tabId, projectId: 'p1', engine: 'claude', model: 'opus',+ kind: 'docs', week: new Date(week), attempts: 5, updatedAt: new Date(week) } })+ const stale = weekStart(T0 - EVIDENCE_RETENTION_MS) - 7 * DAY_MS, kept = weekStart(T0 - EVIDENCE_RETENTION_MS) + 7 * DAY_MS+ await old(f.tab, stale, `stale-${f.tab}`)+ await old(f.tab, kept, `kept-${f.tab}`)+ await db.superTabModelRecent.create({ data: { id: `recent-${f.tab}`, tabId: f.tab, projectId: 'p1', engine: 'claude', model: 'opus', kind: 'docs',+ results: [{ a: 'x', at: stale, passed: true }], updatedAt: new Date(T0 - EVIDENCE_RETENTION_MS - DAY_MS) } })+ const g = await f.group()+ await f.beat(opus(0, 0))+ const a = await f.assign(g)+ await f.review(g, a, true)+ await f.done(g, a)+ expect(await db.superTabModelEvidence.count({ where: { id: `stale-${f.tab}` } })).toBe(0)+ expect(await db.superTabModelEvidence.count({ where: { id: `kept-${f.tab}` } })).toBe(1)+ expect(await db.superTabModelRecent.count({ where: { id: `recent-${f.tab}` } })).toBe(0)+ const read = await f.evidence(T0 - EVIDENCE_RETENTION_MS)+ expect(read.models.map(m => [m.kind, m.attempts])).toEqual([['backend', 1], ['docs', 5]])+ expect((await other.evidence(0)).models).toEqual([])+ })++ it('never keeps a person, an agent or task text in a row', async () => {+ const f = await swarm(), g = await f.group()+ await f.beat(opus(0, 0))+ const a = await f.assign(g)+ await f.review(g, a, false)+ await f.review(g, a, true)+ await f.done(g, a, opus(10, 1))+ await f.merged(g, 'https://github.com/o/r/pull/9')+ const rows = JSON.stringify([...await db.superTabModelEvidence.findMany({ where: { tabId: f.tab } }), ...await db.superTabModelRecent.findMany({ where: { tabId: f.tab } }),+ ...(await db.superTabRouteDecision.findMany({ where: { tabId: f.tab } })).map(r => r.evidence)])+ expect(rows).toContain('"attempts":1')+ const state = (await f.store.read(owner, f.tab)).state+ const secrets = [TASK_TEXT, 'zebra', owner.email, host.email, owner.sub, host.sub, f.lead, f.worker(g), 'Worker 0', 'Lead Mac', 'Worker Mac',+ ...state.agents.map(agent => agent.harnessId), 'ev-test-host', 'rev abc', 'Parser work']+ for (const secret of secrets) expect(rows, secret).not.toContain(secret)+ })+})diff --git a/backend/integration/superTabIndexes.test.ts b/backend/integration/superTabIndexes.test.tsindex 635d98693..49108cd85 100644--- a/backend/integration/superTabIndexes.test.ts+++ b/backend/integration/superTabIndexes.test.ts@@ -8,6 +8,7 @@ import { MongoMemoryReplSet } from 'mongodb-memory-server-core'import { PrismaClient } from '@prisma/client'import { inConversationOrder, pageDeliveries, pageReactions, pageThreads } from '../src/superTabs/pageReads.js'import { costRows } from '../src/superTabs/costs/read.js'+import { readEvidence } from '../src/superTabs/evidence/store.js'import { recentDecisions } from '../src/superTabs/routeDecisions.js'import { settleStuckDeliveries } from '../src/superTabs/deliverySettle.js'import { revokeNativeContexts } from '../src/superTabs/native.js'@@ -213,6 +214,26 @@ describe('cost summary', () => {})})+describe('model evidence', () => {+ // Routing and the weekly report read a Swarm's evidence (superTabs/evidence/store.ts): only the weeks asked for, by index.+ it('reads the weeks of a period and the last-ten rows with one index scan each, examining only that Swarm\'s rows', async () => {+ const WEEK = 7 * 86_400_000, MONDAY = Date.UTC(2026, 9, 26)+ const rows = ['A', 'B'].flatMap(tabId => ['opus', 'sonnet', 'kimi'].flatMap(model => Array.from({ length: 26 }, (_, w) => ({+ _id: `${tabId}-${model}-${w}`, tabId, projectId: 'p1', engine: 'claude', model, kind: 'backend', week: { $date: new Date(MONDAY - w * WEEK).toISOString() },+ attempts: 1, updatedAt: { $date: new Date(MONDAY).toISOString() } }))))+ await db.$runCommandRaw({ insert: 'SuperTabModelEvidence', documents: rows as never })+ await db.$runCommandRaw({ insert: 'SuperTabModelRecent', documents: ['A', 'B'].flatMap(tabId => ['opus', 'sonnet', 'kimi'].map(model => ({+ _id: `${tabId}-${model}`, tabId, projectId: 'p1', engine: 'claude', model, kind: 'backend', results: [{ a: 'x', at: MONDAY, passed: true }],+ updatedAt: { $date: new Date(MONDAY).toISOString() } }))) as never })+ // The last four weeks: 3 models x 4 weeks.+ const [read, profile] = await profiled('SuperTabModelEvidence', () => readEvidence(db, 'A', MONDAY - 3 * WEEK))+ expect(read.models.map(m => [m.model, m.attempts, m.recent])).toEqual([['kimi', 4, [true]], ['opus', 4, [true]], ['sonnet', 4, [true]]])+ expect(profile).toEqual({ plans: ['IXSCAN { tabId: 1, week: 1 }'], docsExamined: 12, returned: 12 })+ const [, recent] = await profiled('SuperTabModelRecent', () => readEvidence(db, 'A', MONDAY))+ expect(recent).toEqual({ plans: ['IXSCAN { tabId: 1, updatedAt: 1 }'], docsExamined: 3, returned: 3 })+ })+})+describe('route decision list', () => {const prismaRead = (tabId: string, conversationIds: string[]) => db.superTabRouteDecision.findMany({ where: { tabId, conversationId: { in: conversationIds } },orderBy: { createdAt: 'desc' }, take: 100 })@@ -237,11 +258,11 @@ describe('route decision list', () => {expect(rows.find(row => row.id === 'A-d1800')).toEqual({ id: 'A-d1800', tabId: 'A', conversationId: 'g000',record: { difficulty: 'medium', candidates: [{ id: 'c0', p: 0.42, slots: 3, title: 'Claude opus high' }, { id: 'c1', p: null, slots: 0 }], why: 'route 1800' },final: { kind: 'new', startId: 's1800' }, override: { by: 'lead', candidateId: 'c1' }, assignmentId: 'as1800', outcome: 'done',- outcomeAt: new Date(T0 + 1_800_500), run: null, createdAt: new Date(T0 + 1_800_000) })+ outcomeAt: new Date(T0 + 1_800_500), run: null, evidence: null, createdAt: new Date(T0 + 1_800_000) })// Written as an older record: none of the optional fields exist.expect(rows.find(row => row.id === 'A-d0721')).toEqual({ id: 'A-d0721', tabId: 'A', conversationId: 'g001',record: { difficulty: 'medium', candidates: [{ id: 'c0', p: 0.42, slots: 3, title: 'Claude opus high' }, { id: 'c1', p: null, slots: 0 }], why: 'route 721' },- final: null, override: null, assignmentId: null, outcome: null, outcomeAt: null, run: null, createdAt: new Date(T0 + 721_000) })+ final: null, override: null, assignmentId: null, outcome: null, outcomeAt: null, run: null, evidence: null, createdAt: new Date(T0 + 721_000) })expect(await recentDecisions(db, 'A', GROUPS)).toEqual(await prismaRead('A', GROUPS))expect(await recentDecisions(db, 'A', ['g007', 'g300'])).toEqual(await prismaRead('A', ['g007', 'g300']))expect(await recentDecisions(db, 'B', [])).toEqual([])diff --git a/backend/integration/superTabLiveness.test.ts b/backend/integration/superTabLiveness.test.tsindex bfc1590a6..fc4e129a4 100644--- a/backend/integration/superTabLiveness.test.ts+++ b/backend/integration/superTabLiveness.test.ts@@ -46,7 +46,7 @@ afterAll(async () => {})/** A Swarm whose Lead runs on one of host's machines and whose worker runs on another, assigned "Ship the parser". */-async function swarm({ legacy = false, client = db, hooks }: { legacy?: boolean; client?: PrismaClient; hooks?: SuperTabStoreHooks } = {}) {+async function swarm({ legacy = false, client = db, hooks, independent = false }: { legacy?: boolean; client?: PrismaClient; hooks?: SuperTabStoreHooks; independent?: boolean } = {}) {let now = 10_000_000const timed = new SuperTabStore(client, () => now, null, hooks)const tab = (await timed.create(owner, randomUUID(), 'Liveness', legacy ? undefined : 'public')).id@@ -64,7 +64,7 @@ async function swarm({ legacy = false, client = db, hooks }: { legacy?: boolean;conversationId, machineId, harnessId, name, configuration: config, lead })).result.agentId)const lead = await add('lead', 'lead-host', harness.lead, 'Lead', true)const group = String((await execute({ type: 'conversation.create', title: 'Ship the parser', brief: 'Implement it',- checks: [{ description: 'Verified', independent: false }] })).result.conversationId)+ checks: [{ description: 'Verified', independent }] })).result.conversationId)const worker = await add(group, 'test-host', harness.worker, 'Worker')const assignmentId = String((await execute({ type: 'work.assign', conversationId: group, agentId: worker })).result.assignmentId)const observe = (machineId: string, running: string[], extra: Partial<MachineObservation> = {}, store = timed) => store.observeMachine(host, tab, machineId, {@@ -552,6 +552,40 @@ function recordingGroups() {// Every machine reports every 15 s, and each report loaded, copied and compared the whole Swarm: about 1.1 MB for a busy one// (#876). It reads only the conversations its checks read, whole, and writes only what it changed.+describe('work waiting for its review', () => {+ // 2026-10-29: five Engineers who had pushed and handed over lost their tasks after 30 quiet minutes waiting for a Reviewer.+ it('stays with its Engineer through 45 quiet minutes in review or after a hand-off, and counts 30 from a review that found problems', async () => {+ const f = await swarm({ independent: true })+ const handedOver = f.clock.now+ const status = (status: 'review' | 'working', result: string) =>+ f.execute({ type: 'work.status', conversationId: f.group, assignmentId: f.assignmentId, status, result }, host, f.worker)+ /** Both machines report every minute, the worker's screen still since the hand-off, and the Lead polls. */+ const quiet = async (from: number, minutes: number) => {+ for (let minute = 1; minute <= minutes; minute++) {+ f.clock.now = from + minute * MINUTE+ await f.beat(handedOver)+ await f.leadInbox()+ }+ }+ await status('review', 'Ready for review: PR #7 at 4f9c2e1')+ await quiet(handedOver, 45)+ expect((await f.assignment()).status).toBe('review')+ // Engineers usually stay working with the hand-off as their result, since done waits for the review.+ await status('working', 'Ready for review: PR #7 at 4f9c2e1')+ await quiet(f.clock.now, 45)+ expect((await f.assignment()).status).toBe('working')+ expect(await f.lostRows()).toEqual([])+ const check = (await f.timed.read(owner, f.tab)).state.conversations.find(c => c.id === f.group)!.checks[0]!.id+ await f.execute({ type: 'work.check', conversationId: f.group, assignmentId: f.assignmentId, checkId: check, passed: false, evidence: 'Two findings' })+ const found = f.clock.now+ await quiet(found, 30)+ expect((await f.assignment()).status).toBe('working')+ f.clock.now = found + 30 * MINUTE + 1+ await f.beat(handedOver)+ expect(await f.assignment()).toMatchObject({ status: 'lost', lost: { reason: 'no progress for 30 minutes' } })+ })+})+describe('a machine\'s report', () => {/** `n` conversations whose work finished but that are not yet quiet, each with a long brief: copies of a real one. */async function finishedGroups(f: Awaited<ReturnType<typeof swarm>>, n: number) {@@ -1079,7 +1113,7 @@ describe('the delivery poll of an agent with nothing waiting', () => {counted.ops.length = 0f.clock.now += 29_999expect(await f.timed.deliveries(host, f.tab, f.lead)).toEqual([])- expect(counted.ops).toEqual(['SuperTabDelivery.findMany'])+ expect(counted.ops).toEqual(['SuperTabDelivery.aggregateRaw'])counted.ops.length = 0f.clock.now += 1expect(await f.timed.deliveries(host, f.tab, f.lead)).toEqual([])@@ -1167,7 +1201,7 @@ describe('the delivery poll of an agent with nothing waiting', () => {counted.ops.length = 0f.clock.now += 1_000expect(await other.deliveries(host, f.tab, f.lead)).toEqual([])- expect(counted.ops).toEqual(['SuperTabDelivery.findMany'])+ expect(counted.ops).toEqual(['SuperTabDelivery.aggregateRaw'])})it('runs the full checked poll each time while the shared memory cannot be read or written, and still answers', async () => {@@ -1199,7 +1233,7 @@ describe('the delivery poll of an agent with nothing waiting', () => {describe('the delivery poll of an agent with a held delivery', () => {// The open deliveries, then the grant the host speaks for its agent under, read outside the Swarm (store.ts grantHolds):// its contributor's Workspace membership, its machine and, lent by host to owner here, the contributor and the share.- const HELD_READS = ['SuperTabDelivery.findMany', 'SwarmWorkspaceMember.findUnique', 'Machine.findFirst', 'User.findUnique', 'MachineShare.findUnique']+ const HELD_READS = ['SuperTabDelivery.aggregateRaw', 'SwarmWorkspaceMember.findUnique', 'Machine.findFirst', 'User.findUnique', 'MachineShare.findUnique']/** A person's message to the Lead, read by a full poll, claimed and held by its host. */const held = async (f: Awaited<ReturnType<typeof swarm>>) => {const sent = await f.execute({ type: 'message.send', conversationId: 'lead', text: 'Status?', replyTo: null, recipientIds: [] })diff --git a/backend/integration/superTabNamedReads.test.ts b/backend/integration/superTabNamedReads.test.tsnew file mode 100644index 000000000..b89748004--- /dev/null+++ b/backend/integration/superTabNamedReads.test.ts@@ -0,0 +1,344 @@+import { randomUUID } from 'node:crypto'+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'+import type { MongoMemoryReplSet } from 'mongodb-memory-server-core'+import type { PrismaClient } from '@prisma/client'+import type { AuthUser } from '../src/lib/ssoAuth.js'+import { SuperTabStore } from '../src/superTabs/store.js'+import { listGroupIndexes, NAMED_INDEX, retryStaleIndex } from '../src/superTabs/parts/indexed.js'+import { logger } from '../src/utils/logger.js'+import { SwarmReads } from '../src/superTabs/read/service.js'+import { SwarmWorkspaces } from '../src/superTabs/workspaceStore.js'+import { agentOpenDeliveries } from '../src/superTabs/pageReads.js'+import { loadChanged } from '../src/superTabs/parts/index.js'+import { planDatabase, plan, profiled, reads } from './plans.test-support.js'++// Roadmap Phase 3 (database optimization, 2026-10-29): Prisma sends `in` and `has` as $expr, which the planner bounds by an+// index's first field alone; on 28 Oct such reads scanned 50 M documents for 220 k returned. Each read here names its index,+// and under Mongo's profiler examines no document it does not return. A fresh loopback replica set; never DATABASE_URL.+let replica: MongoMemoryReplSet+let db: PrismaClient+let store: SuperTabStore+const NOW = Date.parse('2026-10-29T08:00:00Z')+/** A person; their id is an ObjectId, as a user row's is. */+const person = (name: string): AuthUser => ({ sub: randomUUID().replaceAll('-', '').slice(0, 24), email: `${name}@example.com`, autonomousEnv: 'prod', role: 'user' })+const owner = person('owner')+/** Swarms of other people in the same environment: a read bounded by the environment alone examines these too. */+const OTHERS = 12++/** A SuperTab row of `ownerId`, in parts (format 2), with these members and machines. */+async function swarmRow(ownerId: string, fields: { memberIds?: string[]; machineIds?: string[]; cleanupMachineIds?: string[]; autonomousEnv?: string } = {}) {+ const id = `tab-${randomUUID()}`+ await db.superTab.create({ data: { id, ownerId, autonomousEnv: fields.autonomousEnv ?? 'prod', memberIds: fields.memberIds ?? [ownerId], invitedEmails: [],+ machineIds: fields.machineIds ?? [], cleanupMachineIds: fields.cleanupMachineIds ?? [], format: 2, state: { version: 2 } } })+ return id+}++beforeAll(async () => {+ ({ replica, db } = await planDatabase('swarm_named_reads_test'))+ store = new SuperTabStore(db, () => NOW)+ await listGroupIndexes(db)+ for (let i = 0; i < OTHERS; i++) {+ const other = person(`other${i}`)+ await swarmRow(other.sub, { memberIds: [other.sub, `user-guest-${i}`] })+ }+})+afterAll(async () => {+ await db?.$disconnect()+ await replica?.stop()+})++describe('the owner\'s grid poll', () => {+ it('finds the owner\'s Swarms by the owner index, examining none of anyone else\'s', async () => {+ const mine = [await swarmRow(owner.sub), await swarmRow(owner.sub)]+ // Another environment's Swarm of the same owner id is never theirs here.+ await swarmRow(owner.sub, { autonomousEnv: 'dev' })+ const entries = await profiled(db, () => store.hostGrids(owner))+ const rows = reads(entries, 'SuperTab', ['ownerId'])+ expect(rows, JSON.stringify(plan(rows))).toHaveLength(1)+ expect(rows[0]!.nreturned).toBe(mine.length)+ expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(mine.length)+ expect(rows[0]!.command?.hint, `the read names its index: ${JSON.stringify(plan(rows))}`).toBeTruthy()+ })+})++/** A person with a user row, as a signed-in person has. */+async function signedIn(name: string): Promise<AuthUser> {+ const user = person(name)+ await db.user.create({ data: { id: user.sub, externalId: `fixture-${user.sub}`, email: user.email, autonomousEnv: 'prod' } })+ return user+}++describe('a person\'s Swarm list', () => {+ let me: AuthUser+ let mine: string[]+ beforeAll(async () => {+ me = await signedIn('lister')+ // Swarms of other people, born in parts: a read bounded by the environment alone examines these too.+ for (let i = 0; i < 4; i++) await store.create(await signedIn(`maker${i}`), randomUUID(), `Theirs ${i}`)+ mine = []+ for (let i = 0; i < 3; i++) mine.push((await store.create(me, randomUUID(), `Mine ${i}`)).id)+ mine.sort()+ })++ const memberReads = (entries: Awaited<ReturnType<typeof profiled>>) => reads(entries, 'SuperTab', ['memberIds'])+ const bounded = (rows: ReturnType<typeof memberReads>, returned: number) => {+ expect(rows, JSON.stringify(plan(rows))).toHaveLength(1)+ expect(rows[0]!.nreturned).toBe(returned)+ expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(returned)+ expect(rows[0]!.keysExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(returned + 1)+ expect(rows[0]!.command?.hint, `the read names its index: ${JSON.stringify(plan(rows))}`).toBeTruthy()+ }++ it('the Swarms page reads only the person\'s Swarms, in id order, by the member index', async () => {+ let listed: Awaited<ReturnType<SwarmReads['list']>> | undefined+ const entries = await profiled(db, async () => { listed = await new SwarmReads(store, { now: () => NOW }).list(me) })+ expect(listed!.tabs.map(t => t.id)).toEqual(mine)+ expect(listed!.next).toBeNull()+ bounded(memberReads(entries), mine.length)+ })++ it('the store\'s list and its later page read the same way', async () => {+ let first: Awaited<ReturnType<SuperTabStore['list']>> | undefined+ let later: Awaited<ReturnType<SuperTabStore['list']>> | undefined+ const whole = await profiled(db, async () => { first = await store.list(me) })+ expect(first!.tabs.map(t => t.id)).toEqual(mine)+ bounded(memberReads(whole), mine.length)+ const after = await profiled(db, async () => { later = await store.list(me, mine[0]) })+ expect(later!.tabs.map(t => t.id)).toEqual(mine.slice(1))+ bounded(memberReads(after), mine.length - 1)+ })++ it('a Workspace removal finds only the removed person\'s Swarms of that Workspace', async () => {+ const workspaceId = (await db.superTab.findUniqueOrThrow({ where: { id: mine[0]! } })).workspaceId!+ const left: string[] = []+ const workspaces = new SwarmWorkspaces(db, { transaction: body => db.$transaction(body), now: () => NOW,+ leave: async (_person, tabId) => { left.push(tabId) } })+ await db.swarmWorkspaceRemoval.create({ data: { id: `${workspaceId}:${me.sub}:g1`, workspaceId, userId: me.sub, email: me.email, generation: 'g1',+ autonomousEnv: 'prod', removedAt: new Date(NOW), removedBy: owner.sub, finishedAt: null, purgeAt: null } })+ const entries = await profiled(db, () => workspaces.finishPending(workspaceId, me.sub))+ const inWorkspace = (await db.superTab.findMany({ where: { workspaceId }, select: { id: true } })).map(r => r.id).filter(id => mine.includes(id))+ expect(left.sort()).toEqual(inWorkspace.sort())+ const rows = memberReads(entries)+ expect(rows, JSON.stringify(plan(rows))).toHaveLength(1)+ // Bounded by the person's Swarms, whichever Workspace each is in.+ expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(mine.length)+ expect(rows[0]!.command?.hint, `the read names its index: ${JSON.stringify(plan(rows))}`).toBeTruthy()+ })+})++describe('an agent\'s open deliveries', () => {+ const tabId = `tab-${randomUUID()}`, agentId = `${tabId}-agent`+ const delivery = (id: string, fields: { agentId?: string; status: string; createdAt: number; conversationId?: string }) => ({ id: `${tabId}-${id}`, tabId,+ conversationId: fields.conversationId ?? 'c1', messageId: `${tabId}-m-${id}`, agentId: fields.agentId ?? agentId, machineId: 'm1', membershipGeneration: 'g',+ authorKind: 'person', authorId: owner.sub, authorGeneration: 'g', status: fields.status, createdAt: new Date(fields.createdAt) })+ beforeAll(async () => {+ await db.superTabDelivery.createMany({ data: [+ // Its own finished deliveries, which a read bounded by the agent alone examines too.+ ...Array.from({ length: 10 }, (_, i) => delivery(`done-${i}`, { status: i % 2 ? 'confirmed' : 'cancelled', createdAt: NOW - 100_000 + i })),+ // Another agent's open ones.+ ...Array.from({ length: 5 }, (_, i) => delivery(`theirs-${i}`, { agentId: `${tabId}-other`, status: 'queued', createdAt: NOW - 50_000 + i })),+ delivery('claimed', { status: 'claimed', createdAt: NOW - 3000, conversationId: 'c2' }),+ delivery('queued', { status: 'queued', createdAt: NOW - 1000 }),+ ] })+ // One stored before its optional fields existed: Prisma reads each as null.+ await db.$runCommandRaw({ insert: 'SuperTabDelivery', documents: [{ _id: `${tabId}-old`, tabId, conversationId: 'c1', messageId: `${tabId}-m-old`, agentId,+ machineId: 'm1', membershipGeneration: 'g', authorKind: 'agent', authorId: 'lead', authorGeneration: 'g', status: 'uncertain',+ createdAt: { $date: new Date(NOW - 2000).toISOString() }, updatedAt: { $date: new Date(NOW - 2000).toISOString() } }] })+ })++ it('reads only its own open ones, oldest first, by the agent index', async () => {+ let open: Awaited<ReturnType<typeof agentOpenDeliveries>> = []+ const entries = await profiled(db, async () => { open = await db.$transaction(tx => agentOpenDeliveries(tx, tabId, agentId)) })+ expect(open.map(d => d.id)).toEqual([`${tabId}-claimed`, `${tabId}-old`, `${tabId}-queued`])+ const rows = reads(entries, 'SuperTabDelivery', ['tabId', 'agentId', 'status'])+ expect(rows, JSON.stringify(plan(rows))).toHaveLength(1)+ expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(3)+ expect(rows[0]!.keysExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(3 + 3)+ expect(rows[0]!.command?.hint, `the read names its index: ${JSON.stringify(plan(rows))}`).toBeTruthy()+ })++ it('returns each row as Prisma reads it, outside a transaction too', async () => {+ const prisma = await db.superTabDelivery.findMany({ where: { tabId, agentId, status: { in: ['queued', 'claimed', 'uncertain'] } }, orderBy: { createdAt: 'asc' } })+ expect(await agentOpenDeliveries(db, tabId, agentId)).toEqual(prisma)+ const old = prisma.find(d => d.id === `${tabId}-old`)!+ expect(old.nativeContextId).toBeNull()+ expect(old.holdSince).toBeNull()+ })+})++describe('what changed in a set of Swarms since a cursor', () => {+ const OLD = new Date(NOW - 3_600_000), SINCE = new Date(NOW - 1_800_000), LATER = new Date(NOW - 60_000)+ const SWARM_PARTS = ['swarmHead', 'swarmMember', 'swarmAgent', 'swarmGroup', 'swarmMachine', 'swarmStart', 'swarmProgress'] as const+ let ids: string[]+ beforeAll(async () => {+ const maker = await signedIn('changer')+ ids = []+ for (let i = 0; i < 3; i++) ids.push((await store.create(maker, randomUUID(), `Changed ${i}`)).id)+ for (const model of SWARM_PARTS) await (db[model] as unknown as { updateMany(args: unknown): Promise<unknown> }).updateMany({ where: { tabId: { in: ids } }, data: { changedAt: OLD } })+ const machine = (key: string, changedAt: Date, readAt: Date | null) => ({ id: `${ids[0]}:${key}`, tabId: ids[0]!, key, version: 1, changedAt, ordinal: 1,+ data: { machineId: key }, machineId: key, cleanupOwnerIds: [], readAt })+ // Quiet machines of the first Swarm: a read bounded by the Swarm alone examines these too.+ await db.swarmMachine.createMany({ data: [...Array.from({ length: 6 }, (_, i) => machine(`machine:quiet-${i}`, OLD, OLD)),+ machine('machine:read', OLD, LATER), machine('machine:changed', LATER, null), machine('machine:both', LATER, LATER)] })+ await db.swarmMember.updateMany({ where: { tabId: ids[0]! }, data: { changedAt: LATER } })+ })++ it('reads each kind by its changes index, and machines also by when they were read, examining only what changed', async () => {+ let changed = new Map<string, Array<{ kind: string; key: string; readAt?: number }>>()+ const entries = await profiled(db, async () => { changed = await db.$transaction(tx => loadChanged(tx, ids, SINCE)) })+ const keys = (tabId: string) => changed.get(tabId)!.map(p => `${p.kind}:${p.key}`).sort()+ const members = (await db.swarmMember.findMany({ where: { tabId: ids[0]! } })).map(m => `member:${m.key}`)+ expect(keys(ids[0]!)).toEqual([...members, 'machine:machine:both', 'machine:machine:changed', 'machine:machine:read'].sort())+ expect(keys(ids[1]!)).toEqual([])+ expect(keys(ids[2]!)).toEqual([])+ expect(changed.get(ids[0]!)!.find(p => p.key === 'machine:read')!.readAt).toBe(LATER.getTime())+ const swarmReads = entries.filter(e => /\.Swarm(Head|Member|Agent|Group|Machine|Start|Progress)$/.test(e.ns))+ expect(swarmReads.length, JSON.stringify(plan(swarmReads))).toBe(8)+ for (const read of swarmReads) {+ expect(read.docsExamined, `${read.ns} ${JSON.stringify(plan([read]))}`).toBeLessThanOrEqual(read.nreturned!)+ expect(read.command?.hint, `${read.ns} names its index: ${JSON.stringify(plan([read]))}`).toBeTruthy()+ }+ })+})++describe('a conversation\'s page of messages', () => {+ let maker: AuthUser+ let tabId: string+ let conversationId: string+ // One command's rows share a sequence: 10 holds five messages, read by id within it.+ const ids = [...Array.from({ length: 9 }, (_, i) => `m${String(i + 1).padStart(2, '0')}`), 'm10a', 'm10b', 'm10c', 'm10d', 'm10e',+ ...Array.from({ length: 20 }, (_, i) => `m${i + 11}`)]+ const sequenceOf = (id: string) => Number(id.slice(1, 3))+ beforeAll(async () => {+ maker = await signedIn('pager')+ tabId = (await store.create(maker, randomUUID(), 'Pages')).id+ conversationId = (await db.swarmGroup.findFirstOrThrow({ where: { tabId, deleted: false } })).key+ // One a route row with a file, as commands.ts and attachments.ts write them: its numbers come back as Prisma reads them.+ const route = { source: { kind: 'route', decisionId: 'd1', via: 'policy', p: 0.75, belowFloor: false, why: 'Small change', pick: { id: 'c0', title: 'Builder' },+ alternatives: [{ id: 'c1', title: 'New agent' }] }, attachments: [{ id: 'a1', name: 'plan.txt', mime: 'text/plain', size: 2048, url: 'https://files.example/a1' }],+ replyTo: `${tabId}-m04`, mentions: [maker.sub], alsoInChat: true }+ await db.superTabMessage.createMany({ data: ids.map(id => ({ id: `${tabId}-${id}`, tabId, conversationId, sequence: sequenceOf(id), text: id,+ author: { kind: 'person', id: maker.sub, name: maker.email, membershipGeneration: tabId }, recipientIds: [], mentions: [], createdAt: new Date(NOW),+ ...id === 'm05' ? route : {} })) })+ })++ const pageReads = (entries: Awaited<ReturnType<typeof profiled>>) => reads(entries, 'SuperTabMessage', ['conversationId', 'sequence'])+ const boundedPage = (rows: ReturnType<typeof pageReads>) => {+ expect(rows.length, JSON.stringify(plan(rows))).toBeGreaterThan(0)+ for (const row of rows) {+ expect(row.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(row.nreturned!)+ expect(row.keysExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(row.nreturned! + 1)+ expect(row.command?.hint, `the read names its index: ${JSON.stringify(plan(rows))}`).toBeTruthy()+ }+ }++ it('scrolling back from inside a shared sequence reads only the page, by the sequence index', async () => {+ let page: Awaited<ReturnType<SuperTabStore['messages']>> | undefined+ const entries = await profiled(db, async () => { page = await store.messages(maker, tabId, conversationId, { before: 10, beforeId: `${tabId}-m10c` }) })+ expect(page!.messages.map(m => m.text)).toEqual(ids.slice(0, ids.indexOf('m10c')))+ expect(page!.next).toBeNull()+ boundedPage(pageReads(entries))+ })++ it('reading on from inside a shared sequence reads only what follows', async () => {+ let page: Awaited<ReturnType<SuperTabStore['messages']>> | undefined+ const entries = await profiled(db, async () => { page = await store.messages(maker, tabId, conversationId, { after: 10, afterId: `${tabId}-m10b` }) })+ expect(page!.messages.map(m => m.text)).toEqual(ids.slice(ids.indexOf('m10c')))+ boundedPage(pageReads(entries))+ })++ it('returns each message as Prisma reads it', async () => {+ const page = await store.messages(maker, tabId, conversationId, { before: 10, beforeId: `${tabId}-m10c` })+ const prisma = await db.superTabMessage.findMany({ where: { tabId, conversationId, id: { in: page.messages.map(m => m.id) } }, orderBy: [{ sequence: 'asc' }, { id: 'asc' }] })+ expect(page.messages.map(({ reactions: _r, deliveries: _d, ...m }) => m)).toEqual(prisma.map(m => ({ ...m, mentions: m.mentions ?? [] })))+ expect(page.messages.find(m => m.text === 'm05')).toMatchObject({ source: { kind: 'route', p: 0.75 }, attachments: [{ size: 2048 }], alsoInChat: true })+ })+})++describe('who a named read answers', () => {+ it('a Swarm list leaves out a Swarm the person was removed from, and one of another environment', async () => {+ const me = await signedIn('removed')+ const kept = (await store.create(me, randomUUID(), 'Kept')).id, left = (await store.create(me, randomUUID(), 'Left')).id+ // Their removal as parts/commit.ts writes it: memberIds no longer holds them.+ await db.superTab.update({ where: { id: left }, data: { memberIds: { set: [owner.sub] } } })+ await swarmRow(owner.sub, { memberIds: [me.sub], autonomousEnv: 'dev' })+ expect((await new SwarmReads(store, { now: () => NOW }).list(me)).tabs.map(t => t.id)).toEqual([kept])+ expect((await store.list(me)).tabs.map(t => t.id)).toEqual([kept])+ })++ it('an agent id reused in another Swarm reads only this Swarm\'s deliveries', async () => {+ const [here, there] = [`tab-${randomUUID()}`, `tab-${randomUUID()}`]+ const row = (tabId: string) => ({ id: `${tabId}-d`, tabId, conversationId: 'c', messageId: `${tabId}-m`, agentId: 'same-agent', machineId: 'm',+ membershipGeneration: 'g', authorKind: 'person', authorId: owner.sub, authorGeneration: 'g', status: 'queued' })+ await db.superTabDelivery.createMany({ data: [row(here), row(there)] })+ expect((await agentOpenDeliveries(db, here, 'same-agent')).map(d => d.id)).toEqual([`${here}-d`])+ })++ it('a message id of another conversation or Swarm reads nothing', async () => {+ const me = await signedIn('asker')+ const tabId = (await store.create(me, randomUUID(), 'Asks')).id+ const conversationId = (await db.swarmGroup.findFirstOrThrow({ where: { tabId, deleted: false } })).key+ const author = { kind: 'person', id: me.sub, name: me.email, membershipGeneration: tabId }+ await db.superTabMessage.createMany({ data: [+ { id: `${tabId}-mine`, tabId, conversationId, sequence: 1, text: 'mine', author, recipientIds: [], mentions: [] },+ { id: `${tabId}-other`, tabId, conversationId: 'another-conversation', sequence: 1, text: 'other', author, recipientIds: [], mentions: [] },+ { id: 'elsewhere', tabId: 'another-swarm', conversationId, sequence: 1, text: 'elsewhere', author, recipientIds: [], mentions: [] },+ ] })+ expect((await store.messages(me, tabId, conversationId, { messageId: `${tabId}-mine` })).messages.map(m => m.text)).toEqual(['mine'])+ for (const messageId of [`${tabId}-other`, 'elsewhere']) {+ expect((await store.messages(me, tabId, conversationId, { messageId })).messages).toEqual([])+ }+ })+})++describe('a named read whose index the database lacks', () => {+ /** Drops `key` from `collection` around `run`, then builds it again under its old name. */+ async function without<T>(collection: string, key: Record<string, number>, run: () => Promise<T>): Promise<T> {+ const listed = await db.$runCommandRaw({ listIndexes: collection }) as unknown as { cursor: { firstBatch: Array<{ name: string; key: Record<string, number> }> } }+ const name = listed.cursor.firstBatch.find(index => JSON.stringify(Object.keys(index.key)) === JSON.stringify(Object.keys(key)))!.name+ await db.$runCommandRaw({ dropIndexes: collection, index: name })+ try {+ return await run()+ } finally {+ await db.$runCommandRaw({ createIndexes: collection, indexes: [{ key, name }] })+ await listGroupIndexes(db)+ }+ }++ it('reads without it once listed as missing, and says so', async () => {+ const me = await signedIn('unindexed')+ const tabId = (await store.create(me, randomUUID(), 'Unindexed')).id+ const said = vi.spyOn(logger, 'error')+ try {+ await without('SuperTab', NAMED_INDEX.SuperTab.members, async () => {+ await listGroupIndexes(db)+ expect(said).toHaveBeenCalledWith(expect.stringContaining('SuperTab lacks indexes'), { missing: [NAMED_INDEX.SuperTab.members] })+ expect((await store.list(me)).tabs.map(t => t.id)).toEqual([tabId])+ })+ } finally {+ said.mockRestore()+ }+ })++ it('removed after the last listing, a read outside a transaction and one inside both still answer', async () => {+ const me = await signedIn('dropped')+ const tabId = (await store.create(me, randomUUID(), 'Dropped')).id+ await db.superTabDelivery.create({ data: { id: `${tabId}-d`, tabId, conversationId: 'c', messageId: `${tabId}-m`, agentId: 'a', machineId: 'm',+ membershipGeneration: 'g', authorKind: 'person', authorId: me.sub, authorGeneration: 'g', status: 'queued' } })+ await listGroupIndexes(db)+ const said = vi.spyOn(logger, 'error')+ try {+ await without('SuperTab', NAMED_INDEX.SuperTab.members, async () => {+ expect((await store.list(me)).tabs.map(t => t.id)).toEqual([tabId])+ })+ await listGroupIndexes(db)+ await without('SuperTabDelivery', NAMED_INDEX.SuperTabDelivery.agentOpen, async () => {+ // In a transaction the failed hint aborts it; its runner runs it again without hints.+ expect((await retryStaleIndex(() => db.$transaction(tx => agentOpenDeliveries(tx, tabId, 'a')))).map(d => d.id)).toEqual([`${tabId}-d`])+ })+ expect(said).toHaveBeenCalledWith(expect.stringContaining('lacks an index'), expect.objectContaining({ collection: 'SuperTabDelivery' }))+ } finally {+ said.mockRestore()+ }+ })+})diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex 88a898634..b6cf2a1d7 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -19,7 +19,7 @@ import { nextMachineShareGrants } from '../src/lib/machineSharePolicy.js'import { DEFAULT_ROUTING_POLICY } from '../src/superTabs/routingPolicy.js'import { stableId, type SuperTabState } from '../src/superTabs/model.js'import { ensureTerminalExpiry, TERMINAL_EXPIRY_MS } from '../src/superTabs/terminal.js'-import { ensureMentionExpiry, MENTION_EXPIRY_MS } from '../src/superTabs/mentions.js'+import { ensureMentionExpiry, MENTION_EXPIRY_MS, swarmsWithTags } from '../src/superTabs/mentions.js'import * as parts from '../src/superTabs/parts/index.js'import { swarmTransaction } from '../src/superTabs/cache.js'import { guardedWrite, PartConflict } from '../src/superTabs/parts/write.js'@@ -3227,6 +3227,51 @@ describe('Lead mentions', () => {expect((await store.messages(owner, tab, group, {})).messages.find(m => m.id === messageId)!.mentions).toEqual([peer.sub])})+ // Desktop's list (?mentions=1) carries each Swarm's waiting tags, so it makes no mentions call per Swarm.+ const listed = async (user: AuthUser, tab: string, query = '?mentions=1') => {+ let after: string | undefined+ do {+ const response = await app.inject({ method: 'GET', url: `/api/super-tabs/list${query}${after ? `${query ? '&' : '?'}after=${after}` : ''}`,+ headers: { authorization: `Bearer ${user.sub}` } })+ expect(response.statusCode, response.body).toBe(200)+ const page = response.json().data as { tabs: Array<Record<string, unknown>>; next: string | null }+ const row = page.tabs.find(t => t.id === tab)+ if (row) return row+ after = page.next ?? undefined+ } while (after)+ throw new Error('Swarm not listed')+ }++ it('counts each listed Swarm’s waiting tags in the list when asked, as its own state does', async () => {+ const { tab } = await tagged()+ const own = (await app.inject({ method: 'GET', url: `/api/super-tabs/${tab}/parts`, headers: { authorization: `Bearer ${peer.sub}` } }))+ .json().data.derived as { mentionsWaiting: number; mentionsDigest: string }+ expect(own).toMatchObject({ mentionsWaiting: 1, mentionsDigest: expect.any(String) })+ expect(await listed(peer, tab)).toMatchObject({ id: tab, mentionsWaiting: 1, mentionsDigest: own.mentionsDigest })+ expect(await listed(owner, tab)).toMatchObject({ id: tab, mentionsWaiting: 0 })+ expect(await listed(peer, tab, '')).not.toHaveProperty('mentionsWaiting')+ // A Swarm with no tags has the digest the Swarm's own state gives it.+ const ownerDerived = (await app.inject({ method: 'GET', url: `/api/super-tabs/${tab}/parts`, headers: { authorization: `Bearer ${owner.sub}` } }))+ .json().data.derived as { mentionsDigest: string }+ expect(await listed(owner, tab)).toMatchObject({ mentionsDigest: ownerDerived.mentionsDigest })+ })++ it('finds the Swarms holding a tag by the tag index, never a scan of every tag', async () => {+ const { tab } = await tagged()+ const plan = JSON.stringify(await db.$runCommandRaw({ explain: { aggregate: 'SuperTabMention', pipeline: swarmsWithTags([tab], peer.sub, Date.now()),+ cursor: {} }, verbosity: 'queryPlanner' }))+ expect(plan).toContain('IXSCAN')+ expect(plan).not.toContain('COLLSCAN')+ })++ it('leaves a tag out of the list’s count once the person can no longer read its conversation', async () => {+ const { tab } = await tagged()+ expect(await listed(peer, tab)).toMatchObject({ mentionsWaiting: 1 })+ await run(tab, { type: 'project.sharing', projectId: 'lead', visibility: 'private', memberIds: [] })+ expect(await listed(peer, tab)).toMatchObject({ mentionsWaiting: 0 })+ expect((await waiting(tab, peer)).mentionsWaiting).toBe(0)+ })+it('lists a person’s tag of another person under the author’s username, never their email', async () => {const { tab, group } = await tagged()await run(tab, { type: 'member.username', username: 'boss' })diff --git a/backend/package-lock.json b/backend/package-lock.jsonindex 37f1c0420..a0079b2d0 100644--- a/backend/package-lock.json+++ b/backend/package-lock.json@@ -29,6 +29,7 @@"@vitest/coverage-v8": "4.1.11","concurrently": "^9.1.2","esbuild": "^0.27.2",+ "mongodb": "6.21.0","mongodb-memory-server-core": "^10.4.3","prisma": "^5.22.0","tsx": "^4.16.2",diff --git a/backend/package.json b/backend/package.jsonindex 5f110ee8c..d926d1732 100644--- a/backend/package.json+++ b/backend/package.json@@ -49,6 +49,7 @@"@vitest/coverage-v8": "4.1.11","concurrently": "^9.1.2","esbuild": "^0.27.2",+ "mongodb": "6.21.0","mongodb-memory-server-core": "^10.4.3","prisma": "^5.22.0","tsx": "^4.16.2",diff --git a/backend/pnpm-lock.yaml b/backend/pnpm-lock.yamlindex e97325fea..2c9d98c0a 100644--- a/backend/pnpm-lock.yaml+++ b/backend/pnpm-lock.yaml@@ -63,6 +63,9 @@ importers:esbuild:specifier: ^0.27.2version: 0.27.7+ mongodb:+ specifier: 6.21.0+ version: 6.21.0mongodb-memory-server-core:specifier: ^10.4.3version: 10.4.3diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex d667eb3b8..354769f70 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1046,7 +1046,11 @@ model SuperTab {updatedAt DateTime @updatedAt@@index([autonomousEnv, workspaceId])- @@index([autonomousEnv, memberIds])+ /// An owner's Swarms in id order: the grid poll names it (superTabs/parts/indexed.ts NAMED_INDEX.SuperTab.owner).+ @@index([autonomousEnv, ownerId, id])+ /// By id within a member: Swarm lists read 100 at a time in id order, and a Workspace removal finds the person's Swarms+ /// (superTabs/swarmRows.ts).+ @@index([autonomousEnv, memberIds, id])/// By id within an address: the invitation list reads the first 100 in id order (superTabs/invitedSwarms.ts).@@index([autonomousEnv, invitedEmails, id])@@index([autonomousEnv, machineIds])@@ -1323,6 +1327,8 @@ model SuperTabRouteDecision {outcomeAt DateTime?/// Its attempt's run: what it ran on, how it was paid, its session's token totals at start and end (superTabs/costs/attempts.ts).run Json?+ /// What its attempt added to its model's evidence, so a later change adds only the difference (superTabs/evidence/store.ts).+ evidence Json?createdAt DateTime @default(now())@@index([tabId, createdAt])@@ -1330,6 +1336,61 @@ model SuperTabRouteDecision {@@index([tabId, assignmentId])}+/// How one model did on one kind of job in one week of one project of a Swarm (superTabs/evidence/store.ts): counts and sums+/// only, never a person, an agent or task text. `id` is the hash of the Swarm, project, engine, model, kind and week. Kept 180 days.+model SuperTabModelEvidence {+ id String @id @map("_id")+ tabId String+ /// The project of the groups its attempts ran in: the report shows a reader only projects they see.+ projectId String+ engine String+ model String+ kind String+ /// Monday 00:00 UTC of the week its attempts started.+ week DateTime+ attempts Float @default(0)+ firstReviews Float @default(0)+ firstReviewPassed Float @default(0)+ reworkRounds Float @default(0)+ shipped Float @default(0)+ minutesToShipSum Float @default(0)+ minutesToShipCount Float @default(0)+ fixesAfterMerge Float @default(0)+ tokensInput Float @default(0)+ tokensOutput Float @default(0)+ tokensCacheRead Float @default(0)+ tokensCacheWrite Float @default(0)+ tokensKnown Float @default(0)+ apiCost Float @default(0)+ costKnown Float @default(0)+ costUnknown Float @default(0)+ spend Float @default(0)+ spendKnown Float @default(0)+ updatedAt DateTime++ @@index([tabId, week])+ /// The hourly sweep's prune across every Swarm (superTabs/sweeps.ts).+ @@index([week])+}++/// One model's last ten first-review results on one kind of job in one project of a Swarm, oldest first: [{ a: assignment id, at: its start,+/// passed }] (superTabs/evidence/store.ts). Routing reads it for a model under 50% and its recovery. Kept 180 days after its+/// last change.+model SuperTabModelRecent {+ id String @id @map("_id")+ tabId String+ projectId String+ engine String+ model String+ kind String+ results Json+ updatedAt DateTime++ @@index([tabId, updatedAt])+ /// The hourly sweep's prune across every Swarm (superTabs/sweeps.ts).+ @@index([updatedAt])+}+model SuperTabStopReceipt {id String @id @map("_id")tabId Stringdiff --git a/backend/scripts/atlas-snapshot.ts b/backend/scripts/atlas-snapshot.tsnew file mode 100644index 000000000..7a5983eff--- /dev/null+++ b/backend/scripts/atlas-snapshot.ts@@ -0,0 +1,376 @@+/**+ * Saves the database numbers of DB roadmap Phase 1 (docs/superpowers/specs/2026-10-29-database-optimization-roadmap.md,+ * "What we measured") for a before/after comparison: a day of the cluster's process metrics and its slow-query log from+ * the Atlas Admin API, and each collection's documents, data and index sizes read from a secondary.+ *+ * ATLAS_GROUP_ID=… ATLAS_CLUSTER=autonomous-code-prod \+ * ATLAS_CLIENT_ID=… ATLAS_CLIENT_SECRET=… # a service account, or ATLAS_PUBLIC_KEY / ATLAS_PRIVATE_KEY+ * MONGO_READONLY_URL=… # the read-only user+ * npx tsx scripts/atlas-snapshot.ts --label before [--out DIR]+ *+ * npx tsx scripts/atlas-snapshot.ts --compare atlas-snapshots/before-… atlas-snapshots/after-…+ *+ * Safety: it only reads. The database URL is always switched to readPreference=secondary, and the run is refused when+ * the user has any permission beyond reading. It never reads DATABASE_URL. Privacy: the slow log keeps each operation's namespace, plan, timings+ * and the keys of its filter, never the logged line, which holds the query's values. Secrets come only from the+ * environment and are never printed. A part whose settings are missing is skipped and named; a part that fails fails+ * the run (exit 1) after the other parts are saved.+ */+import { createHash, randomBytes } from 'node:crypto'+import { mkdir, readFile, writeFile } from 'node:fs/promises'+import { join } from 'node:path'+import { pathToFileURL } from 'node:url'+import { MongoClient } from 'mongodb'+import { filterShape } from '../src/lib/queryStats.js'++const ATLAS_VERSION = 'application/vnd.atlas.2023-01-01+json'+const DAY_MS = 86_400_000++/** What the roadmap's table reads. PROCESS_CPU in the summary is user + kernel. */+export const METRICS = ['PROCESS_NORMALIZED_CPU_USER', 'PROCESS_NORMALIZED_CPU_KERNEL', 'SYSTEM_NORMALIZED_CPU_USER',+ 'OPCOUNTER_QUERY', 'OPCOUNTER_GETMORE', 'OPCOUNTER_CMD', 'OPCOUNTER_UPDATE', 'OPCOUNTER_INSERT', 'OPCOUNTER_DELETE',+ 'DOCUMENT_METRICS_RETURNED', 'NETWORK_BYTES_OUT', 'QUERY_TARGETING_SCANNED_OBJECTS_PER_RETURNED', 'QUERY_TARGETING_SCANNED_PER_RETURNED',+ 'OP_EXECUTION_TIME_READS', 'OP_EXECUTION_TIME_WRITES', 'SYSTEM_MEMORY_AVAILABLE', 'CONNECTIONS']++/** The summary's rows: label, and a factor to the unit the label names. */+const ROWS: [string, string, number][] = [+ ['PROCESS_CPU', 'Process CPU (%)', 1], ['OPCOUNTER_QUERY', 'Queries / s', 1], ['OPCOUNTER_GETMORE', 'getMores / s', 1],+ ['OPCOUNTER_CMD', 'Commands / s', 1], ['OPCOUNTER_UPDATE', 'Updates / s', 1], ['OPCOUNTER_INSERT', 'Inserts / s', 1],+ ['DOCUMENT_METRICS_RETURNED', 'Documents returned / s', 1], ['NETWORK_BYTES_OUT', 'Network out (MB/s)', 1e-6],+ ['QUERY_TARGETING_SCANNED_OBJECTS_PER_RETURNED', 'Scanned per returned', 1], ['OP_EXECUTION_TIME_READS', 'Read time (ms)', 1],+ ['OP_EXECUTION_TIME_WRITES', 'Write time (ms)', 1], ['SYSTEM_MEMORY_AVAILABLE', 'Memory available (MB)', 1e-6], ['CONNECTIONS', 'Connections', 1],+]+/** Atlas units → bytes, for the rows above that are sizes. */+const BYTES: Record<string, number> = { BYTES: 1, KILOBYTES: 1e3, MEGABYTES: 1e6, GIGABYTES: 1e9, BYTES_PER_SECOND: 1, KILOBYTES_PER_SECOND: 1e3,+ MEGABYTES_PER_SECOND: 1e6, GIGABYTES_PER_SECOND: 1e9 }++type Stat = { average: number; peak: number; latest: number }+type Measurement = { name: string; units: string; dataPoints: { timestamp: string; value: number | null }[] }+type Process = { id: string; hostname: string; port: number; typeName: string; userAlias?: string }+type SlowOp = { at: string; ns: string; op: string; shape: string; plan: string; ms: number; docsExamined?: number; keysExamined?: number; returned?: number }+export type SlowSummary = { count: number; unreadable: number; totalSeconds: number; peakSecondsPerMinute: number+ top: { ns: string; op: string; shape: string; count: number; seconds: number }[] }+export type Sizes = { primary: string; readFrom: string; dataBytes: number; indexBytes: number+ collections: { name: string; count: number; dataBytes: number; storageBytes: number; indexBytes: number; nindexes: number }[] }+export type Summary = { label: string; takenAt: string; skipped: string[]; failed: string[]; primaryProcess?: string+ primary?: Record<string, Stat>; units?: Record<string, string>; slowOps?: SlowSummary; sizes?: Sizes }++/* ---------- safety ---------- */++const URL_PARTS = /^(mongodb(?:\+srv)?:\/\/)(?:([^@/]*)@)?([^/?]+)(\/[^?]*)?(?:\?(.*))?$/++/** The URL with readPreference=secondary and retryWrites=false, whatever it asked. */+export function secondaryUrl(url: string): string {+ const parts = URL_PARTS.exec(url)+ if (!parts) throw new Error('MONGO_READONLY_URL is not a mongodb:// or mongodb+srv:// URL.')+ const [, scheme, auth, hosts, path, query] = parts+ const params = new URLSearchParams(query ?? '')+ params.set('readPreference', 'secondary')+ params.set('retryWrites', 'false')+ return `${scheme}${auth ? `${auth}@` : ''}${hosts}${path || '/'}?${params}`+}++const hostsOf = (url: string) => (URL_PARTS.exec(url)?.[3] ?? '').split(',').map(h => h.replace(/:\d+$/, ''))+const LOOPBACK = new Set(['127.0.0.1', 'localhost', '[::1]'])++/** Any text with each URL's password as `***`. */+export function redactUrl(text: string): string {+ return text.replace(/(mongodb(?:\+srv)?:\/\/[^:@/\s]+):[^@/\s]+@/g, '$1:***@')+}++/** Permissions that only read: MongoDB's built-in read and readAnyDatabase roles, and the read-only monitoring ones of+ * clusterMonitor. Anything else (a write, a root user's anyAction, emptycapped, a permission added later) is refused. */+const READ_ONLY = new Set(['find', 'listCollections', 'listIndexes', 'listSearchIndexes', 'listDatabases', 'collStats', 'dbStats', 'dbHash',+ 'changeStream', 'killCursors', 'planCacheRead', 'useUUID', 'serverStatus', 'replSetGetStatus', 'replSetGetConfig', 'getLog', 'top', 'indexStats',+ 'connPoolStats', 'hostInfo', 'inprog', 'netstat', 'getCmdLineOpts', 'getParameter', 'listSessions', 'getDefaultRWConcern', 'listShards',+ 'getShardMap', 'shardingState', 'operationMetrics', 'checkMetadataConsistency'])++type ConnectionStatus = { authInfo?: { authenticatedUsers?: unknown[]; authenticatedUserPrivileges?: { actions?: string[] }[] } }++/** Refuses a user with any permission beyond reading, and a remote database reached without signing in. */+export function assertReadOnly(status: ConnectionStatus, host: string): void {+ const users = status.authInfo?.authenticatedUsers ?? []+ if (!users.length) {+ if (LOOPBACK.has(host)) return+ throw new Error('Refused: a database that is not on this computer, without signing in. Use the read-only user.')+ }+ const actions = new Set((status.authInfo?.authenticatedUserPrivileges ?? []).flatMap(p => p.actions ?? []))+ const more = [...actions].filter(a => !READ_ONLY.has(a)).sort()+ if (more.length) throw new Error(`Refused: this user can do more than read (${more.join(', ')}). Use the read-only user.`)+}++/* ---------- Atlas Admin API ---------- */++type Auth = { kind: 'service'; clientId: string; clientSecret: string } | { kind: 'digest'; publicKey: string; privateKey: string }++function atlasClient(base: string, auth: Auth) {+ let token: string | undefined+ const md5 = (s: string) => createHash('md5').update(s).digest('hex')++ async function bearer(): Promise<string> {+ if (token) return token+ if (auth.kind !== 'service') throw new Error('unreachable')+ const response = await fetch(`${base}/api/oauth/token`, { method: 'POST', body: 'grant_type=client_credentials',+ headers: { authorization: `Basic ${Buffer.from(`${auth.clientId}:${auth.clientSecret}`).toString('base64')}`,+ 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' } })+ if (!response.ok) throw new Error(`Atlas refused the service account (${response.status}).`)+ token = (await response.json() as { access_token: string }).access_token+ return token+ }++ function digest(challenge: string, uri: string): string {+ if (auth.kind !== 'digest') throw new Error('unreachable')+ const field = (name: string) => new RegExp(`${name}="?([^",]+)"?`).exec(challenge)?.[1] ?? ''+ const realm = field('realm'), nonce = field('nonce'), cnonce = randomBytes(8).toString('hex'), nc = '00000001'+ const response = md5(`${md5(`${auth.publicKey}:${realm}:${auth.privateKey}`)}:${nonce}:${nc}:${cnonce}:auth:${md5(`GET:${uri}`)}`)+ return `Digest username="${auth.publicKey}", realm="${realm}", nonce="${nonce}", uri="${uri}", qop=auth, nc=${nc}, cnonce="${cnonce}", response="${response}", algorithm=MD5`+ }++ return async function get<T>(path: string, query: [string, string][] = []): Promise<T> {+ const search = query.length ? `?${new URLSearchParams(query)}` : ''+ const uri = `/api/atlas/v2${path}${search}`+ const headers: Record<string, string> = { accept: ATLAS_VERSION }+ if (auth.kind === 'service') headers.authorization = `Bearer ${await bearer()}`+ let response = await fetch(`${base}${uri}`, { headers })+ const challenge = response.headers.get('www-authenticate')+ if (auth.kind === 'digest' && response.status === 401 && challenge?.startsWith('Digest ')) {+ await response.body?.cancel()+ response = await fetch(`${base}${uri}`, { headers: { ...headers, authorization: digest(challenge, uri) } })+ }+ if (!response.ok) throw new Error(`Atlas answered ${response.status} to ${path}.`)+ return await response.json() as T+ }+}++function stat(points: number[]): Stat | undefined {+ if (!points.length) return undefined+ const round = (n: number) => Math.round(n * 100) / 100+ return { average: round(points.reduce((a, b) => a + b, 0) / points.length), peak: round(Math.max(...points)), latest: round(points.at(-1)!) }+}++/** A day of the primary's metrics, by name, with PROCESS_CPU as user + kernel at each point. */+function summarizeMeasurements(measurements: Measurement[]): { primary: Record<string, Stat>; units: Record<string, string> } {+ const primary: Record<string, Stat> = {}, units: Record<string, string> = {}+ const values = (m: Measurement) => m.dataPoints.map(p => p.value).filter((v): v is number => typeof v === 'number')+ for (const m of measurements) {+ const s = stat(values(m))+ if (s) { primary[m.name] = s; units[m.name] = m.units }+ }+ const user = measurements.find(m => m.name === 'PROCESS_NORMALIZED_CPU_USER'), kernel = measurements.find(m => m.name === 'PROCESS_NORMALIZED_CPU_KERNEL')+ if (user && kernel) {+ const sums = user.dataPoints.map((p, i) => p.value === null || kernel.dataPoints[i]?.value == null ? null : p.value + kernel.dataPoints[i]!.value!)+ const s = stat(sums.filter((v): v is number => v !== null))+ if (s) { primary.PROCESS_CPU = s; units.PROCESS_CPU = 'PERCENT' }+ }+ return { primary, units }+}++/** A logged slow operation without its values: namespace, command, plan, timings and the keys it filtered on. */+function slowOp(line: string, namespace: string): SlowOp | undefined {+ try {+ const entry = JSON.parse(line) as { t?: { $date?: string }; attr?: Record<string, unknown> }+ const attr = entry.attr ?? {}+ const ms = Number(attr.durationMillis)+ if (!Number.isFinite(ms)) return undefined+ const command = (attr.command && typeof attr.command === 'object' ? attr.command : {}) as Record<string, unknown>+ const num = (v: unknown) => typeof v === 'number' ? v : undefined+ return { at: entry.t?.$date ?? '', ns: String(attr.ns ?? namespace), op: Object.keys(command)[0] ?? String(attr.type ?? '?'),+ shape: filterShape('$runCommandRaw', command), plan: String(attr.planSummary ?? '').replace(/\{[^}]*\}/g, m => m.replace(/:\s*[^,}]+/g, '')), ms,+ docsExamined: num(attr.docsExamined), keysExamined: num(attr.keysExamined), returned: num(attr.nreturned) }+ } catch {+ return undefined+ }+}++function summarizeSlow(ops: SlowOp[], unreadable: number): SlowSummary {+ const perMinute = new Map<number, number>(), groups = new Map<string, SlowSummary['top'][number]>()+ for (const op of ops) {+ const minute = Math.floor(Date.parse(op.at) / 60_000)+ perMinute.set(minute, (perMinute.get(minute) ?? 0) + op.ms)+ const key = `${op.ns}\0${op.op}\0${op.shape}`+ const group = groups.get(key) ?? { ns: op.ns, op: op.op, shape: op.shape, count: 0, seconds: 0 }+ group.count++; group.seconds += op.ms / 1000+ groups.set(key, group)+ }+ const seconds = (ms: number) => Math.round(ms) / 1000+ return { count: ops.length, unreadable, totalSeconds: seconds(ops.reduce((a, o) => a + o.ms, 0)),+ peakSecondsPerMinute: seconds(Math.max(0, ...perMinute.values())),+ top: [...groups.values()].sort((a, b) => b.seconds - a.seconds).slice(0, 20).map(g => ({ ...g, seconds: Math.round(g.seconds * 1000) / 1000 })) }+}++async function snapshotAtlas(get: ReturnType<typeof atlasClient>, groupId: string, cluster: string, now: number) {+ const group = `/groups/${encodeURIComponent(groupId)}`+ const { results } = await get<{ results: Process[] }>(`${group}/processes`, [['itemsPerPage', '500']])+ const name = (p: Process) => (p.userAlias || p.hostname).toLowerCase()+ const processes = results.filter(p => name(p).startsWith(`${cluster.toLowerCase()}-`) || name(p) === cluster.toLowerCase())+ if (!processes.length) {+ throw new Error(`No process of cluster ${cluster}. Processes seen: ${[...new Set(results.map(name))].join(', ') || 'none'}.`)+ }+ const measurements: Record<string, Measurement[]> = {}, slow: Record<string, SlowOp[]> = {}+ let unreadable = 0+ for (const p of processes) {+ const path = `${group}/processes/${encodeURIComponent(p.id)}`+ const reply = await get<{ measurements: Measurement[] }>(`${path}/measurements`,+ [['granularity', 'PT5M'], ['period', 'P1D'], ...METRICS.map((m): [string, string] => ['m', m])])+ measurements[p.id] = reply.measurements+ const logs = await get<{ slowQueries: { line: string; namespace: string }[] }>(`${path}/performanceAdvisor/slowQueryLogs`,+ [['since', String(now - DAY_MS)], ['duration', String(DAY_MS)], ['nLogs', '20000']])+ slow[p.id] = []+ for (const q of logs.slowQueries ?? []) {+ const op = slowOp(q.line, q.namespace)+ if (op) slow[p.id]!.push(op)+ else unreadable+++ }+ }+ const primaryProcess = processes.find(p => p.typeName === 'REPLICA_PRIMARY') ?? processes[0]!+ return { processes, measurements, slow, primaryProcess: primaryProcess.id, ...summarizeMeasurements(measurements[primaryProcess.id] ?? []),+ slowOps: summarizeSlow(Object.values(slow).flat(), unreadable) }+}++/* ---------- sizes from a secondary ---------- */++async function snapshotSizes(url: string): Promise<Sizes> {+ const client = new MongoClient(secondaryUrl(url))+ try {+ await client.connect()+ const db = client.db()+ const status = await db.admin().command({ connectionStatus: 1, showPrivileges: true }) as ConnectionStatus+ for (const host of hostsOf(url)) assertReadOnly(status, host)+ const hello = await db.admin().command({ hello: 1 }) as { primary?: string }+ const names = (await db.listCollections({}, { nameOnly: true }).toArray())+ .filter(c => c.type !== 'view' && !c.name.startsWith('system.')).map(c => c.name)+ let readFrom = ''+ const collections: Sizes['collections'] = []+ for (const name of names) {+ const [stats] = await db.collection(name).aggregate([{ $collStats: { storageStats: {} } }], { readPreference: 'secondary' }).toArray() as+ { host: string; storageStats: { count: number; size: number; storageSize: number; totalIndexSize: number; nindexes: number } }[]+ if (!stats) continue+ readFrom ||= stats.host+ const s = stats.storageStats+ collections.push({ name, count: s.count, dataBytes: s.size, storageBytes: s.storageSize, indexBytes: s.totalIndexSize, nindexes: s.nindexes })+ }+ collections.sort((a, b) => b.dataBytes + b.indexBytes - (a.dataBytes + a.indexBytes))+ return { primary: hello.primary ?? '', readFrom, dataBytes: collections.reduce((a, c) => a + c.dataBytes, 0),+ indexBytes: collections.reduce((a, c) => a + c.indexBytes, 0), collections }+ } finally {+ await client.close()+ }+}++/* ---------- the run ---------- */++const fmt = (n: number) => String(Number(n.toFixed(1)))++function markdown(summary: Summary): string {+ const lines = [`# Atlas snapshot: ${summary.label}`, '', `Taken ${summary.takenAt}.`, '']+ if (summary.primary) {+ lines.push(`Primary ${summary.primaryProcess}, last 24 h at 5-minute points.`, '', '| Metric | Average | Peak | Latest |', '|---|---|---|---|')+ for (const [name, label, factor] of ROWS) {+ const s = summary.primary[name]+ if (!s) continue+ const f = label.includes('MB') ? (BYTES[summary.units?.[name] ?? ''] ?? 1) * factor : factor+ lines.push(`| ${label} | ${fmt(s.average * f)} | ${fmt(s.peak * f)} | ${fmt(s.latest * f)} |`)+ }+ lines.push('')+ }+ if (summary.slowOps) {+ const s = summary.slowOps+ lines.push(`Slow operations (Atlas's slow log, last 24 h): ${s.count}, ${fmt(s.totalSeconds)} s in all, ${fmt(s.peakSecondsPerMinute)} s in the worst minute` ++ `${s.unreadable ? `, ${s.unreadable} lines unreadable` : ''}.`, '', '| Namespace | Op | Filter keys | Count | Seconds |', '|---|---|---|---|---|',+ ...s.top.map(t => `| ${t.ns} | ${t.op} | \`${t.shape}\` | ${t.count} | ${fmt(t.seconds)} |`), '')+ }+ if (summary.sizes) {+ const z = summary.sizes, mb = (b: number) => fmt(b / 1e6)+ lines.push(`Sizes, read from ${z.readFrom}: ${z.collections.length} collections, ${mb(z.dataBytes)} MB of data, ${mb(z.indexBytes)} MB of indexes.`, '',+ '| Collection | Documents | Data (MB) | Indexes (MB) | Indexes |', '|---|---|---|---|---|',+ ...z.collections.slice(0, 15).map(c => `| ${c.name} | ${c.count} | ${mb(c.dataBytes)} | ${mb(c.indexBytes)} | ${c.nindexes} |`), '')+ }+ for (const s of summary.skipped) lines.push(`Skipped ${s}`)+ for (const f of summary.failed) lines.push(`Failed ${f}`)+ return `${lines.join('\n')}\n`+}++export async function runSnapshot({ env, out, label, now = Date.now(), print = console.log }:+ { env: NodeJS.ProcessEnv; out: string; label: string; now?: number; print?: (line: string) => void }): Promise<{ ok: boolean; skipped: string[]; failed: string[] }> {+ const summary: Summary = { label, takenAt: new Date(now).toISOString(), skipped: [], failed: [] }+ const files: Record<string, unknown> = {}+ const base = (env.ATLAS_BASE_URL ?? 'https://cloud.mongodb.com').replace(/\/$/, '')+ const auth: Auth | undefined = env.ATLAS_CLIENT_ID && env.ATLAS_CLIENT_SECRET ? { kind: 'service', clientId: env.ATLAS_CLIENT_ID, clientSecret: env.ATLAS_CLIENT_SECRET }+ : env.ATLAS_PUBLIC_KEY && env.ATLAS_PRIVATE_KEY ? { kind: 'digest', publicKey: env.ATLAS_PUBLIC_KEY, privateKey: env.ATLAS_PRIVATE_KEY } : undefined++ if (!auth) summary.skipped.push('atlas: set ATLAS_CLIENT_ID and ATLAS_CLIENT_SECRET, or ATLAS_PUBLIC_KEY and ATLAS_PRIVATE_KEY')+ else if (!env.ATLAS_GROUP_ID || !env.ATLAS_CLUSTER) summary.skipped.push('atlas: set ATLAS_GROUP_ID and ATLAS_CLUSTER')+ else {+ try {+ const atlas = await snapshotAtlas(atlasClient(base, auth), env.ATLAS_GROUP_ID, env.ATLAS_CLUSTER, now)+ Object.assign(summary, { primaryProcess: atlas.primaryProcess, primary: atlas.primary, units: atlas.units, slowOps: atlas.slowOps })+ files['measurements.json'] = { processes: atlas.processes, measurements: atlas.measurements }+ files['slow-queries.json'] = atlas.slow+ } catch (error) {+ summary.failed.push(`atlas: ${redactUrl(error instanceof Error ? error.message : String(error))}`)+ }+ }+ if (!env.MONGO_READONLY_URL) summary.skipped.push('sizes: set MONGO_READONLY_URL to the read-only user')+ else {+ try {+ summary.sizes = await snapshotSizes(env.MONGO_READONLY_URL)+ files['sizes.json'] = summary.sizes+ } catch (error) {+ summary.failed.push(`sizes: ${redactUrl(error instanceof Error ? error.message : String(error))}`)+ }+ }++ await mkdir(out, { recursive: true })+ for (const [name, content] of Object.entries(files)) await writeFile(join(out, name), `${JSON.stringify(content, null, 1)}\n`)+ await writeFile(join(out, 'summary.json'), `${JSON.stringify(summary, null, 1)}\n`)+ await writeFile(join(out, 'summary.md'), markdown(summary))+ print(`Saved to ${out}`)+ for (const s of summary.skipped) print(`Skipped ${s}`)+ for (const f of summary.failed) print(`Failed ${f}`)+ const ran = Boolean(summary.primary || summary.sizes)+ return { ok: ran && !summary.failed.length, skipped: summary.skipped, failed: summary.failed }+}++/** Two snapshots' numbers side by side, with the change. */+export function compareSnapshots(before: Summary, after: Summary): string {+ const rows: [string, number | undefined, number | undefined][] = []+ for (const [name, label, factor] of ROWS) {+ for (const key of ['average', 'peak'] as const) {+ const f = label.includes('MB') ? (BYTES[before.units?.[name] ?? ''] ?? 1) * factor : factor+ const b = before.primary?.[name]?.[key], a = after.primary?.[name]?.[key]+ if (b !== undefined || a !== undefined) rows.push([`${label}, ${key}`, b === undefined ? b : b * f, a === undefined ? a : a * f])+ }+ }+ rows.push(['Slow operations, seconds', before.slowOps?.totalSeconds, after.slowOps?.totalSeconds],+ ['Slow operations, worst minute (s)', before.slowOps?.peakSecondsPerMinute, after.slowOps?.peakSecondsPerMinute],+ ['Data (MB)', before.sizes && before.sizes.dataBytes / 1e6, after.sizes && after.sizes.dataBytes / 1e6],+ ['Indexes (MB)', before.sizes && before.sizes.indexBytes / 1e6, after.sizes && after.sizes.indexBytes / 1e6])+ const change = (b?: number, a?: number) => b === undefined || a === undefined || b === 0 ? '–' : `${a >= b ? '+' : ''}${Math.round((a / b - 1) * 100)}%`+ const cell = (n?: number) => n === undefined ? '–' : fmt(n)+ return [`| Metric | ${before.label} (${before.takenAt}) | ${after.label} (${after.takenAt}) | Change |`, '|---|---|---|---|',+ ...rows.filter(([, b, a]) => b !== undefined || a !== undefined).map(([label, b, a]) => `| ${label} | ${cell(b)} | ${cell(a)} | ${change(b, a)} |`)].join('\n')+}++async function main(): Promise<void> {+ const args = process.argv.slice(2)+ const option = (name: string) => { const at = args.indexOf(`--${name}`); return at >= 0 ? args[at + 1] : undefined }+ const compare = args.indexOf('--compare')+ if (compare >= 0) {+ const [before, after] = [args[compare + 1], args[compare + 2]]+ if (!before || !after) throw new Error('Usage: --compare BEFORE_DIR AFTER_DIR')+ const read = async (dir: string) => JSON.parse(await readFile(join(dir, 'summary.json'), 'utf8')) as Summary+ console.log(compareSnapshots(await read(before), await read(after)))+ return+ }+ const label = option('label') ?? 'snapshot'+ const out = option('out') ?? join('atlas-snapshots', `${label}-${new Date().toISOString().replace(/[:.]/g, '-')}`)+ const result = await runSnapshot({ env: process.env, out, label })+ if (!result.ok) process.exitCode = 1+}++if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {+ main().catch(error => {+ console.error(redactUrl(error instanceof Error ? error.message : String(error)))+ process.exitCode = 1+ })+}diff --git a/backend/src/lib/prisma.ts b/backend/src/lib/prisma.tsindex 875a290e1..51416d500 100644--- a/backend/src/lib/prisma.ts+++ b/backend/src/lib/prisma.ts@@ -1,13 +1,15 @@import { PrismaClient, type Prisma } from '@prisma/client'import { env } from '../config/env.js'import { POOL_DEFAULTS, withPoolDefaults } from './databaseUrl.js'+import { withQueryStats } from './queryStats.js'// The Prisma CLI (db push) reads env("DATABASE_URL"); keep it in sync for any manual run.process.env.DATABASE_URL ??= env.DATABASE_URL-export const prisma = new PrismaClient({+// Every query is timed for the per-minute `db by shape` log (lib/queryStats.ts, DB roadmap Phase 1).+export const prisma = withQueryStats(new PrismaClient({datasources: { db: { url: withPoolDefaults(env.DATABASE_URL, POOL_DEFAULTS) } },-})+}))/** "Not soft-deleted" filter for Machine findMany where-clauses. Mongo-Prisma gotcha: legacy* rows have NO `deletedAt` field and `{deletedAt: null}` matches only an explicit null, so thediff --git a/backend/src/lib/queryStats.test.ts b/backend/src/lib/queryStats.test.tsnew file mode 100644index 000000000..ad5d350a1--- /dev/null+++ b/backend/src/lib/queryStats.test.ts@@ -0,0 +1,237 @@+import Fastify from 'fastify'+import { afterEach, describe, expect, it } from 'vitest'+import { createQueryStats, enterWork, estimateBytes, filterShape, registerWorkContext, runWork, workKind, type QueryStatsOptions } from './queryStats.js'++type Logged = { message: string; context: Record<string, unknown> }++function stats(options: Partial<QueryStatsOptions> = {}) {+ const infos: Logged[] = [], warns: Logged[] = []+ const s = createQueryStats({ pod: 'pod-1', log: (message, context) => infos.push({ message, context }),+ warn: (message, context) => warns.push({ message, context }), ...options })+ return { s, infos, warns }+}++type Row = { op: string; shape: string; route: string; n: number; ms: number; docs: number; bytes: number; errors: number; maxMs: number }+const rows = (logged: Logged) => logged.context.top as Row[]++describe('filterShape', () => {+ it('keeps the keys of a Prisma filter and replaces every value with ?', () => {+ const shape = filterShape('findMany', { where: { tabId: 'tab-secret-1', OR: [{ status: { in: ['open', 'held'] } }, { owner: { email: '[email protected]' } }] },+ select: { id: true }, take: 5 })+ expect(shape).toBe('{"OR":[{"status":{"in":"?"}},{"owner":{"email":"?"}}],"tabId":"?"}')+ expect(shape).not.toContain('tab-secret-1')+ expect(shape).not.toContain('alice')+ })++ it('never shows a value, even an object under a value operator or a string that looks like a field path', () => {+ const shape = filterShape('findFirst', { where: { meta: { equals: { private: 'note' } }, label: { not: '$secret' }, at: { gt: new Date(0) } } })+ expect(shape).toBe('{"at":{"gt":"?"},"label":{"not":"?"},"meta":{"equals":"?"}}')+ })++ it('hides keys that carry ids, emails or anything else that is not a plain name', () => {+ const shape = filterShape('$runCommandRaw', { update: 'SwarmGroup', updates: [{ q: { 'parts.a5e7c91b0462f5fa1a4a7f1b': 1, '[email protected]': 2, 'state.ok': 3, 'agent 7': 4 } }] })+ expect(shape).toBe('{"*":"?","parts.*":"?","state.ok":"?"}')+ })++ it('names the stages of a raw pipeline and the keys of its $match', () => {+ expect(filterShape('aggregateRaw', { pipeline: [{ $match: { tabId: 't1', archived: false } }, { $sort: { at: -1 } }, { $limit: 5 }] }))+ .toBe('[{"$match":{"archived":"?","tabId":"?"}},"$sort","$limit"]')+ expect(filterShape('findRaw', { filter: { machineIds: 'm1' } })).toBe('{"machineIds":"?"}')+ expect(filterShape('$runCommandRaw', { find: 'users', filter: { email: '[email protected]' } })).toBe('{"email":"?"}')+ expect(filterShape('$runCommandRaw', { aggregate: 'SwarmGroup', pipeline: [{ $match: { tabId: 'x' } }], cursor: {} })).toBe('[{"$match":{"tabId":"?"}}]')+ expect(filterShape('$runCommandRaw', { ping: 1 })).toBe('')+ })++ it('has an empty shape for writes without a filter', () => {+ expect(filterShape('create', { data: { email: '[email protected]' } })).toBe('')+ expect(filterShape('findMany', undefined)).toBe('')+ })++ it('stays bounded for deep or wide filters', () => {+ let deep: Record<string, unknown> = { leaf: 1 }+ for (let i = 0; i < 20; i++) deep = { AND: deep }+ expect(filterShape('findMany', { where: deep })).toContain('…')+ const wide = Object.fromEntries(Array.from({ length: 200 }, (_, i) => [`field${String.fromCharCode(97 + (i % 26))}${'x'.repeat(i % 7)}`, i]))+ expect(filterShape('findMany', { where: wide }).length).toBeLessThanOrEqual(301)+ })+})++describe('per-minute totals', () => {+ it('records count, ms, documents and bytes per model.action, shape and route, then starts a new window', () => {+ const { s, infos } = stats({ sampleEvery: 1 })+ runWork('http GET /api/users/:id', () => {+ s.record('User', 'findMany', { where: { email: '[email protected]' } }, 3, [{ id: '1', email: '[email protected]' }])+ s.record('User', 'findMany', { where: { email: '[email protected]' } }, 5, [{ id: '2', email: '[email protected]' }, { id: '3', email: '[email protected]' }])+ })+ s.record('User', 'findMany', { where: { email: '[email protected]' } }, 7, [])+ s.flush()+ expect(infos).toHaveLength(1)+ expect(infos[0]!.message).toBe('db by shape')+ const all = JSON.stringify(infos[0]!.context)+ expect(all).not.toContain('[email protected]')+ const byRoute = Object.fromEntries(rows(infos[0]!).map(r => [r.route, r]))+ expect(byRoute['http GET /api/users/:id']).toEqual({ op: 'User.findMany', shape: '{"email":"?"}', route: 'http GET /api/users/:id', n: 2, ms: 8, docs: 3,+ bytes: JSON.stringify([{ id: '1', email: '[email protected]' }]).length + JSON.stringify([{ id: '2', email: '[email protected]' }, { id: '3', email: '[email protected]' }]).length, errors: 0, maxMs: 5 })+ expect(byRoute.background).toMatchObject({ n: 1, ms: 7, docs: 0, bytes: 2 })+ expect(infos[0]!.context).toMatchObject({ pod: 'pod-1', queries: 3, ms: 15, docs: 3, keys: 2, overflowQueries: 0, slowSuppressed: 0 })+ s.flush()+ expect(infos[1]!.context).toMatchObject({ queries: 0, keys: 0, top: [] })+ })++ it('measures the bytes of every Nth result per key and scales them to the count', () => {+ const { s, infos } = stats({ sampleEvery: 4 })+ const big = [{ blob: 'x'.repeat(100) }], small = [{ blob: '' }]+ // Results 1 and 5 are measured (two bigs), the rest are not even serialized: 2 × big over 2 samples, times 8 queries.+ const results = [big, small, small, small, big, small, small, small]+ for (const r of results) s.record('SwarmGroup', 'findMany', { where: { tabId: 't' } }, 1, r)+ s.flush()+ expect(rows(infos[0]!)[0]!.bytes).toBe(JSON.stringify(big).length * 8)+ })++ it('counts a failed query as an error with its time and no bytes', () => {+ const { s, infos } = stats({ sampleEvery: 1 })+ s.record('Machine', 'update', { where: { machineId: 'm' } }, 4, undefined, true)+ s.flush()+ expect(rows(infos[0]!)[0]).toMatchObject({ op: 'Machine.update', n: 1, ms: 4, errors: 1, bytes: 0, docs: 0 })+ })++ it('counts a single-document result as one document and a raw cursor reply by its batch', () => {+ const { s, infos } = stats({ sampleEvery: 1 })+ s.record('User', 'findUnique', { where: { id: '1' } }, 1, { id: '1' })+ s.record('User', 'findUnique', { where: { id: '2' } }, 1, null)+ s.record(undefined, '$runCommandRaw', { aggregate: 'SwarmGroup', pipeline: [] }, 1, { cursor: { firstBatch: [{}, {}, {}] }, ok: 1 })+ s.flush()+ const byOp = Object.fromEntries(rows(infos[0]!).map(r => [r.op, r]))+ expect(byOp['User.findUnique']!.docs).toBe(1)+ expect(byOp['SwarmGroup.$runCommandRaw aggregate']!.docs).toBe(3)+ })++ it('keeps a bounded number of keys per window and counts the rest under other', () => {+ const { s, infos } = stats({ maxKeys: 3 })+ for (const model of ['A', 'B', 'C', 'D', 'E']) s.record(model, 'findMany', { where: { id: 'x' } }, 1, [])+ s.flush()+ expect(infos[0]!.context).toMatchObject({ queries: 5, keys: 3, overflowQueries: 3 })+ expect(rows(infos[0]!).map(r => r.op).sort()).toEqual(['A.findMany', 'B.findMany', 'other'])+ })++ it('logs the keys a window ranks highest by bytes, by count and by time', () => {+ const { s, infos } = stats({ sampleEvery: 1, top: { bytes: 1, count: 1, ms: 1 } })+ s.record('Big', 'findMany', {}, 1, [{ x: 'x'.repeat(500) }])+ s.record('Often', 'count', {}, 1, 1); s.record('Often', 'count', {}, 1, 1); s.record('Often', 'count', {}, 1, 1)+ s.record('Slow', 'findFirst', {}, 150, null)+ s.record('Quiet', 'findFirst', {}, 1, null)+ s.flush()+ // Ranked by bytes: Big (500+), Slow ("null", 4), Often ("1" three times, 3); Quiet makes no list.+ expect(rows(infos[0]!).map(r => r.op)).toEqual(['Big.findMany', 'Slow.findFirst', 'Often.count'])+ })+})++describe('slow queries', () => {+ it('warns about a query at or over the threshold with its shape and route, never its values', () => {+ const { s, warns } = stats({ slowMs: 200 })+ runWork('web-ws swarm_changes', () => s.record('SwarmGroup', 'findMany', { where: { tabId: 'tab-secret', title: { contains: 'payroll' } } }, 250, [{ title: 'payroll 2026' }]))+ s.record('SwarmGroup', 'findMany', { where: { tabId: 'quick' } }, 199, [])+ expect(warns).toHaveLength(1)+ expect(warns[0]).toEqual({ message: 'slow query', context: { pod: 'pod-1', op: 'SwarmGroup.findMany', shape: '{"tabId":"?","title":{"contains":"?"}}',+ route: 'web-ws swarm_changes', ms: 250, docs: 1, bytes: JSON.stringify([{ title: 'payroll 2026' }]).length, error: false } })+ expect(JSON.stringify(warns)).not.toMatch(/tab-secret|payroll/)+ })++ it('warns at most slowPerWindow times a window and reports how many it held back', () => {+ const { s, warns, infos } = stats({ slowMs: 10, slowPerWindow: 2 })+ for (let i = 0; i < 5; i++) s.record('A', 'findMany', {}, 20, [])+ s.record('A', 'findMany', {}, 9, [])+ s.flush()+ expect(warns).toHaveLength(2)+ // Every slow query's time counts, logged or held back: what an alert on slow seconds a minute sums across pods.+ expect(infos[0]!.context).toMatchObject({ slowSuppressed: 3, slowQueries: 5, slowMs: 100 })+ s.record('A', 'findMany', {}, 20, [])+ expect(warns).toHaveLength(3)+ })+})++describe('work context', () => {+ afterEach(() => enterWork(undefined))++ it('follows awaited work, and is background outside any', async () => {+ expect(workKind()).toBe('background')+ const seen = await runWork('http POST /api/x', async () => {+ await new Promise(resolve => setTimeout(resolve, 1))+ return workKind()+ })+ expect(seen).toBe('http POST /api/x')+ expect(workKind()).toBe('background')+ })++ it('can name the work running now and what it schedules', async () => {+ await new Promise<void>(resolve => setImmediate(() => {+ enterWork('manager-ws up')+ void Promise.resolve().then(() => { expect(workKind()).toBe('manager-ws up'); resolve() })+ }))+ })+})++describe('HTTP work context', () => {+ it('names a request by its route pattern in later hooks and in the handler, a JSON body included', async () => {+ const app = Fastify()+ registerWorkContext(app)+ const seen: string[] = []+ // Like the rate limit and sign-in: hooks added after it, which read the database too.+ app.addHook('onRequest', async () => { await new Promise(resolve => setTimeout(resolve, 1)); seen.push(`hook ${workKind()}`) })+ app.get('/api/items/:id', async () => { await new Promise(resolve => setImmediate(resolve)); seen.push(workKind()); return {} })+ app.post('/api/items', async request => { await Promise.resolve(); seen.push(`${workKind()} ${(request.body as { n: number }).n}`); return {} })+ await app.inject({ method: 'GET', url: '/api/items/alice-1' })+ // A body big enough to arrive in more than one chunk.+ await app.inject({ method: 'POST', url: '/api/items', payload: { n: 2, pad: 'x'.repeat(256 * 1024) } })+ expect(seen).toEqual(['hook http GET /api/items/:id', 'http GET /api/items/:id', 'hook http POST /api/items', 'http POST /api/items 2'])+ // A real socket, where the body's chunks arrive on the connection's own callbacks after the hooks ran.+ seen.length = 0+ const url = await app.listen({ port: 0, host: '127.0.0.1' })+ const sent = await fetch(`${url}/api/items`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ n: 3, pad: 'x'.repeat(256 * 1024) }) })+ expect(sent.status).toBe(200)+ expect(seen).toEqual(['hook http POST /api/items', 'http POST /api/items 3'])+ expect(workKind()).toBe('background')+ await app.close()+ })+})++describe('estimateBytes', () => {+ it('is the JSON length of an ordinary result', () => {+ const result = [{ id: 'a', n: 1.5, ok: true, no: false, at: new Date(0), none: null, skipped: undefined, tags: ['x', 'y'], nested: { deep: { v: -3 } } }, null]+ expect(estimateBytes(result)).toEqual({ bytes: JSON.stringify(result).length, capped: false })+ expect(estimateBytes(null)).toEqual({ bytes: 4, capped: false })+ expect(estimateBytes(undefined)).toEqual({ bytes: 0, capped: false })+ })++ it('counts a big page up to its budget only, and scales up from the documents it counted', () => {+ const doc = (i: number) => ({ id: `doc-${String(i).padStart(5, '0')}`, body: 'x'.repeat(1000) })+ const page = Array.from({ length: 10_000 }, (_, i) => doc(i))+ const real = JSON.stringify(page).length+ // Past the first 1,000 documents (~1 MB), reading a document throws: the estimate must stop before them.+ let touched = 0+ for (let i = 1000; i < page.length; i++) Object.defineProperty(page, i, { get: () => { touched++; throw new Error('read past the budget') } })+ const estimate = estimateBytes(page, 256 * 1024)+ expect(touched).toBe(0)+ expect(estimate.capped).toBe(true)+ expect(Math.abs(estimate.bytes - real) / real).toBeLessThan(0.01)+ })++ it('stops inside one huge document and gives at least the budget', () => {+ const huge: Record<string, unknown> = {}+ for (let i = 0; i < 5_000; i++) huge[`k${i}`] = 'x'.repeat(1000)+ let touched = 0+ for (let i = 1000; i < 5_000; i++) Object.defineProperty(huge, `k${i}`, { enumerable: true, get: () => { touched++; return 'x'.repeat(1000) } })+ const estimate = estimateBytes(huge, 256 * 1024)+ expect(touched).toBe(0)+ expect(estimate).toMatchObject({ capped: true })+ expect(estimate.bytes).toBeGreaterThanOrEqual(256 * 1024)+ })++ it('reports how many results a window estimated past the budget', () => {+ const { s, infos } = stats({ sampleEvery: 1, byteBudget: 1024 })+ s.record('SwarmGroup', 'findMany', {}, 1, Array.from({ length: 100 }, () => ({ body: 'x'.repeat(100) })))+ s.record('SwarmGroup', 'findMany', {}, 1, [])+ s.flush()+ expect(infos[0]!.context).toMatchObject({ bytesCapped: 1 })+ })+})diff --git a/backend/src/lib/queryStats.ts b/backend/src/lib/queryStats.tsnew file mode 100644index 000000000..381392c12--- /dev/null+++ b/backend/src/lib/queryStats.ts@@ -0,0 +1,335 @@+import { AsyncLocalStorage } from 'node:async_hooks'+import { hostname } from 'node:os'+import { performance } from 'node:perf_hooks'+import type { PrismaClient } from '@prisma/client'+import type { FastifyInstance, FastifyRequest } from 'fastify'+import { logger } from '../utils/logger.js'++/**+ * Which queries this process sends, per kind of work (DB roadmap Phase 1). Atlas logs only operations over 100 ms; the+ * load is in the ~900 fast ones a second. Every minute, `db by shape` logs per model.action, filter shape and route: count,+ * total ms, documents and result bytes (sampled), with the window's top keys, and the count and total time of queries at+ * or over 200 ms (Atlas has no alert on slow operations; a log monitor sums `slowMs`). Each such query also logs+ * `slow query`, at most 20 a minute. Neither log carries a value: a shape keeps a filter's keys and replaces every value+ * with `?`, and a key that is not a plain name (an id, an email) becomes `*`. Routes are patterns, never URLs.+ */++const work = new AsyncLocalStorage<string>()++/** The kind of work running now: an HTTP route pattern or WebSocket frame kind, or `background` for timers and startup. */+export function workKind(): string {+ return work.getStore() ?? 'background'+}++/** Runs fn, and everything it schedules, as `kind`. */+export function runWork<T>(kind: string, fn: () => T): T {+ return work.run(kind, fn)+}++/** Names the work running now and what it goes on to schedule, for code that has no callback to wrap (a frame handler).+ * undefined clears it. */+export function enterWork(kind: string | undefined): void {+ work.enterWith(kind as string)+}++const httpKind = (request: FastifyRequest) => `http ${request.method} ${request.routeOptions.url ?? 'unrouted'}`++/** Names every request by its route pattern, for the hooks and handler that follow. Register it before any hook that+ * reads the database (rate limit, sign-in). */+export function registerWorkContext(app: FastifyInstance): void {+ app.addHook('onRequest', (request, _reply, done) => runWork(httpKind(request), done))+}++/* ---------- filter shapes ---------- */++const MAX_DEPTH = 6+const MAX_ITEMS = 5+const MAX_SHAPE = 300+/** Operators whose argument is a value, even when it is an object (`equals` on a Json field, `$literal`). */+const VALUE_OPS = new Set(['equals', 'in', 'notIn', 'has', 'hasSome', 'hasEvery', 'set', 'push', 'path',+ '$eq', '$ne', '$in', '$nin', '$all', '$literal', '$gt', '$gte', '$lt', '$lte'])+const NAME = /^[$A-Za-z_][A-Za-z0-9_$]{0,39}$/+const ID_LIKE = /[0-9a-f]{12,}|\d{5,}/i++const KEY_CHARS = /^[A-Za-z0-9_$.]{1,120}$/++/** A key as a log may show it: `*` for any key with other characters (an email, a space), else each dotted segment that is+ * a plain name, an id-like one as `*` (`parts.*`). */+function safeKey(key: string): string {+ if (!KEY_CHARS.test(key)) return '*'+ return key.split('.').map(segment => NAME.test(segment) && !ID_LIKE.test(segment) ? segment : '*').join('.')+}++const isPlainObject = (value: unknown): value is Record<string, unknown> => {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false+ const proto = Object.getPrototypeOf(value)+ return proto === Object.prototype || proto === null+}++function shapeOf(value: unknown, depth: number): unknown {+ if (Array.isArray(value)) {+ if (!value.some(item => isPlainObject(item) || Array.isArray(item))) return '?'+ if (depth >= MAX_DEPTH) return '…'+ const items = value.slice(0, MAX_ITEMS).map(item => shapeOf(item, depth + 1))+ return value.length > MAX_ITEMS ? [...items, '…'] : items+ }+ if (!isPlainObject(value)) return '?'+ if (depth >= MAX_DEPTH) return '…'+ const shaped: Record<string, unknown> = {}+ for (const key of Object.keys(value).sort()) {+ const safe = safeKey(key)+ if (safe in shaped) continue+ shaped[safe] = VALUE_OPS.has(key) ? '?' : shapeOf(value[key], depth + 1)+ }+ return shaped+}++/** A pipeline as its stage names, with the keys of each `$match`. */+function pipelineShape(pipeline: unknown[]): unknown {+ return pipeline.slice(0, 10).map(stage => {+ if (!isPlainObject(stage)) return '?'+ const name = Object.keys(stage)[0] ?? '?'+ return name === '$match' ? { $match: shapeOf(stage.$match, 1) } : safeKey(name)+ })+}++/** What a query filtered on, keys only, as a short string: equal for queries that differ only in their values. */+export function filterShape(action: string, args: unknown): string {+ if (!isPlainObject(args)) return ''+ let shape: unknown+ if (action === '$runCommandRaw') {+ if (Array.isArray(args.pipeline)) shape = pipelineShape(args.pipeline)+ else if ('filter' in args) shape = shapeOf(args.filter, 0)+ else if ('query' in args) shape = shapeOf(args.query, 0)+ else {+ const first = Array.isArray(args.updates) ? args.updates[0] : Array.isArray(args.deletes) ? args.deletes[0] : undefined+ if (isPlainObject(first)) shape = shapeOf(first.q, 0)+ }+ } else if (action === 'aggregateRaw' && Array.isArray(args.pipeline)) shape = pipelineShape(args.pipeline)+ else if (action === 'findRaw') shape = shapeOf(args.filter, 0)+ else if ('where' in args) shape = shapeOf(args.where, 0)+ if (shape === undefined) return ''+ const text = JSON.stringify(shape)+ return text.length > MAX_SHAPE ? `${text.slice(0, MAX_SHAPE)}…` : text+}++/** `Model.action`; a raw command by its collection and command name (`SwarmGroup.$runCommandRaw aggregate`). */+function opName(model: string | undefined, action: string, args: unknown): string {+ if (model) return `${model}.${action}`+ if (action === '$runCommandRaw' && isPlainObject(args)) {+ const command = Object.keys(args)[0] ?? '?'+ const collection = typeof args[command] === 'string' ? safeKey(args[command] as string) : '-'+ return `${collection}.$runCommandRaw ${safeKey(command)}`+ }+ return action+}++/** Documents a result holds: a list's length, one for a document, a raw cursor reply's first batch. */+function docsOf(result: unknown): number {+ if (Array.isArray(result)) return result.length+ if (isPlainObject(result)) {+ const cursor = result.cursor+ if (isPlainObject(cursor) && Array.isArray(cursor.firstBatch)) return cursor.firstBatch.length+ return 1+ }+ return 0+}++/** How much of a result one measurement reads at most. */+const BYTE_BUDGET = 256 * 1024++/**+ * A result's size as JSON characters, close to what it cost to send and unpack, without serializing it: the exact JSON+ * length for ordinary results (strings count without escapes). It reads at most `budget` characters' worth: a list+ * past it is scaled up from the documents counted so far, and one document past it gives the budget (`capped`), so a+ * multi-MB page never stalls the process.+ */+export function estimateBytes(result: unknown, budget = BYTE_BUDGET): { bytes: number; capped: boolean } {+ let used = 0, over = false+ const add = (n: number) => { used += n; if (used > budget) over = true }+ const walk = (value: unknown, inList: boolean): void => {+ if (over) return+ if (value === null) return add(4)+ switch (typeof value) {+ case 'string': return add(value.length + 2)+ case 'number': return add(Number.isFinite(value) ? String(value).length : 4)+ case 'boolean': return add(value ? 4 : 5)+ case 'bigint': return add(String(value).length)+ case 'object': break+ default: return inList ? add(4) : undefined+ }+ if (ArrayBuffer.isView(value)) return add(value.byteLength * 4)+ const toJSON = (value as { toJSON?: unknown }).toJSON+ if (typeof toJSON === 'function') return walk(toJSON.call(value), inList)+ if (Array.isArray(value)) {+ add(2 + Math.max(0, value.length - 1))+ for (let i = 0; i < value.length && !over; i++) walk(value[i], true)+ return+ }+ add(2)+ let first = true+ for (const key of Object.keys(value)) {+ const item = (value as Record<string, unknown>)[key]+ if (item === undefined || typeof item === 'function' || typeof item === 'symbol') continue+ add(key.length + 3 + (first ? 0 : 1))+ first = false+ walk(item, false)+ if (over) return+ }+ }+ if (!Array.isArray(result) || !result.length) {+ walk(result, false)+ return { bytes: used, capped: over }+ }+ const brackets = 2 + result.length - 1+ add(brackets)+ let counted = 0, countedBytes = 0+ for (; counted < result.length; counted++) {+ walk(result[counted], true)+ if (over) break+ countedBytes = used - brackets+ }+ if (!over) return { bytes: used, capped: false }+ return { bytes: counted ? Math.round(brackets + countedBytes / counted * result.length) : used, capped: true }+}++/* ---------- per-minute totals ---------- */++type Entry = { op: string; shape: string; route: string; n: number; ms: number; docs: number; errors: number; maxMs: number+ sampled: number; sampledBytes: number }++export type QueryStatsOptions = {+ /** This pod and process, on every line. */+ pod?: string+ /** Logs a query at or over this as `slow query`. */+ slowMs?: number+ slowPerWindow?: number+ /** Keys one window keeps, the overflow key included; queries past it count under `other`. */+ maxKeys?: number+ /** Measures every Nth result of a key to count its bytes, and scales up. */+ sampleEvery?: number+ /** Characters one measurement reads at most (estimateBytes). */+ byteBudget?: number+ /** How many keys of each ranking a window's line lists. */+ top?: { bytes: number; count: number; ms: number }+ log?: (message: string, context: Record<string, unknown>) => void+ warn?: (message: string, context: Record<string, unknown>) => void+}++export type QueryStats = {+ record(model: string | undefined, action: string, args: unknown, ms: number, result: unknown, failed?: boolean): void+ /** Logs the window so far and starts a new one. */+ flush(): void+}++const OTHER = 'other'++export function createQueryStats({ pod = `${hostname()}:${process.pid}`, slowMs = 200, slowPerWindow = 20, maxKeys = 1000, sampleEvery = 8, byteBudget = BYTE_BUDGET,+ top = { bytes: 20, count: 10, ms: 10 }, log = (m, c) => logger.info(m, c), warn = (m, c) => logger.warn(m, c) }: QueryStatsOptions = {}): QueryStats {+ let entries = new Map<string, Entry>()+ let overflowQueries = 0, slowLogged = 0, slowSuppressed = 0, slowQueries = 0, slowTotalMs = 0, bytesCapped = 0, started = performance.now()++ const record: QueryStats['record'] = (model, action, args, ms, result, failed = false) => {+ const op = opName(model, action, args), shape = filterShape(action, args), route = workKind()+ let key = `${op}\0${shape}\0${route}`+ let entry = entries.get(key)+ if (!entry) {+ if (entries.size >= maxKeys - 1) {+ overflowQueries+++ key = OTHER+ entry = entries.get(OTHER)+ }+ if (!entry) {+ entry = key === OTHER ? { op: OTHER, shape: '', route: '', n: 0, ms: 0, docs: 0, errors: 0, maxMs: 0, sampled: 0, sampledBytes: 0 }+ : { op, shape, route, n: 0, ms: 0, docs: 0, errors: 0, maxMs: 0, sampled: 0, sampledBytes: 0 }+ entries.set(key, entry)+ }+ }+ entry.n+++ entry.ms += ms+ if (ms > entry.maxMs) entry.maxMs = ms+ const docs = failed ? 0 : docsOf(result)+ entry.docs += docs+ if (failed) entry.errors+++ const slow = ms >= slowMs+ let bytes: number | undefined+ if (!failed && (slow || (entry.n - 1) % sampleEvery === 0)) {+ const estimate = estimateBytes(result, byteBudget)+ bytes = estimate.bytes+ if (estimate.capped) bytesCapped+++ entry.sampled+++ entry.sampledBytes += bytes+ }+ if (!slow) return+ slowQueries+++ slowTotalMs += ms+ if (slowLogged >= slowPerWindow) { slowSuppressed++; return }+ slowLogged+++ warn('slow query', { pod, op, shape, route, ms: Math.round(ms), docs, bytes: bytes ?? 0, error: failed })+ }++ const flush = () => {+ const rows = [...entries.values()].map(e => ({ op: e.op, shape: e.shape, route: e.route, n: e.n, ms: Math.round(e.ms), docs: e.docs,+ bytes: e.sampled ? Math.round(e.sampledBytes * e.n / e.sampled) : 0, errors: e.errors, maxMs: Math.round(e.maxMs) }))+ const ranked = (by: (r: typeof rows[number]) => number, n: number) => [...rows].sort((a, b) => by(b) - by(a)).slice(0, n)+ const picked = new Set([...ranked(r => r.bytes, top.bytes), ...ranked(r => r.n, top.count), ...ranked(r => r.ms, top.ms)])+ const sum = (by: (r: typeof rows[number]) => number) => rows.reduce((total, r) => total + by(r), 0)+ log('db by shape', { pod, windowMs: Math.round(performance.now() - started), queries: sum(r => r.n), ms: sum(r => r.ms), docs: sum(r => r.docs),+ bytes: sum(r => r.bytes), errors: sum(r => r.errors), keys: rows.length, overflowQueries, bytesCapped, slowQueries, slowMs: Math.round(slowTotalMs), slowSuppressed,+ top: [...picked].sort((a, b) => b.bytes - a.bytes || b.n - a.n) })+ entries = new Map(); overflowQueries = 0; slowLogged = 0; slowSuppressed = 0; slowQueries = 0; slowTotalMs = 0; bytesCapped = 0; started = performance.now()+ }++ return { record, flush }+}++/* ---------- the process's own stats, fed by the Prisma hook ---------- */++let active: QueryStats | undefined++/** Starts this process's per-minute log. Returns a stop that logs the last partial window. Until started, the hook only+ * times queries. */+export function startQueryStats(options: QueryStatsOptions & { reportMs?: number } = {}): () => void {+ const stats = createQueryStats(options)+ active = stats+ const timer = setInterval(() => stats.flush(), options.reportMs ?? 60_000)+ timer.unref()+ return () => {+ clearInterval(timer)+ if (active === stats) active = undefined+ stats.flush()+ }+}++/** The client with one query hook that times every operation, model calls and raw commands alike, for `db by shape`.+ * Query extensions keep the client's types, so it is still a PrismaClient to its callers. A failure of the stats never+ * reaches the query: it is warned about once per client, and the query's own result or error goes back unchanged. */+export function withQueryStats(client: PrismaClient, stats: () => QueryStats | undefined = () => active,+ warn: (message: string, context: Record<string, unknown>) => void = (m, c) => logger.warn(m, c)): PrismaClient {+ let warned = false+ const note = (model: string | undefined, operation: string, args: unknown, ms: number, result: unknown, failed: boolean) => {+ try {+ stats()?.record(model, operation, args, ms, result, failed)+ } catch (error) {+ if (warned) return+ warned = true+ warn('query stats failed', { error: error instanceof Error ? error.message : String(error) })+ }+ }+ return client.$extends({+ query: {+ async $allOperations({ model, operation, args, query }) {+ const started = performance.now()+ let result: unknown+ try {+ result = await query(args)+ } catch (error) {+ note(model, operation, args, performance.now() - started, undefined, true)+ throw error+ }+ note(model, operation, args, performance.now() - started, result, false)+ return result+ },+ },+ }) as unknown as PrismaClient+}diff --git a/backend/src/lib/routeLatency.test.ts b/backend/src/lib/routeLatency.test.tsnew file mode 100644index 000000000..380ad535c--- /dev/null+++ b/backend/src/lib/routeLatency.test.ts@@ -0,0 +1,64 @@+import Fastify from 'fastify'+import { expect, it } from 'vitest'+import { createRouteLatency, registerRouteLatency } from './routeLatency.js'++type Logged = { message: string; context: Record<string, unknown> }+type Route = { n: number; p50: number; p95: number; max: number }++function latency(options: Parameters<typeof createRouteLatency>[0] = {}) {+ const logs: Logged[] = []+ const l = createRouteLatency({ pod: 'pod-1', log: (message, context) => logs.push({ message, context }), ...options })+ return { l, logs, routes: (i = 0) => logs[i]!.context.routes as Record<string, Route> }+}++it('logs each route p50 and p95 for the window, then starts a new one', () => {+ const { l, logs, routes } = latency()+ for (let ms = 1; ms <= 100; ms++) l.record('GET /api/items/:id', ms)+ l.record('POST /api/items', 7)+ l.flush()+ expect(logs[0]!.message).toBe('route latency')+ expect(logs[0]!.context).toMatchObject({ pod: 'pod-1', requests: 101 })+ expect(routes()).toEqual({ 'GET /api/items/:id': { n: 100, p50: 50, p95: 95, max: 100 }, 'POST /api/items': { n: 1, p50: 7, p95: 7, max: 7 } })+ l.flush()+ expect(logs[1]!.context).toMatchObject({ requests: 0, routes: {} })+})++it('keeps a bounded sample per route but counts every request', () => {+ const { l, routes } = latency({ maxSamples: 10, random: () => 0.99 })+ for (let i = 0; i < 1000; i++) l.record('GET /api/x', i < 10 ? 3 : 900)+ l.flush()+ // A random draw of 0.99 never replaces one of the first 10 samples: the percentiles come from them, the max from all.+ expect(routes()['GET /api/x']).toEqual({ n: 1000, p50: 3, p95: 3, max: 900 })+})++it('keeps a bounded number of routes and counts the rest under other', () => {+ const { l, routes } = latency({ maxRoutes: 2 })+ for (const route of ['GET /a', 'GET /b', 'GET /c', 'GET /d']) l.record(route, 1)+ l.flush()+ expect(routes()).toEqual({ 'GET /a': { n: 1, p50: 1, p95: 1, max: 1 }, other: { n: 3, p50: 1, p95: 1, max: 1 } })+})++it('lists the routes that took the most time first, up to top', () => {+ const { l, routes } = latency({ top: 2 })+ l.record('GET /rare-slow', 500)+ for (let i = 0; i < 100; i++) l.record('GET /often-fast', 10)+ l.record('GET /rare-fast', 1)+ l.flush()+ expect(Object.keys(routes())).toEqual(['GET /often-fast', 'GET /rare-slow'])+})++it('names each request by its route pattern, never its URL', async () => {+ const app = Fastify()+ const logs: Logged[] = []+ const l = registerRouteLatency(app, { pod: 'pod-1', log: (message, context) => logs.push({ message, context }) })+ app.get('/api/items/:id', async () => ({ ok: true }))+ for (const id of ['alice-secret-1', 'bob-2']) await app.inject({ method: 'GET', url: `/api/items/${id}?token=hunter2` })+ await app.inject({ method: 'GET', url: '/nowhere' })+ l.flush()+ const routes = logs[0]!.context.routes as Record<string, Route>+ expect(Object.keys(routes).sort()).toEqual(['GET /api/items/:id', 'GET unrouted'])+ expect(routes['GET /api/items/:id']!.n).toBe(2)+ expect(routes['GET /api/items/:id']!.p95).toBeGreaterThanOrEqual(0)+ expect(JSON.stringify(logs)).not.toMatch(/alice|bob|hunter2|nowhere/)+ await app.close()+})diff --git a/backend/src/lib/routeLatency.ts b/backend/src/lib/routeLatency.tsnew file mode 100644index 000000000..5445d1a68--- /dev/null+++ b/backend/src/lib/routeLatency.ts@@ -0,0 +1,84 @@+import { hostname } from 'node:os'+import { performance } from 'node:perf_hooks'+import type { FastifyInstance } from 'fastify'+import { logger } from '../utils/logger.js'++/**+ * Per-route latency (DB roadmap Phase 1): every minute, `route latency` logs each HTTP route's request count, p50, p95 and+ * max in ms, routes that took the most time first. Same cadence as `cpu by kind` (lib/selfProfile.ts), but always on. A+ * route is its pattern (`GET /api/items/:id`), never its URL. Each route keeps a bounded random sample (reservoir) for its+ * percentiles; its count and max cover every request.+ */++type Window = { n: number; max: number; samples: number[] }++export type RouteLatencyOptions = {+ pod?: string+ /** Samples one route keeps per window. */+ maxSamples?: number+ /** Routes one window keeps, `other` included. */+ maxRoutes?: number+ /** Routes one line lists. */+ top?: number+ random?: () => number+ log?: (message: string, context: Record<string, unknown>) => void+}++export type RouteLatency = { record(route: string, ms: number): void; flush(): void }++const OTHER = 'other'++/** Nearest-rank percentile of sorted values. */+const percentile = (sorted: number[], p: number) => sorted[Math.max(0, Math.ceil(p / 100 * sorted.length) - 1)] ?? 0+const round = (ms: number) => Math.round(ms * 10) / 10++export function createRouteLatency({ pod = `${hostname()}:${process.pid}`, maxSamples = 2000, maxRoutes = 200, top = 40, random = Math.random,+ log = (m, c) => logger.info(m, c) }: RouteLatencyOptions = {}): RouteLatency {+ let routes = new Map<string, Window>(), started = performance.now()++ const record = (route: string, ms: number) => {+ let window = routes.get(route)+ if (!window) {+ const key = routes.size >= maxRoutes - 1 ? OTHER : route+ window = routes.get(key)+ if (!window) routes.set(key, window = { n: 0, max: 0, samples: [] })+ }+ window.n+++ if (ms > window.max) window.max = ms+ if (window.samples.length < maxSamples) window.samples.push(ms)+ else {+ const slot = Math.floor(random() * window.n)+ if (slot < maxSamples) window.samples[slot] = ms+ }+ }++ const flush = () => {+ const rows = [...routes].map(([route, w]) => {+ const sorted = w.samples.sort((a, b) => a - b)+ const mean = sorted.reduce((total, ms) => total + ms, 0) / (sorted.length || 1)+ return { route, totalMs: mean * w.n, stats: { n: w.n, p50: round(percentile(sorted, 50)), p95: round(percentile(sorted, 95)), max: round(w.max) } }+ }).sort((a, b) => b.totalMs - a.totalMs).slice(0, top)+ log('route latency', { pod, windowMs: Math.round(performance.now() - started), requests: [...routes.values()].reduce((total, w) => total + w.n, 0),+ routes: Object.fromEntries(rows.map(r => [r.route, r.stats])) })+ routes = new Map(); started = performance.now()+ }++ return { record, flush }+}++/** Records every response's time under its route pattern. Returns the recorder, for a flush on shutdown. */+export function registerRouteLatency(app: FastifyInstance, options: RouteLatencyOptions = {}): RouteLatency {+ const latency = createRouteLatency(options)+ app.addHook('onResponse', (request, reply, done) => {+ latency.record(`${request.method} ${request.routeOptions.url ?? 'unrouted'}`, reply.elapsedTime)+ done()+ })+ return latency+}++/** Starts the per-minute line on a recorder. Returns a stop that logs the last partial window. */+export function startRouteLatency(latency: RouteLatency, reportMs = 60_000): () => void {+ const timer = setInterval(() => latency.flush(), reportMs)+ timer.unref()+ return () => { clearInterval(timer); latency.flush() }+}diff --git a/backend/src/lib/selfProfile.test.ts b/backend/src/lib/selfProfile.test.tsindex f5c4d4ca4..58732566d 100644--- a/backend/src/lib/selfProfile.test.ts+++ b/backend/src/lib/selfProfile.test.ts@@ -1,6 +1,7 @@import Fastify from 'fastify'import { afterEach, expect, it } from 'vitest'import { frameKind, markCpuKind, selfProfileFromEnv, startSelfProfile, topSelfTime } from './selfProfile.js'+import { enterWork, workKind } from './queryStats.js'let stop = () => {}afterEach(() => stop())@@ -75,3 +76,12 @@ it('names HTTP requests when CPU_SELF_PROFILE=1, and adds no request hook when iexpect(off.started).toBe(false)expect(off.kinds).not.toContain('http GET /api/off')})++it('names the work for the query stats too, with the profile off', async () => {+ const seen = await new Promise<string>(resolve => setImmediate(() => {+ markCpuKind('web-ws swarm_changes')+ void Promise.resolve().then(() => resolve(workKind()))+ }))+ expect(seen).toBe('web-ws swarm_changes')+ enterWork(undefined)+})diff --git a/backend/src/lib/selfProfile.ts b/backend/src/lib/selfProfile.tsindex 6cd646634..ad8266df0 100644--- a/backend/src/lib/selfProfile.ts+++ b/backend/src/lib/selfProfile.ts@@ -3,6 +3,7 @@ import { Session } from 'node:inspector/promises'import { performance } from 'node:perf_hooks'import type { FastifyInstance } from 'fastify'import { logger } from '../utils/logger.js'+import { enterWork } from './queryStats.js'/*** Where this process spends its CPU, logged from production without a debugger (#314: five pods with few people).@@ -23,8 +24,10 @@ let busy = new Map<string, number>()/** Names one window keeps; work under any further name counts as `other`, so memory stays bounded. */const MAX_KINDS = 50-/** Names the work running now, and everything it goes on to schedule. A no-op unless the profile is on. */+/** Names the work running now, and everything it goes on to schedule: always for the query stats (lib/queryStats.ts),+ * and for the CPU accounting when the profile is on. */export function markCpuKind(kind: string): void {+ enterWork(kind)if (!enabled) returnconst resource = executionAsyncResource() as Taggedif (resource) resource[KIND] = kinddiff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex 5fec99ed7..ec07fee63 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -48,7 +48,7 @@ const workspaceTransfer = z.object({ userId: id }).strict()const workspaceVisibility = z.object({ visibility: z.enum(['invite-only', 'workspace']) }).strict()const workspaceJoin = z.object({ operationId: id }).strict()const personOnly = (user: AuthUser) => { if (isTeamSession(user)) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403) }-const listQuery = z.object({ after: id.optional() }).strict()+const listQuery = z.object({ after: id.optional(), mentions: z.literal('1').optional() }).strict()const cursor = z.string().min(1).max(512).regex(/^[A-Za-z0-9_-]+$/)const changesQuery = agentQuery.extend({ cursor })const costsQuery = z.object({ days: z.coerce.number().int().min(1).max(MAX_DAYS).default(DEFAULT_DAYS), asAgentId: id.optional() }).strict()@@ -295,7 +295,7 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su(req, reply) => respond(reply, () => store.tabPolicy(req.user!, req.params.tabId, req.query.asAgentId)))app.get('/api/super-tabs', updateRequired)app.get<{ Querystring: z.infer<typeof listQuery> }>('/api/super-tabs/list', { preHandler: validateQuery(listQuery) },- (req, reply) => respond(reply, () => reads.list(req.user!, req.query.after)))+ (req, reply) => respond(reply, () => reads.list(req.user!, req.query.after, req.query.mentions === '1')))app.post<{ Body: z.infer<typeof create> }>('/api/super-tabs', { preHandler: validateBody(create) },(req, reply) => respond(reply, () => store.create(req.user!, req.body.operationId, req.body.name, req.body.projectVisibility, req.body.workspaceId)))// Workspaces (docs/plans/2026-10-27-swarm-workspaces.md): the person's Workspaces and the Swarms they may see in each.diff --git a/backend/src/server.ts b/backend/src/server.tsindex e63985f06..824199c29 100644--- a/backend/src/server.ts+++ b/backend/src/server.ts@@ -30,6 +30,8 @@ import { createRouteRateLimit } from './middlewares/routeRateLimit.js'import { redisWindowCounter } from './lib/redisRateCounter.js'import { selfProfileFromEnv } from './lib/selfProfile.js'import { startRelayUsageFlush } from './lib/productUsage.js'+import { registerWorkContext, startQueryStats } from './lib/queryStats.js'+import { registerRouteLatency, startRouteLatency } from './lib/routeLatency.js'import { drainAllSockets, openSocketCount, RELEASE_UPGRADE_SLOT, type SlotSocket } from './lib/wsServer.js'import { endpointOf, refusedUpgrade, startWsCounterLog, watchUpgrade } from './lib/wsAttribution.js'@@ -133,8 +135,13 @@ const app = Fastify({async function start(): Promise<void> {// Mint the Cloudflare TURN credential before the first socket lands; no-op when TURN is unconfigured.startTurnCredentialRefresh()+ // Every request is named by its route pattern before any hook reads the database, so its queries count for it.+ registerWorkContext(app)// Off by default: logs this process's CPU by kind of work every minute, and a 30 s profile every 15 min (#314).selfProfileFromEnv(app)+ // Always on, every minute (DB roadmap Phase 1): queries by model.action, filter shape and route, and each route's p50/p95.+ const stopQueryStats = startQueryStats()+ const stopRouteLatency = startRouteLatency(registerRouteLatency(app))app.setErrorHandler(errorHandler)@@ -215,6 +222,9 @@ async function start(): Promise<void> {await Promise.race([fastifyClosed, new Promise((resolve) => setTimeout(resolve, 5_000))])// The sockets have closed, so no connect is left to count. Bounded: a slow database must not hold the exit.await Promise.race([stopRelayUsage().catch(() => {}), new Promise((resolve) => setTimeout(resolve, 3_000))])+ // The last partial minute of both logs, once the drain and the usage flush have run their queries.+ stopQueryStats()+ stopRouteLatency()// The database stays connected through the drain, for the requests still being served (lib/prisma.ts).await Promise.allSettled([prisma.$disconnect(), closeBus()])process.exit(exitCode)diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.tsindex 50a60fc6d..9bd2d180f 100644--- a/backend/src/superTabs/commands.test.ts+++ b/backend/src/superTabs/commands.test.ts@@ -750,6 +750,19 @@ describe('route.record and route.override', () => {expect(() => run(sized('small', patch))).toThrow()}})+ it('writes the job kind from the group\'s owned paths, then the route word, and never takes one sent with the route', () => {+ const f = routed(), group = f.group()+ const route = (conversationId: string, patch: Record<string, unknown> = {}, kind?: string) => f.run({ type: 'route.record', conversationId,+ decision: record({ ...patch, assessment: { difficulty: 'high', risk: 'low', why: 'Schema change.', ...(kind ? { kind } : {}) } }) } as Command, f.leadActor, {}).routeDecisions[0]+ f.run({ type: 'work.define', conversationId: group, task: { goal: 'g', changes: 'c', constraints: 'k', owns: ['backend/src/superTabs', 'backend/src/superTabs/store.test.ts'] },+ checks: [{ description: 'Tests pass.', independent: false }] })+ expect(route(group, {}, 'ui')).toMatchObject({ record: { jobKind: 'backend', assessment: { kind: 'ui' } } })+ expect(route(group, {}, 'security')).toMatchObject({ record: { jobKind: 'security' } })+ expect(route(group, { jobKind: 'docs' })).toMatchObject({ record: { jobKind: 'backend' } })+ // The Lead conversation owns nothing: the route word decides, and a word outside the list is general.+ expect(route('lead', {}, 'mobile')).toMatchObject({ record: { jobKind: 'mobile' } })+ expect(route('lead', {}, 'parser')).toMatchObject({ record: { jobKind: 'general' } })+ })it('refuses a pick outside the candidates, a non-lead agent and a busy hour', () => {const f = routed()const route = (decision: unknown, actor: Actor, context: Partial<CommandContext>) =>@@ -1419,6 +1432,63 @@ describe('Reviewer role', () => {expect(f.run({ type: 'work.status', conversationId: group, assignmentId, status: 'review', result: 'Head 789' }, builderActor).messages[0]!.recipients).toEqual([lead])})+ describe('work waiting for its review (liveness.ts: its quiet time does not count)', () => {+ const HOUR = 3_600_000, QUIET = 30 * 60_000+ function handedOver(status: 'review' | 'working') {+ const setup = reviewed()+ const { f, group, builder, reviewer } = setup+ const built = f.run({ type: 'work.assign', conversationId: group, agentId: builder }).result.assignmentId as string+ const builderActor: Actor = { kind: 'agent', agentId: builder, machineOwnerId: 'host-owner' }+ const reviewerActor: Actor = { kind: 'agent', agentId: reviewer, machineOwnerId: 'target-owner' }+ f.run({ type: 'work.status', conversationId: group, assignmentId: built, status, result: 'Ready for review: PR #42 at abc1234' }, builderActor, { now: 2000 })+ const checkId = f.state.conversations.find(c => c.id === group)!.checks[0]!.id+ const verdict = (passed: boolean, now: number) => f.run({ type: 'work.check', conversationId: group, assignmentId: built, checkId, passed,+ evidence: passed ? 'Passed at abc1234' : 'Two findings at abc1234' }, reviewerActor, { now })+ const task = () => f.state.conversations.find(c => c.id === group)!.assignment!+ /** The task's status after the time checks ran at `now`, on a copy. */+ const swept = (now: number) => { const copy = structuredClone(f.state); sweepLiveness(copy, now); return copy.conversations.find(c => c.id === group)!.assignment!.status }+ return { ...setup, built, builderActor, verdict, task, swept }+ }++ it('moves work in review back to working when a review finds problems, tells its Engineer, and counts its quiet time from then', () => {+ const { verdict, task, swept, builder } = handedOver('review')+ const foundAt = 2000 + 2 * HOUR+ expect(swept(foundAt)).toBe('review')+ const found = verdict(false, foundAt)+ expect(task()).toMatchObject({ status: 'working', result: 'Ready for review: PR #42 at abc1234' })+ expect(found.messages.find(m => m.recipients.includes(builder))?.text).toBe('Working\n\nThe review found problems. Fix them, then hand it over for review again.')+ expect(swept(foundAt + QUIET)).toBe('working')+ expect(swept(foundAt + QUIET + 1)).toBe('lost')+ })++ it('keeps work in review when the review passes', () => {+ const { verdict, task, swept } = handedOver('review')+ expect(verdict(true, 2000 + HOUR).messages).toEqual([])+ expect(task().status).toBe('review')+ expect(swept(2000 + 2 * HOUR)).toBe('review')+ })++ it('counts a working hand-off\'s quiet time once a review finds problems, and pauses it again at the Engineer\'s next hand-off', () => {+ const { f, group, built, builderActor, verdict, task, swept } = handedOver('working')+ const foundAt = 2000 + 2 * HOUR+ expect(swept(foundAt)).toBe('working')+ verdict(false, foundAt)+ expect(task().status).toBe('working')+ expect(swept(foundAt + QUIET)).toBe('working')+ expect(swept(foundAt + QUIET + 1)).toBe('lost')+ f.run({ type: 'work.status', conversationId: group, assignmentId: built, status: 'working', result: 'Ready for review: PR #42 at def5678' }, builderActor, { now: foundAt + HOUR })+ expect(swept(foundAt + 3 * HOUR)).toBe('working')+ })++ it('counts quiet time from when the Lead moves the work out of review', () => {+ const { f, group, built, leadActor, swept } = handedOver('review')+ const movedAt = 2000 + 2 * HOUR+ f.run({ type: 'work.status', conversationId: group, assignmentId: built, status: 'working', result: 'Rebase on main' }, leadActor, { now: movedAt })+ expect(swept(movedAt + QUIET)).toBe('working')+ expect(swept(movedAt + QUIET + 1)).toBe('lost')+ })+ })+describe('a review the Swarm opens by itself', () => {const pr = 'https://github.com/example/project/pull/42'/** reviewed() with the project's repository, the Builder working, and a second Reviewer `fresh` that is not in the group. */@@ -3392,7 +3462,8 @@ describe('stepping up from a cheap model', () => {expect(g().stepUp!.carry).toContain(pr)expect(g().stepUp!.carry).toContain('Ready: no. Two links are broken.')expect(g().stepUp!.carry).toContain('Ready: yes. Branch fix/docs.')- expect(effects.messages.find(m => m.recipients.includes(kimi))!.text).toContain('Stop working on it.')+ // Told only to stop: a stepped-up attempt is not handed back to fix its findings.+ expect(effects.messages.filter(m => m.recipients.includes(kimi)).map(m => m.text)).toEqual([expect.stringContaining('Stop working on it.')])// Each row its own: one write stores them all.expect(new Set(effects.messages.map(m => m.id)).size).toBe(effects.messages.length)expect(effects.messages.find(m => m.recipients.includes(f.lead))!.text)@@ -3413,7 +3484,8 @@ describe('stepping up from a cheap model', () => {expect(g().stepUp).toMatchObject({ attempt: 3, floor: 3 })const opus = builder('opus', 'claude-opus-4-7'), third = assign(opus)expect(fail(third.assignmentId, opus).messages.some(m => m.text.includes('stepped up'))).toBe(false)- expect(g().assignment).toMatchObject({ id: third.assignmentId, status: 'review' })+ // Not stepped up: a review that found problems hands it back to its Builder (liveness.ts reviewFoundProblems).+ expect(g().assignment).toMatchObject({ id: third.assignmentId, status: 'working' })})it('stops after two steps, and never steps up work that did not start on the grid', () => {@@ -3422,14 +3494,14 @@ describe('stepping up from a cheap model', () => {const first = assign(opus)fail(first.assignmentId, opus)expect(g().stepUp).toBeUndefined()- expect(g().assignment!.status).toBe('review')+ expect(g().assignment!.status).toBe('working')// At the cap a failed Sonnet attempt stays with its Builder.const { builder: other, assign: give, fail: failIt, g: group } = cheap()group().stepUp = { attempt: 3, floor: 3, reason: 'Earlier.', at: 1, carry: '' }const sonnet = other('sonnet', 'claude-sonnet-4-5')failIt(give(sonnet).assignmentId, sonnet)expect(group().stepUp!.attempt).toBe(3)- expect(group().assignment!.status).toBe('review')+ expect(group().assignment!.status).toBe('working')})it('steps up a group whose grid start failed, and not one whose subscription start failed', () => {@@ -3455,7 +3527,7 @@ describe('stepping up from a cheap model', () => {const attempt = assign(codex)fail(attempt.assignmentId, codex)expect(g().stepUp!.attempt).toBe(2)- expect(g().assignment).toMatchObject({ id: attempt.assignmentId, status: 'review' })+ expect(g().assignment).toMatchObject({ id: attempt.assignmentId, status: 'working' })})it('steps up once for one failed grid start, however often its failure is reported', () => {diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex afe740e56..0ad679172 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -8,6 +8,7 @@ import {finishWorker, requireWorkerDecisions, reviewing, seenMachineIds, swarmGridName, visibleState, AGENT_ONLY, forRecipients,type Actor, type AgentStartRequest, type WorkTask, type Agent, type Author, type CommandEffects, type Conversation, type SuperTabState,} from './model.js'+import { jobKindOf } from './evidence/jobKind.js'import { routeRecordSchema, routeTitle, startedAs, type RouteCandidate, type RouteDecision, type RouteFinal, type RouteOverride } from './routeRecord.js'import { DEFAULT_ROUTING_POLICY, routingOverrideSchema, type RoutingPolicy } from './routingPolicy.js'import { agentTarget, askedInSchema, broken, MAX_RULES, reviewRefusal, RULE_MESSAGE_MS, sameEngineReview, ruleSchema, ruleTextSchema, startTarget, unmet, type RunTarget } from './rules.js'@@ -15,14 +16,14 @@ import { MAX_ATTACHMENTS, type Attachment } from './attachments.js'import { checkMentions, MAX_MENTIONS, type MentionTarget } from './mentions.js'import { answerDecision, askDecisions, checkAsker, decisionChoices, decisionQuestion, MAX_OPEN_DECISIONS, MAX_QUESTIONS, type DecisionTarget } from './decisions.js'import { TERMINAL_KEYS, terminalAlert, terminalRequest, terminalResult, toLead, type TerminalRequest } from './terminal.js'-import { leadNoticeRows, loseTasks, recordTaskState, renewLease, renewOwnTask } from './liveness.js'+import { leadNoticeRows, loseTasks, recordTaskState, renewLease, renewOwnTask, restartQuietTime, reviewFoundProblems, waitingForReview } from './liveness.js'import { ABANDONED, failureNotice, MACHINE_REMOVED } from './startFailure.js'import { noteStartFailed, noteStartSucceeded, resumeEngine } from './engineHealth.js'import { digestStartsAfter, knownTimeZone } from './digest.js'import { credentialResult, redactCredentials, type CredentialKind } from './credentials.js'import { dirtyGroups, reportGroups, summarize } from './projectUpdates.js'import { workspaceCan, type WorkspaceRole } from './workspaces.js'-import { LEDGER_WEEKS, PULL_REQUEST_URL, recordAsked, recordDecision, recordMerged, recordPost, recordProposal, recordReview, recordRun, recordStatus,+import { fixedOriginal, LEDGER_WEEKS, PULL_REQUEST_URL, recordAsked, recordFix, recordDecision, recordMerged, recordPost, recordProposal, recordReview, recordRun, recordStatus,recordVerdict } from './leaderboard/record.js'import { WEEK_MS } from './leaderboard/week.js'import { react, reactionSchema, type ReactionTarget } from './reactions.js'@@ -135,8 +136,9 @@ export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('conversation.archive'), conversationId: id, archived: z.boolean() }).strict(),z.object({ type: z.literal('conversation.requester'), conversationId: id, personId: id.nullable() }).strict(),// The Lead's record that a request's pull request merged (leaderboard/record.ts recordMerged); `mergedAt` for a backfill.+ // `fixes`: the merged PR this one fixes, for its model's fixes after merge (leaderboard/record.ts recordFix).z.object({ type: z.literal('conversation.merged'), conversationId: id, pullRequestUrl: z.string().max(400).regex(PULL_REQUEST_URL),- mergedAt: z.iso.datetime().optional() }).strict(),+ mergedAt: z.iso.datetime().optional(), fixes: z.string().max(400).regex(PULL_REQUEST_URL).optional() }).strict(),z.object({ type: z.literal('agent.add'), conversationId: id, machineId: id, harnessId: id, name: title, configuration, lead: z.boolean(), project: project.optional(), roleId: roleId.optional(), initialMessage: text.optional() }).strict(),z.object({ type: z.literal('agent.start'), request: startRequestSchema, routeDecisionId: id.optional(), overrideReason: reason.optional() }).strict(),// A Buddy's proposal for its owner, posted in its project's chat: `conversationId` is its own chat, and `ownerMessageId` its@@ -1302,16 +1304,22 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaif (mergedAt > context.now || mergedAt <= context.now - (LEDGER_WEEKS - 1) * WEEK_MS) {fail('MERGE_TIME', 'Record a merge from the last four weeks, not one still to come.', 400)}+ // One refusal for every link it cannot take, so a link never tells what another project or a private chat holds.+ const original = command.fixes === undefined ? undefined : fixedOriginal(state, group, command.fixes, mergedAt)+ ?? fail('FIX_LINK', 'No merged pull request in this project matches that link within the last 14 days.', 400)const shippedAt = group.ledger?.shippedAt, linked = group.pullRequestUrls?.includes(command.pullRequestUrl)appendPullRequestUrls(group, [command.pullRequestUrl])recordMerged(group, mergedAt)// Like a Slack app's update: the card shows the merge, and the line goes in the card's thread, once per pull request.- // Without a card yet, the group's first ship or a new link still says so, and the line becomes the card.+ // Without a card yet, the group's first ship or a new link still says so, and the line becomes the card. A fix of an+ // earlier merge says so once more.+ const fixed = original ? recordFix(original, group, mergedAt) : falseconst card = pullRequestCard(group, command.pullRequestUrl)- if (card ? card.mergedAt === undefined : !linked || group.ledger!.shippedAt !== shippedAt) {- message(group.id, `Merged ${command.pullRequestUrl}`, [], card?.messageId ?? null, SYSTEM_ROW)- if (card) effects.messages.at(-1)!.thread = card.messageId- else bindPullRequestCards(group, effects.messages.at(-1)!)+ if (fixed || (card ? card.mergedAt === undefined : !linked || group.ledger!.shippedAt !== shippedAt)) {+ message(group.id, `Merged ${command.pullRequestUrl}${original ? `, a fix of ${command.fixes}` : ''}`, [], card?.messageId ?? null, SYSTEM_ROW)+ const posted = effects.messages.at(-1)!+ if (card) posted.thread = card.messageId+ else bindPullRequestCards(group, posted)}recordCardMerged(group, command.pullRequestUrl, mergedAt)break@@ -1959,9 +1967,10 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma// the server's own judgement (rules.ts).const step = conversation(state, command.conversationId).stepUpconst sameEngine = sameEngineReview(state, conversation(state, command.conversationId).reviewOf, member ? agentTarget(state, member) : chosen, policy, mayRun(command.conversationId, true))- const { stepUp: _sent, sameEngine: _said, ...made } = decision+ const { stepUp: _sent, sameEngine: _said, jobKind: _kind, ...made } = decision+ const jobKind = jobKindOf(conversation(state, command.conversationId), decision.assessment.kind)effects.routeDecisions.push({ op: 'create', id: operationId, conversationId: command.conversationId,- record: { ...made, ...step ? { stepUp: { attempt: step.attempt, reason: step.reason } } : {}, ...sameEngine ? { sameEngine } : {} } })+ record: { ...made, ...step ? { stepUp: { attempt: step.attempt, reason: step.reason } } : {}, ...sameEngine ? { sameEngine } : {}, jobKind } })result.routeDecisionId = operationId// The row quotes the Lead's reason for the task; the verdict's own text stays in the decision record.const reason = decision.assessment.why@@ -2110,8 +2119,11 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaelse effects.result.notAsked = `Not asked ${person(state, personId).email}: ${context.openDecisions} decisions you asked them are still open, and at most ${MAX_OPEN_DECISIONS} can be. Wait for answers before asking more.`}const changed = assignment.status !== command.status || assignment.result !== command.result || !!command.ask, previous = assignment.status+ const waited = waitingForReview(assignment)assignment.status = command.statusassignment.result = command.result+ // A new status is a new hand-off, or the end of one: a review's earlier findings are answered.+ delete assignment.reviewFoundAtif (command.ask) assignment.askedOf = command.ask.personIdelse if (command.status !== 'needs_human') delete assignment.askedOfrecordStatus(group, assignment, previous, context.now, changed ? operationId : null, asked)@@ -2145,6 +2157,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma}}if (actor.kind === 'agent') renewOwnTask(group, actor.agentId, context.now)+ // The time it waited for its review never counts, whoever moved it on.+ if (waited && activeWork(group) && !waitingForReview(assignment)) restartQuietTime(assignment, context.now)break}case 'work.cancel': {@@ -2213,6 +2227,11 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: CommarecordReview(group, check, command.passed)// A cheap attempt whose first review just said Ready no steps up a tier (stepUp.ts).if (reviewed === undefined && run?.firstReview === false && cheapAttempt(group, policy)) steppedUp(group, REVIEW_FAILED)+ // Otherwise a review that found problems hands the work back to its Engineer, whose quiet time counts again (liveness.ts).+ // A stepped-up attempt was cancelled just above, so it is not waiting for its review and its Engineer is told only to stop.+ if (check.independent && !command.passed && reviewFoundProblems(group.assignment, context.now)) {+ message(group.id, 'Working\n\nThe review found problems. Fix them, then hand it over for review again.', [group.assignment.agentId], null, SYSTEM_ROW)+ }if (actor.kind === 'agent') renewOwnTask(group, actor.agentId, context.now)break}diff --git a/backend/src/superTabs/evidence/contribution.test.ts b/backend/src/superTabs/evidence/contribution.test.tsnew file mode 100644index 000000000..58a64d1e2--- /dev/null+++ b/backend/src/superTabs/evidence/contribution.test.ts@@ -0,0 +1,106 @@+import { describe, expect, it } from 'vitest'+import type { Conversation } from '../model.js'+import type { RouteRun } from '../costs/attempts.js'+import { weekStart } from '../leaderboard/week.js'+import { contributionOf, increments, type Contribution, type EvidenceDecision } from './contribution.js'++const MINUTE = 60_000, START = Date.UTC(2026, 9, 28, 9)+const run = (patch: Partial<RouteRun> = {}): RouteRun => ({ machineId: 'm', harnessId: 'h', engine: 'claude', model: 'claude-opus-5-5', effort: 'high',+ billing: 'subscription', startedAt: START, start: { 'claude-opus-5-5': { input: 1_000, output: 0, cacheRead: 0, cacheWrite: 0 } },+ endedAt: START + 30 * MINUTE, end: { 'claude-opus-5-5': { input: 1_001_000, output: 100_000, cacheRead: 0, cacheWrite: 0 } }, ...patch })+const decision = (patch: Partial<EvidenceDecision> = {}): EvidenceDecision => ({ assignmentId: 'a1', outcome: 'done', final: { kind: 'member' },+ record: { assessment: { kind: 'ui' }, jobKind: 'backend' }, run: run(), ...patch })+const group = (ledger: Conversation['ledger'] = {}, owns = ['cli/src']): Pick<Conversation, 'reviewOf' | 'task' | 'ledger'> =>+ ({ task: { goal: 'g', changes: 'c', constraints: 'k', owns }, ledger })+const ranOn = { engine: 'claude', model: 'opus' }++describe('what one attempt adds to its model and kind', () => {+ it('adds nothing while the attempt is open or has no run', () => {+ expect(contributionOf(decision({ outcome: null }), group(), null, 'p1')).toBeNull()+ expect(contributionOf(decision({ run: null }), group(), null, 'p1')).toBeNull()+ })++ it('counts an ended attempt under its engine and model, the grid model by its own name, efforts merged, in the week it started', () => {+ const made = contributionOf(decision(), group(), null, 'p1')!+ expect(made).toMatchObject({ engine: 'claude', model: 'claude-opus-5-5', kind: 'backend', week: weekStart(START),+ counts: { attempts: 1, firstReviews: 0, firstReviewPassed: 0, reworkRounds: 0, shipped: 0, fixesAfterMerge: 0, minutesToShipCount: 0 } })+ expect(contributionOf(decision({ run: run({ effort: 'low' }) }), group(), null, 'p1')).toMatchObject({ engine: 'claude', model: 'claude-opus-5-5' })+ expect(contributionOf(decision({ run: run({ model: 'default', grid: 'moonshotai/kimi-k3', billing: 'api' }) }), group(), null, 'p1'))+ .toMatchObject({ model: 'moonshotai/kimi-k3' })+ })++ it('counts its tokens and cost at list prices, with the spend its billing says', () => {+ const { counts } = contributionOf(decision(), group(), null, 'p1')!+ // 1,000,000 input at $4 and 100,000 output at $20 per million.+ expect(counts).toMatchObject({ tokensInput: 1_000_000, tokensOutput: 100_000, tokensKnown: 1, costKnown: 1, costUnknown: 0, spend: 0, spendKnown: 1 })+ expect(counts.apiCost).toBeCloseTo(6, 9)+ expect(contributionOf(decision({ run: run({ billing: 'api' }) }), group(), null, 'p1')!.counts.spend).toBeCloseTo(6, 9)+ const unknown = contributionOf(decision({ run: run({ end: null }) }), group(), null, 'p1')!.counts+ expect(unknown).toMatchObject({ tokensKnown: 0, costKnown: 0, costUnknown: 1, apiCost: 0 })+ })++ it('takes its first review and rework rounds from its ledger entry', () => {+ const ledger = { runs: [{ assignmentId: 'a1', at: START, ...ranOn, firstReview: false, reworkRounds: 2 }] }+ expect(contributionOf(decision(), group(ledger), null, 'p1')).toMatchObject({ firstReview: false, counts: { firstReviews: 1, firstReviewPassed: 0, reworkRounds: 2 } })+ const passed = { runs: [{ assignmentId: 'a1', at: START, ...ranOn, firstReview: true }] }+ expect(contributionOf(decision(), group(passed), null, 'p1')).toMatchObject({ firstReview: true, counts: { firstReviews: 1, firstReviewPassed: 1, reworkRounds: 0 } })+ })++ it('ships, with its minutes to ship and a fix after merge, only on the attempt the request shipped on', () => {+ const ledger = { shippedAt: START + 90 * MINUTE, shippedBy: { assignmentId: 'a1', at: START, ...ranOn }, fixedAfterMergeAt: START + 2 * 86_400_000 }+ expect(contributionOf(decision(), group(ledger), null, 'p1')!.counts)+ .toMatchObject({ shipped: 1, minutesToShipSum: 90, minutesToShipCount: 1, fixesAfterMerge: 1 })+ expect(contributionOf(decision({ assignmentId: 'a0' }), group(ledger), null, 'p1')!.counts)+ .toMatchObject({ shipped: 0, minutesToShipSum: 0, minutesToShipCount: 0, fixesAfterMerge: 0 })+ })++ it('keeps what it counted from a ledger whose entry rolled off or a group that is gone', () => {+ const ledger = { runs: [{ assignmentId: 'a1', at: START, ...ranOn, firstReview: true, reworkRounds: 1 }],+ shippedAt: START + 10 * MINUTE, shippedBy: { assignmentId: 'a1', at: START, ...ranOn } }+ const before = contributionOf(decision(), group(ledger), null, 'p1')!+ expect(contributionOf(decision(), group({ ...ledger, runs: [] }), before, 'p1')).toEqual(before)+ expect(contributionOf(decision(), undefined, before, 'p1')).toEqual(before)+ })++ // Review of #2173: the weekly report shows each reader only the projects they can see, so each row keeps its project.+ it('counts the attempt under its group\'s project, and keeps the project counted before once the group is gone', () => {+ expect(contributionOf(decision(), group(), null, 'p1')).toMatchObject({ projectId: 'p1', model: 'claude-opus-5-5' })+ const before = contributionOf(decision(), group(), null, 'p1')!+ expect(contributionOf(decision(), undefined, before, undefined)).toMatchObject({ projectId: 'p1' })+ expect(contributionOf(decision(), undefined, null, undefined)).toBeNull()+ })++ it('takes the kind of a decision routed before kinds from its group and route word', () => {+ expect(contributionOf(decision({ record: { assessment: { kind: 'ui' } } }), group(), null, 'p1')!.kind).toBe('cli')+ expect(contributionOf(decision({ record: { assessment: { kind: 'docs' } } }), group({}, []), null, 'p1')!.kind).toBe('docs')+ expect(contributionOf(decision({ record: { assessment: {} } }), group({}, []), null, 'p1')!.kind).toBe('general')+ })+})++describe('the change one attempt makes to the store', () => {+ const made = (patch: Partial<Contribution> = {}, counts: Partial<Contribution['counts']> = {}): Contribution => {+ const base = contributionOf(decision(), group(), null, 'p1')!+ return { ...base, ...patch, counts: { ...base.counts, ...counts } }+ }++ it('adds a new contribution whole, and only the difference of a changed one', () => {+ const first = made()+ const nonZero = Object.fromEntries(Object.entries(first.counts).filter(([, n]) => n !== 0))+ expect(nonZero).toMatchObject({ attempts: 1, tokensKnown: 1 })+ expect(increments(null, first)).toEqual([{ key: first, counts: nonZero }])+ const shipped = made({}, { shipped: 1, minutesToShipSum: 12, minutesToShipCount: 1 })+ expect(increments(first, shipped)).toEqual([{ key: shipped, counts: { shipped: 1, minutesToShipSum: 12, minutesToShipCount: 1 } }])+ expect(increments(shipped, shipped)).toEqual([])+ })++ it('takes a withdrawn attempt back out, and moves one whose model or kind changed', () => {+ const first = made()+ expect(increments(first, null)).toEqual([{ key: first, counts: Object.fromEntries(Object.entries(first.counts).filter(([, n]) => n !== 0).map(([k, n]) => [k, -n])) }])+ expect(increments(first, made({ projectId: 'p2' })).map(c => [c.key.projectId, c.counts.attempts])).toEqual([['p1', -1], ['p2', 1]])+ const moved = made({ kind: 'docs' })+ const changes = increments(first, moved)+ expect(changes.map(c => c.key.kind)).toEqual(['backend', 'docs'])+ expect(changes[0]!.counts.attempts).toBe(-1)+ expect(changes[1]!.counts.attempts).toBe(1)+ })+})diff --git a/backend/src/superTabs/evidence/contribution.ts b/backend/src/superTabs/evidence/contribution.tsnew file mode 100644index 000000000..7c72634da--- /dev/null+++ b/backend/src/superTabs/evidence/contribution.ts@@ -0,0 +1,112 @@+/**+ * What one attempt adds to its model's evidence for its kind of job (evidence routing, Ken 2026-10-29): counts and sums only,+ * never a person, an agent or task text. Pure: evidence/store.ts keeps each attempt's contribution on its route decision and+ * adds only the difference when the attempt ends, ships, is reviewed again or is fixed after its merge.+ */+import type { Conversation } from '../model.js'+import { attemptTokens, type RouteRun } from '../costs/attempts.js'+import { attemptCost } from '../costs/cost.js'+import { weekStart } from '../leaderboard/week.js'+import { JOB_KINDS, jobKindOf, type JobKind } from './jobKind.js'++/** The counters a store row sums. Minutes to ship are a sum and a count, so they add up (an average, Lead 2026-10-29). Cost is+ * API-equivalent in US dollars over the attempts whose cost is known; `costUnknown` ended without one, so a cost per shipped+ * change over them would read cheaper than it was. */+export interface Counts {+ attempts: number+ firstReviews: number; firstReviewPassed: number+ reworkRounds: number+ shipped: number; minutesToShipSum: number; minutesToShipCount: number+ fixesAfterMerge: number+ tokensInput: number; tokensOutput: number; tokensCacheRead: number; tokensCacheWrite: number; tokensKnown: number+ apiCost: number; costKnown: number; costUnknown: number+ spend: number; spendKnown: number+}+export const COUNTS: ReadonlyArray<keyof Counts> = ['attempts', 'firstReviews', 'firstReviewPassed', 'reworkRounds', 'shipped', 'minutesToShipSum',+ 'minutesToShipCount', 'fixesAfterMerge', 'tokensInput', 'tokensOutput', 'tokensCacheRead', 'tokensCacheWrite', 'tokensKnown', 'apiCost', 'costKnown',+ 'costUnknown', 'spend', 'spendKnown']++/** The row an attempt counts in: its group's project (the report shows a reader only projects they see; review of #2173), its+ * engine, its model (a grid model by its own name; efforts merged), its kind and the week (Monday 00:00 UTC) it started. */+export interface EvidenceKey { projectId: string; engine: string; model: string; kind: JobKind; week: number }+/** One attempt's part, as its route decision keeps it. `firstReview` and `startedAt` feed the model's last-ten row. */+export interface Contribution extends EvidenceKey { counts: Counts; firstReview?: boolean; startedAt: number }++/** What of a route decision the contribution reads. `final.kind` `new`: its agent was started for it (costs/attempts.ts). */+export interface EvidenceDecision {+ assignmentId: string | null+ outcome: string | null+ final: { kind?: unknown } | null+ record: { assessment?: { kind?: unknown }; jobKind?: unknown }+ run: RouteRun | null+}++const zero = (): Counts => Object.fromEntries(COUNTS.map(k => [k, 0])) as unknown as Counts++/**+ * The attempt's part once it ended: null while it is open (or taken back by its session), or never ran. Its first review and+ * rework rounds come from its ledger entry, and its ship from the group's ledger; when that entry rolled off or the group is+ * gone, what was counted before stays, as those no longer change.+ */+export function contributionOf(decision: EvidenceDecision, group: Pick<Conversation, 'reviewOf' | 'task' | 'ledger'> | undefined,+ previous: Contribution | null, groupProjectId: string | undefined): Contribution | null {+ const run = decision.run+ const projectId = groupProjectId ?? previous?.projectId+ if (!run || decision.outcome == null || !decision.assignmentId || !projectId) return null+ const word = typeof decision.record.assessment?.kind === 'string' ? decision.record.assessment.kind : undefined+ const kind = (JOB_KINDS as readonly unknown[]).includes(decision.record.jobKind) ? decision.record.jobKind as JobKind : jobKindOf(group ?? {}, word)+ const counts = zero()+ counts.attempts = 1+ const entry = group?.ledger?.runs?.find(r => r.assignmentId === decision.assignmentId)+ let firstReview: boolean | undefined+ if (entry || !previous) {+ firstReview = entry?.firstReview+ if (firstReview !== undefined) { counts.firstReviews = 1; counts.firstReviewPassed = firstReview ? 1 : 0 }+ counts.reworkRounds = entry?.reworkRounds ?? 0+ } else {+ firstReview = previous.firstReview+ for (const k of ['firstReviews', 'firstReviewPassed', 'reworkRounds'] as const) counts[k] = previous.counts[k]+ }+ const ledger = group?.ledger+ if (ledger) {+ if (ledger.shippedBy?.assignmentId === decision.assignmentId && ledger.shippedAt !== undefined) {+ counts.shipped = 1+ counts.minutesToShipSum = Math.max(0, ledger.shippedAt - run.startedAt) / 60_000+ counts.minutesToShipCount = 1+ counts.fixesAfterMerge = ledger.fixedAfterMergeAt !== undefined ? 1 : 0+ }+ } else if (previous) {+ for (const k of ['shipped', 'minutesToShipSum', 'minutesToShipCount', 'fixesAfterMerge'] as const) counts[k] = previous.counts[k]+ }+ const fresh = decision.final?.kind === 'new'+ const used = attemptTokens(run, fresh)+ if (used) {+ counts.tokensKnown = 1+ for (const t of Object.values(used)) {+ counts.tokensInput += t.input; counts.tokensOutput += t.output; counts.tokensCacheRead += t.cacheRead; counts.tokensCacheWrite += t.cacheWrite+ }+ }+ const cost = attemptCost(run, fresh)+ if (cost.apiCost !== null) { counts.costKnown = 1; counts.apiCost = cost.apiCost } else counts.costUnknown = 1+ if (cost.spend !== null) { counts.spendKnown = 1; counts.spend = cost.spend }+ return { projectId, engine: run.engine, model: run.grid ?? run.model, kind, week: weekStart(run.startedAt), counts,+ ...(firstReview !== undefined ? { firstReview } : {}), startedAt: run.startedAt }+}++export const sameKey = (a: EvidenceKey, b: EvidenceKey): boolean =>+ a.projectId === b.projectId && a.engine === b.engine && a.model === b.model && a.kind === b.kind && a.week === b.week++/** The non-zero differences of [after] less [before], or all of [sign] times [counts]. */+const diff = (after: Counts, before: Counts | null, sign = 1): Partial<Counts> =>+ Object.fromEntries(COUNTS.map(k => [k, sign * (after[k] - (before?.[k] ?? 0))]).filter(([, n]) => n !== 0))++/** The increments that take the store from [before] to [after]: the difference in one row, or the old row's part taken out and+ * the new one's added when its key changed. Nothing when both are the same. */+export function increments(before: Contribution | null, after: Contribution | null): Array<{ key: EvidenceKey; counts: Partial<Counts> }> {+ if (before && after && sameKey(before, after)) {+ const counts = diff(after.counts, before.counts)+ return Object.keys(counts).length ? [{ key: after, counts }] : []+ }+ return [...before ? [{ key: before as EvidenceKey, counts: diff(before.counts, null, -1) }] : [],+ ...after ? [{ key: after as EvidenceKey, counts: diff(after.counts, null) }] : []].filter(c => Object.keys(c.counts).length)+}diff --git a/backend/src/superTabs/evidence/jobKind.test.ts b/backend/src/superTabs/evidence/jobKind.test.tsnew file mode 100644index 000000000..c35d989d0--- /dev/null+++ b/backend/src/superTabs/evidence/jobKind.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from 'vitest'+import { jobKindOf } from './jobKind.js'++const group = (owns: string[], reviewOf?: string) => ({ task: { goal: 'g', changes: 'c', constraints: 'k', owns }, ...(reviewOf ? { reviewOf } : {}) })++describe('job kind', () => {+ it('takes the kind its owned paths agree on, a path or a leading word', () => {+ expect(jobKindOf(group(['backend/src/superTabs/costs', 'backend/prisma/schema.prisma']))).toBe('backend')+ expect(jobKindOf(group(['backend Swarm route and attempt records', 'a new backend aggregate store module']))).toBe('backend')+ expect(jobKindOf(group(['cli/src/superTabs/route.ts']))).toBe('cli')+ expect(jobKindOf(group(['desktop/lib/super_tab/models.dart']))).toBe('desktop')+ expect(jobKindOf(group(['mobile/lib/main.dart']))).toBe('mobile')+ expect(jobKindOf(group(['docs/swarms.md']))).toBe('docs')+ expect(jobKindOf(group(['README.md', 'CONTRIBUTING.md']))).toBe('docs')+ })++ it('counts code with its own tests as the code, and only tests as tests', () => {+ expect(jobKindOf(group(['backend/src/superTabs/store.ts', 'backend/src/superTabs/store.test.ts', 'backend/integration/superTabs.test.ts']))).toBe('backend')+ expect(jobKindOf(group(['backend/src/superTabs/store.test.ts', 'cli/src/superTabs/route.spec.ts', 'desktop/test/models_test.dart']))).toBe('tests')+ expect(jobKindOf(group(['tests/e2e']))).toBe('tests')+ })++ it('falls back to the route word when the paths disagree or say nothing, and to general after that', () => {+ expect(jobKindOf(group(['backend/src', 'cli/src']), 'cli')).toBe('cli')+ expect(jobKindOf(group(['backend/src', 'cli/src']))).toBe('general')+ expect(jobKindOf(group(['the fix-after-merge record']), 'mobile')).toBe('mobile')+ expect(jobKindOf(group(['the fix-after-merge record']), 'ui')).toBe('general')+ expect(jobKindOf(group([]), 'parser')).toBe('general')+ expect(jobKindOf({}, undefined)).toBe('general')+ })++ it('keeps security work security whatever it owns, and a review group a review', () => {+ expect(jobKindOf(group(['backend/src/lib/ssoAuth.ts']), 'security')).toBe('security')+ expect(jobKindOf(group(['backend/src/superTabs'], 'build-group'), 'backend')).toBe('review')+ })++ it('reads a backtick, ./ or a capitalised word the same', () => {+ expect(jobKindOf(group(['`backend/src/superTabs/costs`']))).toBe('backend')+ expect(jobKindOf(group(['./cli/src']))).toBe('cli')+ expect(jobKindOf(group(['Desktop Models section']))).toBe('desktop')+ })+})diff --git a/backend/src/superTabs/evidence/jobKind.ts b/backend/src/superTabs/evidence/jobKind.tsnew file mode 100644index 000000000..5d2f602b8--- /dev/null+++ b/backend/src/superTabs/evidence/jobKind.ts@@ -0,0 +1,39 @@+/**+ * The kind of job a routed attempt is, from a fixed list, so models are compared on like work (evidence routing spec,+ * 2026-10-29, Ken). Owned paths decide first, then the Lead's route word, else general. The route word stays free-form for+ * owners' preferEngine rules; only its value from this list counts here.+ */+import type { Conversation } from '../model.js'++export const JOB_KINDS = ['docs', 'tests', 'backend', 'cli', 'desktop', 'mobile', 'security', 'review', 'general'] as const+export type JobKind = typeof JOB_KINDS[number]++const COMPONENTS = new Set<JobKind>(['backend', 'cli', 'desktop', 'mobile', 'docs'])+/** Test files and folders in this repository: `*.test.ts`, `*.spec.ts`, `*_test.dart`, `tests/`, `test/`, `integration/`. */+const TEST_PATH = /(\.(test|spec)\.[a-z]+$|_test\.dart$|(^|\/)(tests?|integration)(\/|$))/++/** What one owned entry names: a test path, a component by its first path segment or leading word, a Markdown file as docs,+ * or nothing. */+function entryKind(entry: string): JobKind | 'tests' | null {+ const plain = entry.trim().replace(/^[`'"]+|[`'"]+$/g, '').replace(/^\.\//, '')+ if (/^\S+$/.test(plain) && TEST_PATH.test(plain)) return 'tests'+ const first = plain.split(/[\s/]/, 1)[0]!.toLowerCase()+ if (COMPONENTS.has(first as JobKind)) return first as JobKind+ return /^\S+\.md$/i.test(plain) ? 'docs' : null+}++/**+ * The group's job kind. A review group is `review`; `security` from the route word wins, as no path names security work and+ * exploration must never touch it (spec constraint). Otherwise the one component its owned entries name, code with its own+ * tests counting as the code and only tests as `tests`; entries naming several components, or none, leave it to the route+ * word when that is a kind, else `general`.+ */+export function jobKindOf(group: Pick<Conversation, 'reviewOf'> & { task?: { owns: string[] } }, routeWord?: string): JobKind {+ if (group.reviewOf) return 'review'+ if (routeWord === 'security') return 'security'+ const kinds = new Set((group.task?.owns ?? []).map(entryKind).filter(k => k !== null))+ const components = [...kinds].filter(k => k !== 'tests')+ if (components.length === 1) return components[0]!+ if (!components.length && kinds.has('tests')) return 'tests'+ return (JOB_KINDS as readonly string[]).includes(routeWord ?? '') && routeWord !== 'review' ? routeWord as JobKind : 'general'+}diff --git a/backend/src/superTabs/evidence/store.ts b/backend/src/superTabs/evidence/store.tsnew file mode 100644index 000000000..934c7da07--- /dev/null+++ b/backend/src/superTabs/evidence/store.ts@@ -0,0 +1,170 @@+/**+ * Each Swarm's evidence of how its models do per kind of job (evidence routing, Ken 2026-10-29): one row per project, model,+ * kind and week with counts and sums, and one per project, model and kind with its last ten first reviews. Swarm-wide numbers+ * are the sum over projects; a reader's are over the projects they see (review of #2173). Route decisions expire at 90 days and+ * a group's ledger keeps 20 attempts, so this store keeps the history: 180 days. Rows hold no person, agent or task text.+ *+ * Written inside the store's write, after its attempt hooks (routeDecisions.ts): each attempt keeps its contribution on its+ * route decision, and a write that ends, ships, reviews or fixes an attempt adds only the difference. Concurrency: the+ * write's transaction; two writes adding to one row conflict and the store tries again (retry.ts). Read by routing and the+ * weekly report on the server only (readEvidence); nothing here is served to a reader. Rows past 180 days go on the Swarm's+ * next evidence write and in the hourly sweep (expireEvidence, sweeps.ts), whichever comes first.+ */+import type { Prisma } from '@prisma/client'+import { activeWork, stableId, type Conversation, type SuperTabState } from '../model.js'+import { groupProject } from '../projects.js'+import { DAY_MS, weekStart } from '../leaderboard/week.js'+import { ms } from '../parts/light.js'+import type { RouteRun } from '../costs/attempts.js'+import { contributionOf, COUNTS, increments, type Contribution, type Counts, type EvidenceKey } from './contribution.js'+import type { JobKind } from './jobKind.js'++type Tx = Prisma.TransactionClient+const json = (value: unknown): Prisma.InputJsonValue => JSON.parse(JSON.stringify(value)) as Prisma.InputJsonValue++export const EVIDENCE_RETENTION_MS = 180 * DAY_MS+/** First reviews a model's last-ten row keeps per kind (spec PM call 4). */+export const RECENT_RESULTS = 10+/** Weekly rows one read takes: a Swarm with 20 models in all 9 kinds over 180 days has about 4,700. */+export const MAX_WEEK_ROWS = 10_000++/** Whether a write changed what a group's evidence depends on: its attempt and whether it is active, its ship, a fix after+ * its merge. Its first reviews and rework rounds change only while an attempt is active (work.check), and that attempt's end+ * is a change here, so they need no comparing. A status change within active work is not a change. Compared field by field:+ * every write runs it over every group (under 0.1 ms for 1,000). */+function evidenceChanged(before: Conversation | undefined, after: Conversation): boolean {+ if (!before) return true+ const was = before.ledger, now = after.ledger+ return before.assignment?.id !== after.assignment?.id || activeWork(before) !== activeWork(after) || was?.shippedAt !== now?.shippedAt+ || was?.shippedBy?.assignmentId !== now?.shippedBy?.assignmentId || was?.fixedAfterMergeAt !== now?.fixedAfterMergeAt+}++/**+ * Brings the evidence of every group this write changed up to date: each of its attempts with a route decision is counted+ * again from its decision and the group's ledger, and only the difference is written. Called after the write's route+ * decisions are closed (closeAssignment) and their runs kept (recordAttempts).+ */+export async function recordEvidence(tx: Tx, tabId: string, before: SuperTabState, after: SuperTabState, now: number): Promise<void> {+ const earlier = new Map(before.conversations.map(c => [c.id, c]))+ const changed = after.conversations.filter(c => evidenceChanged(earlier.get(c.id), c))+ let wrote = false+ for (const group of changed) {+ const rows = await tx.superTabRouteDecision.findMany({ where: { tabId, conversationId: group.id },+ select: { id: true, assignmentId: true, outcome: true, final: true, record: true, run: true, evidence: true } })+ for (const row of rows) {+ if (!row.assignmentId || !row.run) continue+ const previous = (row.evidence ?? null) as unknown as Contribution | null+ const next = contributionOf({ assignmentId: row.assignmentId, outcome: row.outcome, final: row.final as { kind?: unknown } | null,+ record: row.record as { assessment?: { kind?: unknown }; jobKind?: unknown }, run: row.run as unknown as RouteRun }, group, previous,+ groupProject(after, group).id)+ if (JSON.stringify(previous) === JSON.stringify(next)) continue+ for (const change of increments(previous, next)) await addCounts(tx, tabId, change.key, change.counts, now)+ if (previous && (!next || !sameRow(previous, next) || previous.firstReview !== next.firstReview)) {+ await recordRecent(tx, tabId, previous, row.assignmentId, null, now)+ }+ if (next?.firstReview !== undefined) await recordRecent(tx, tabId, next, row.assignmentId, { at: next.startedAt, passed: next.firstReview }, now)+ await tx.superTabRouteDecision.update({ where: { id: row.id }, data: { evidence: next ? json(next) : null as unknown as Prisma.InputJsonValue } })+ wrote = true+ }+ }+ if (!wrote) return+ await tx.superTabModelEvidence.deleteMany({ where: { tabId, week: { lt: expiredWeek(now) } } })+ await tx.superTabModelRecent.deleteMany({ where: { tabId, updatedAt: { lt: new Date(now - EVIDENCE_RETENTION_MS) } } })+}++/** Weekly rows before this week's start are past retention. */+const expiredWeek = (now: number) => new Date(weekStart(now - EVIDENCE_RETENTION_MS))++/** Every Swarm's rows past 180 days, for the hourly sweep: a Swarm that stops routing still loses its old rows. By the+ * week and updatedAt indexes. Returns how many went. */+export async function expireEvidence(tx: Pick<Tx, 'superTabModelEvidence' | 'superTabModelRecent'>, now: number): Promise<number> {+ const weeks = await tx.superTabModelEvidence.deleteMany({ where: { week: { lt: expiredWeek(now) } } })+ const recent = await tx.superTabModelRecent.deleteMany({ where: { updatedAt: { lt: new Date(now - EVIDENCE_RETENTION_MS) } } })+ return weeks.count + recent.count+}++type ModelKey = Pick<EvidenceKey, 'engine' | 'model' | 'kind'>+const sameModel = (a: ModelKey, b: ModelKey): boolean => a.engine === b.engine && a.model === b.model && a.kind === b.kind+const sameRow = (a: Omit<EvidenceKey, 'week'>, b: Omit<EvidenceKey, 'week'>): boolean => a.projectId === b.projectId && sameModel(a, b)+const weekId = (tabId: string, key: EvidenceKey) => stableId('evidence', tabId, key.projectId, key.engine, key.model, key.kind, String(key.week))+const recentId = (tabId: string, key: Omit<EvidenceKey, 'week'>) => stableId('evidence-recent', tabId, key.projectId, key.engine, key.model, key.kind)++/** Adds to a week's row, creating it for an attempt's first part. A part taken out of a row that is gone (past retention)+ * is dropped rather than written as a negative row. */+async function addCounts(tx: Tx, tabId: string, key: EvidenceKey, counts: Partial<Counts>, now: number): Promise<void> {+ const id = weekId(tabId, key), updatedAt = new Date(now)+ const { count } = await tx.superTabModelEvidence.updateMany({ where: { id, tabId },+ data: { ...Object.fromEntries(Object.entries(counts).map(([k, n]) => [k, { increment: n }])), updatedAt } })+ if (count || (counts.attempts ?? 0) <= 0) return+ await tx.superTabModelEvidence.create({ data: { id, tabId, projectId: key.projectId, engine: key.engine, model: key.model, kind: key.kind, week: new Date(key.week), ...counts, updatedAt } })+}++interface RecentResult { a: string; at: number; passed: boolean }++/** Sets or removes one attempt's first review in its model's last-ten row, oldest first. */+async function recordRecent(tx: Tx, tabId: string, key: Omit<EvidenceKey, 'week'>, assignmentId: string, result: { at: number; passed: boolean } | null,+ now: number): Promise<void> {+ const id = recentId(tabId, key)+ const row = await tx.superTabModelRecent.findFirst({ where: { id, tabId }, select: { results: true } })+ const results = ((row?.results ?? []) as unknown as RecentResult[]).filter(r => r.a !== assignmentId)+ if (result) results.push({ a: assignmentId, ...result })+ const kept = results.sort((x, y) => x.at - y.at).slice(-RECENT_RESULTS)+ if (row) await tx.superTabModelRecent.update({ where: { id }, data: { results: json(kept), updatedAt: new Date(now) } })+ else if (kept.length) await tx.superTabModelRecent.create({ data: { id, tabId, projectId: key.projectId, engine: key.engine, model: key.model, kind: key.kind, results: json(kept), updatedAt: new Date(now) } })+}++/** One model on one kind of job over the period and projects read, with the rates routing and the report use. `recent`: its+ * last ten first reviews in those projects, oldest first, whatever the period. */+export interface ModelKindEvidence extends Counts {+ engine: string; model: string; kind: JobKind+ /** Null with no first review. */+ firstReviewPassRate: number | null+ /** Minutes from the shipping attempt's start to its ship, averaged; null with nothing shipped. */+ averageMinutesToShip: number | null+ /** API-equivalent cost of every attempt over what shipped; null with nothing shipped or any ended attempt's cost unknown,+ * as a partial sum would read cheaper than it was. */+ costPerShipped: number | null+ recent: boolean[]+}+export interface EvidenceRead {+ models: ModelKindEvidence[]+ /** The weekly rows the totals come from, oldest first, for the weekly report. */+ weeks: Array<EvidenceKey & Counts>+ /** More weekly rows than MAX_WEEK_ROWS: the oldest were left out. */+ truncated: boolean+}++/** A Swarm's evidence from the week holding [since], by its tabId+week index: the whole Swarm's, or with [projectIds] only+ * those projects' (the caller passes the projects its reader sees). A plain $match: Prisma's own filters reach Mongo as+ * $expr, which its planner does not serve from the index (costs/read.ts). */+export async function readEvidence(tx: Tx, tabId: string, since: number, projectIds?: string[]): Promise<EvidenceRead> {+ if (projectIds && !projectIds.length) return { models: [], weeks: [], truncated: false }+ const projects = projectIds ? { projectId: { $in: projectIds } } : {}+ const found = await tx.superTabModelEvidence.aggregateRaw({ pipeline: [+ { $match: { tabId, week: { $gte: { $date: new Date(weekStart(since)).toISOString() } }, ...projects } },+ { $sort: { week: -1 } }, { $limit: MAX_WEEK_ROWS + 1 },+ { $project: { _id: 0, tabId: 0, updatedAt: 0 } },+ ] }) as unknown as Array<Record<string, unknown>>+ const recent = await tx.superTabModelRecent.aggregateRaw({ pipeline: [{ $match: { tabId, ...projects } },+ { $project: { engine: 1, model: 1, kind: 1, results: 1 } }] }) as unknown as Array<ModelKey & { results: RecentResult[] }>+ const weeks = found.slice(0, MAX_WEEK_ROWS).map(row => ({ projectId: String(row.projectId), engine: String(row.engine), model: String(row.model), kind: row.kind as JobKind,+ week: ms(row.week), ...Object.fromEntries(COUNTS.map(k => [k, Number(row[k] ?? 0)])) as unknown as Counts })).reverse()+ const totals = new Map<string, ModelKindEvidence>()+ for (const row of weeks) {+ const id = JSON.stringify([row.engine, row.model, row.kind])+ const total = totals.get(id) ?? { engine: row.engine, model: row.model, kind: row.kind, ...Object.fromEntries(COUNTS.map(k => [k, 0])) as unknown as Counts,+ firstReviewPassRate: null, averageMinutesToShip: null, costPerShipped: null, recent: [] }+ for (const k of COUNTS) total[k] += row[k]+ totals.set(id, total)+ }+ const models = [...totals.values()].sort((a, b) => a.engine.localeCompare(b.engine) || a.model.localeCompare(b.model) || a.kind.localeCompare(b.kind))+ for (const m of models) {+ m.firstReviewPassRate = m.firstReviews ? m.firstReviewPassed / m.firstReviews : null+ m.averageMinutesToShip = m.minutesToShipCount ? m.minutesToShipSum / m.minutesToShipCount : null+ m.costPerShipped = m.shipped && !m.costUnknown ? m.apiCost / m.shipped : null+ // Each project's row keeps its own last ten, so the last ten of all of them are among those.+ m.recent = recent.filter(r => sameModel(r, m)).flatMap(r => r.results).sort((x, y) => x.at - y.at).slice(-RECENT_RESULTS).map(r => r.passed)+ }+ return { models, weeks, truncated: found.length > MAX_WEEK_ROWS }+}+diff --git a/backend/src/superTabs/leaderboard/record.test.ts b/backend/src/superTabs/leaderboard/record.test.tsindex ed4fad5be..50e70f30a 100644--- a/backend/src/superTabs/leaderboard/record.test.ts+++ b/backend/src/superTabs/leaderboard/record.test.ts@@ -226,6 +226,82 @@ describe('when the Lead records a merge', () => {expect(f.group(id).pullRequestUrls).toBeUndefined()})+ // Evidence routing (Ken, 2026-10-29): a merged PR whose code a follow-up fix PR changes within 14 days, the follow-up linking it.+ describe('a fix after merge', () => {+ const FIX = 'https://github.com/o/r/pull/43', REFUSED = 'No merged pull request in this project matches that link within the last 14 days.'+ const fixes = (conversationId: string, extra: Record<string, unknown> = {}) =>+ commandSchema.parse({ type: 'conversation.merged', conversationId, pullRequestUrl: FIX, fixes: PR, ...extra })+ /** The original merged at NOW, and a follow-up group for its fix. */+ const original = () => {+ const s = setup()+ s.f.run(merged(s.id), s.lead)+ const fix = s.f.create(s.lead)+ return { ...s, fix }+ }++ it('marks the original merged request as fixed after merge, once, at the fix\'s merge', () => {+ const { f, lead, id, fix } = original()+ f.at(NOW + 3 * DAY_MS)+ const effects = f.run(fixes(fix), lead)+ expect(f.group(id).ledger?.fixedAfterMergeAt).toBe(NOW + 3 * DAY_MS)+ expect(f.group(fix).ledger).toMatchObject({ shippedAt: NOW + 3 * DAY_MS, fixOf: id })+ expect(f.group(fix).pullRequestUrls).toEqual([FIX])+ expect(effects.messages.map(m => m.text)).toEqual([`Merged ${FIX}, a fix of ${PR}`])+ // The line is the fix's card (cards.ts: a main-chat line's links become cards, the original's too).+ expect(f.group(fix).cards?.pullRequests?.[0]).toMatchObject({ url: FIX, messageId: effects.messages[0]!.id, mergedAt: NOW + 3 * DAY_MS })+ // Recorded again, or by a second fix later: the first fix stays the one counted.+ f.at(NOW + 5 * DAY_MS)+ f.run(fixes(fix), lead)+ const second = f.create(lead)+ f.run(fixes(second, { pullRequestUrl: 'https://github.com/o/r/pull/44' }), lead)+ expect(f.group(id).ledger?.fixedAfterMergeAt).toBe(NOW + 3 * DAY_MS)+ })++ it('takes a backfilled fix merge time, and refuses one over 14 days after the original merge or before it', () => {+ const { f, lead, id, fix } = original()+ f.at(NOW + 20 * DAY_MS)+ expect(() => f.run(fixes(fix), lead)).toThrow(REFUSED)+ expect(() => f.run(fixes(fix, { mergedAt: new Date(NOW - 60_000).toISOString() }), lead)).toThrow(REFUSED)+ f.run(fixes(fix, { mergedAt: new Date(NOW + 14 * DAY_MS).toISOString() }), lead)+ expect(f.group(id).ledger?.fixedAfterMergeAt).toBe(NOW + 14 * DAY_MS)+ })++ it('refuses alike a link to no group, an unmerged one, the same group, a review, another project or a private chat, changing nothing', () => {+ const { f, lead, id, fix } = original()+ const refused = (conversationId: string, link: string) => {+ expect(() => f.run(fixes(conversationId, { fixes: link }), lead)).toThrow(REFUSED)+ expect(f.group(id).ledger?.fixedAfterMergeAt).toBeUndefined()+ }+ refused(fix, 'https://github.com/o/r/pull/99')+ const open = f.create(lead)+ f.group(open).pullRequestUrls = ['https://github.com/o/r/pull/50']+ refused(fix, 'https://github.com/o/r/pull/50')+ Object.assign(f.group(open), { reviewOf: id, ledger: { mergedAt: NOW, shippedAt: NOW } })+ refused(fix, 'https://github.com/o/r/pull/50')+ refused(id, PR)+ const other = f.run({ type: 'project.create', name: 'Web', visibility: 'public', brief: '' }).result as { projectId: string }+ const elsewhere = f.run(commandSchema.parse({ type: 'conversation.create', projectId: other.projectId, title: 'Other', brief: 'x', checks })).result.conversationId as string+ f.run(merged(elsewhere, { pullRequestUrl: 'https://github.com/o/r/pull/60' }))+ refused(fix, 'https://github.com/o/r/pull/60')+ const chat = f.buddyChat()+ Object.assign(f.group(chat), { pullRequestUrls: ['https://github.com/o/r/pull/70'], ledger: { mergedAt: NOW, shippedAt: NOW } })+ refused(fix, 'https://github.com/o/r/pull/70')+ expect(f.group(fix).ledger?.shippedAt).toBeUndefined()+ expect(f.group(fix).pullRequestUrls).toBeUndefined()+ })++ it('keeps the fix record to the Lead and owners, as the merge record', () => {+ const { f, fix } = original()+ f.invitePeer()+ expect(() => f.run(fixes(fix), peer)).toThrow('Lead or an owner')+ })++ it('takes only a GitHub pull request link as the original', () => {+ expect(() => fixes('g', { fixes: 'https://example.com/o/r/pull/1' })).toThrow()+ expect(() => fixes('g')).not.toThrow()+ })+ })+it('takes the record from the Swarm and project owner', () => {const { f, id } = setup()f.run(merged(id), owner)@@ -599,6 +675,41 @@ describe('the model behind each assignment, and its first review (roadmap, Dec:expect(g.group(both).ledger!.runs![0]).toMatchObject({ firstReview: true })})+ // Evidence routing (Ken, 2026-10-29): a rework round is a re-review after a failed review in the same attempt.+ it('counts each re-review after a failed verdict as a rework round of the attempt, a review of several checks once', () => {+ const two = [{ description: 'Code review', independent: true }, { description: 'Security review', independent: true }, { description: 'Builder', independent: false }]+ const f = fixture()+ const id = f.create(owner, { checks: two })+ const { assignmentId } = f.assign(id)+ const [code, security, own] = f.group(id).checks+ const run = () => f.group(id).ledger!.runs![0]!+ const check = (checkId: string, passed: boolean) => f.run({ type: 'work.check', conversationId: id, assignmentId, checkId, passed, evidence: 'rev abc' })+ check(code!.id, true)+ check(own!.id, false)+ check(own!.id, true)+ expect(run().reworkRounds).toBeUndefined()+ // Both reviews fail, then both pass: one round, not two.+ check(code!.id, false)+ check(security!.id, false)+ expect(run().reworkRounds).toBe(0)+ check(code!.id, true)+ check(security!.id, true)+ expect(run().reworkRounds).toBe(1)+ // A verdict after a pass is not a re-review of a failure.+ check(code!.id, true)+ expect(run().reworkRounds).toBe(1)+ check(security!.id, false)+ check(security!.id, false)+ check(security!.id, true)+ expect(run().reworkRounds).toBe(3)+ // A new attempt starts from none.+ f.run({ type: 'work.cancel', conversationId: id, assignmentId, reason: 'Again.' })+ const second = f.assign(id)+ f.run({ type: 'work.check', conversationId: id, assignmentId: second.assignmentId, checkId: code!.id, passed: true, evidence: 'rev def' })+ expect(f.group(id).ledger!.runs![1]).toMatchObject({ assignmentId: second.assignmentId })+ expect(f.group(id).ledger!.runs![1]!.reworkRounds).toBeUndefined()+ })+it('records each finished review verdict an agent gives, with the model it ran on, for the reviewer models\' points', () => {const f = fixture()f.at(7_000)diff --git a/backend/src/superTabs/leaderboard/record.ts b/backend/src/superTabs/leaderboard/record.tsindex ebdca0c24..8d7c1b3a2 100644--- a/backend/src/superTabs/leaderboard/record.ts+++ b/backend/src/superTabs/leaderboard/record.ts@@ -22,7 +22,12 @@ export interface Run extends RanOn { assignmentId: string; at: numberstepUp?: { attempt: number; reason: string }/** Its agent was launched on the engine's own model, which Codex reports by a slug the policy may not name: it is rated by* the engine's `default` row (rules.ts policyQuality; review of ee4ee6c9a). */- engineDefault?: true }+ engineDefault?: true+ /** Re-reviews after a failed review during this attempt (evidence routing, Ken 2026-10-29): the most on any one independent+ * check, so a review that judges two checks counts once. Absent until a review fails; 0 while a failure waits for its+ * re-review. `reworks`: each check's last verdict and its re-reviews after a failure, by check id. */+ reworkRounds?: number+ reworks?: Record<string, { last: boolean; rounds: number }> }/** What an agent ran on: its engine, the model (a grid model's own name, `grid` set), and its effort when it names one;* absent from attempts recorded before efforts were (Lead, 2026-10-29: never guessed afterwards). */export interface RanOn { engine: string; model: string | null; effort?: string; grid?: true }@@ -38,6 +43,11 @@ export interface GroupLedger {shippedAt?: number/** The earliest merge the Lead recorded (recordMerged); once there is one, it is the ship time. */mergedAt?: number+ /** When the first follow-up fix of its merged PR merged, within FIX_WINDOW_MS of its merge (recordFix): it needed a fix+ * after merge (evidence routing, Ken 2026-10-29). */+ fixedAfterMergeAt?: number+ /** The group whose merged PR this group's merge fixed. */+ fixOf?: string/** The item waiting on a person: the attempt, since when, the "Needs a human" row it posted, the decision it asked with it* (the same one again when the worker repeats an open question), and once a person answered it, when. An answered item no* longer waits, though its worker has not moved on yet. A wait recorded before decisions were named has none. */@@ -102,7 +112,7 @@ function shipOn(group: Conversation, run?: Run): void {function shipAttempt(ledger: GroupLedger, run?: Run): void {const shipping = run ?? ledger.runs?.filter(r => r.at <= ledger.shippedAt!).at(-1) ?? ledger.runs?.[0]if (!shipping) return- const { firstVerdicts: _verdicts, firstReview: _review, ...shippedBy } = shipping+ const { firstVerdicts: _verdicts, firstReview: _review, reworkRounds: _rounds, reworks: _reworks, ...shippedBy } = shippingledger.shippedBy = shippedBy}@@ -122,6 +132,29 @@ export function recordMerged(group: Conversation, mergedAt: number): void {else shipOn(group)}+/** How long after a merge a follow-up fix still counts against it (evidence routing spec, PM call 10). */+export const FIX_WINDOW_MS = 14 * 86_400_000++/** The merged group a fix PR merged at [mergedAt] fixes: a shared group of the same project, not [fix] itself nor a review,+ * that links [url] and merged at most FIX_WINDOW_MS before. Undefined for anything else, which its caller refuses alike, so+ * a link names nothing outside the project. */+export function fixedOriginal(state: SuperTabState, fix: Conversation, url: string, mergedAt: number): Conversation | undefined {+ const project = groupProject(state, fix).id+ return state.conversations.find(g => g.id !== fix.id && !g.reviewOf && !g.audience && !isLeads(g) && g.pullRequestUrls?.includes(url)+ && g.ledger?.mergedAt !== undefined && mergedAt >= g.ledger.mergedAt && mergedAt - g.ledger.mergedAt <= FIX_WINDOW_MS+ && groupProject(state, g).id === project)+}++/** Records that [fix]'s merge at [mergedAt] fixed [original]'s merged PR. Only the first fix counts against it; true when this+ * one is that first. */+export function recordFix(original: Conversation, fix: Conversation, mergedAt: number): boolean {+ const ledger = original.ledger!+ ;(fix.ledger ??= {}).fixOf = original.id+ if (ledger.fixedAfterMergeAt !== undefined && ledger.fixedAfterMergeAt <= mergedAt) return false+ ledger.fixedAfterMergeAt = mergedAt+ return true+}+/** The person a waiting item waits on: its requester while still a member, otherwise the project's owner. */export function waitedOn(state: SuperTabState, group: Conversation): string {const requester = group.requesterId && state.people.some(p => p.id === group.requesterId) ? group.requesterId : undefined@@ -263,7 +296,17 @@ export function recordReview(group: Conversation, check: Check, passed: boolean)if (!check.independent || !run) returnconst verdicts = run.firstVerdicts ??= {}verdicts[check.id] ??= passed+ recordRework(run, check.id, passed)const firsts = group.checks.filter(c => c.independent).map(c => verdicts[c.id])if (firsts.includes(false)) run.firstReview = falseelse if (firsts.every(v => v === true)) run.firstReview = true}++/** A verdict on a check whose last verdict in this attempt failed is a rework round. */+function recordRework(run: Run, checkId: string, passed: boolean): void {+ const trail = run.reworks?.[checkId]+ if (!trail && passed) return+ const reworks = run.reworks ??= {}+ reworks[checkId] = { last: passed, rounds: (trail?.rounds ?? 0) + (trail && !trail.last ? 1 : 0) }+ run.reworkRounds = Math.max(...Object.values(reworks).map(r => r.rounds))+}diff --git a/backend/src/superTabs/liveness.test.ts b/backend/src/superTabs/liveness.test.tsindex 93c11e903..fff3ae978 100644--- a/backend/src/superTabs/liveness.test.ts+++ b/backend/src/superTabs/liveness.test.ts@@ -43,6 +43,62 @@ describe('the lease on a worker\'s task', () => {})})+describe('a task waiting for review', () => {+ // 2026-10-29: five Engineers who had pushed and handed over lost their tasks after 30 quiet minutes waiting for a Reviewer.+ const handedOver = 1_000_000+ const quiet = (status: 'review' | 'working', minutes: number) => status === 'review'+ ? swarm(assignment({ status, result: 'Ready for review: abc123', leaseUntil: handedOver + LEASE_MS, progressAt: handedOver }),+ { receivedAt: handedOver + minutes * MINUTE, harnessProgress: { h: handedOver } })+ : swarm(assignment({ status, leaseUntil: handedOver + LEASE_MS, progressAt: handedOver }),+ { receivedAt: handedOver + minutes * MINUTE, harnessProgress: { h: handedOver } })++ it('stays with its Engineer through 45 quiet minutes, while working work is still lost after 30', () => {+ expect(status(quiet('review', 45), handedOver + 45 * MINUTE)).toMatchObject({ status: 'review', result: 'Ready for review: abc123' })+ expect(status(quiet('working', 30), handedOver + 30 * MINUTE).status).toBe('working')+ expect(status(quiet('working', 30), handedOver + 30 * MINUTE + 1)).toMatchObject({ status: 'lost', lost: { reason: 'no progress for 30 minutes' } })+ })++ // Engineers stay working with a "Ready for review" result, since done is refused until the review passes (Lead, 2026-10-29).+ const working = (result: string, patch: Partial<Assignment> = {}) => status(swarm(assignment({ result, leaseUntil: handedOver + LEASE_MS,+ progressAt: handedOver, ...patch }), { receivedAt: handedOver + 45 * MINUTE, harnessProgress: { h: handedOver } }), handedOver + 45 * MINUTE)++ it('stays with its Engineer through 45 quiet minutes while working with a ready-for-review hand-off naming a revision', () => {+ expect(working('Ready for review: https://github.com/example/project/pull/2180 at 4f9c2e1').status).toBe('working')+ expect(working('ready for review — PR #2180, head 4f9c2e1d8a').status).toBe('working')+ })++ // A short hash can be all digits or all letters (review of #2176): after '@', 'at ' or 'head ' any 7-40 hex counts.+ it('takes an all-digit or all-letter revision named right after @, at or head', () => {+ for (const revision of ['1234567', 'abcdefa']) {+ expect(working(`Ready for review: PR #2180 @${revision}`).status).toBe('working')+ expect(working(`Ready for review: PR #2180 at ${revision}`).status).toBe('working')+ expect(working(`Ready for review — PR #2180, head ${revision}`).status).toBe('working')+ expect(working(`Ready for review: PR #2180 HEAD ${revision}`).status).toBe('working')+ }+ })++ it('does not take an all-digit or all-letter run anywhere else as a revision', () => {+ expect(working('Ready for review on 20261029, PR #2180').status).toBe('lost')+ expect(working('Ready for review: 1234567').status).toBe('lost')+ expect(working('Ready for review: abcdefa').status).toBe('lost')+ expect(working('Ready for review: PR #2180 at 12345678901234567890123456789012345678901').status).toBe('lost')+ expect(working('Ready for review: chat 12:00 at 1234567x').status).toBe('lost')+ })++ it('counts quiet time for a hand-off without a revision, any other result, or one a review has since found problems in', () => {+ expect(working('Ready for review soon, running the suite').status).toBe('lost')+ expect(working('Fixed 4f9c2e1; running the suite').status).toBe('lost')+ expect(working('Ready for review: 4f9c2e1', { reviewFoundAt: handedOver }).status).toBe('lost')+ })++ it('is still lost at once when its session stops or its machine goes offline', () => {+ const stopped = quiet('review', 1)+ stopped.machines![0]!.observation!.stoppedHarnessIds = ['h']+ expect(status(stopped, handedOver + MINUTE)).toMatchObject({ status: 'lost', lost: { reason: 'its session on Mac stopped' } })+ expect(status(quiet('review', 1), handedOver + 4 * MINUTE)).toMatchObject({ status: 'lost', lost: { reason: 'its machine Mac has been offline for 2 minutes' } })+ })+})+describe('a worker whose task is lost', () => {it('is marked lost in the same write that loses its task, so routing keeps it out after a cancel or reassignment', () => {const state = swarm(assignment({ leaseUntil: 1 })), now = 1 + LEASE_MS + 1diff --git a/backend/src/superTabs/liveness.ts b/backend/src/superTabs/liveness.tsindex 67fc24c21..350fc5c2d 100644--- a/backend/src/superTabs/liveness.ts+++ b/backend/src/superTabs/liveness.ts@@ -61,6 +61,37 @@ export function renewLease(assignment: Assignment, now: number): void {assignment.progressAt = now}+/** A hand-off: a result that says it is ready for review and names a revision (a commit hash). Right after '@', 'at ' or+ * 'head ', the forms hand-offs use, any 7-40 hex digits count, since a short hash can be all digits or all letters;+ * anywhere else it needs a digit and a letter, so dates and other numbers do not count (review of #2176). */+const READY_FOR_REVIEW = /\bready for review\b/i+const REVISION = /(?:@|\b(?:at|head)\s+)[0-9a-f]{7,40}\b|\b(?=[0-9a-f]*\d)(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}\b/i++/** Work that waits for its review, whose quiet time therefore does not count (2026-10-29: five Engineers who had handed+ * over lost their tasks waiting for a Reviewer). In review, or working with a hand-off as its latest result, as Engineers+ * report while done is refused until the review passes, until a review finds problems in it. */+export function waitingForReview(assignment: Assignment): boolean {+ if (assignment.status === 'review') return true+ return assignment.status === 'working' && assignment.reviewFoundAt === undefined && !!assignment.result+ && READY_FOR_REVIEW.test(assignment.result) && REVISION.test(assignment.result)+}++/** Work that stopped waiting for its review counts its quiet time from now: its agent keeps it QUIET_RUNNING_MS without+ * progress, as after its last screen change, though its screen stayed still while it waited. */+export function restartQuietTime(assignment: Assignment, now: number): void {+ assignment.progressAt = now+ assignment.leaseUntil = Math.max(assignment.leaseUntil ?? 0, now + QUIET_RUNNING_MS)+}++/** A review found problems in work waiting for it: the work is its Engineer's to fix again, and its quiet time counts. */+export function reviewFoundProblems(assignment: Assignment, now: number): boolean {+ if (!waitingForReview(assignment)) return false+ assignment.status = 'working'+ assignment.reviewFoundAt = now+ restartQuietTime(assignment, now)+ return true+}+/** The active assignments held by workers, not by a Lead, and not already being reconciled after their agent left. */function workerTasks(state: SuperTabState): Array<{ group: Conversation; assignment: Assignment; worker: Agent }> {return state.conversations.filter(activeWork).flatMap(group => {@@ -120,6 +151,7 @@ function lostReason(state: SuperTabState, group: Conversation, worker: Agent, as// Its host alerts only after ten minutes of retries without an answer (cli superTabs/terminal.ts MODEL_WAIT_MS), so a// short burst of failures that recovers never gets here.if (worker.alerting?.includes('model')) return 'its model keeps failing'+ if (waitingForReview(assignment)) return nullconst end = leaseEnd(group, assignment, reportRenewedAt(state, worker))if (end !== undefined && now > end) {const progress = lastProgress(state, worker, assignment)diff --git a/backend/src/superTabs/mentions.ts b/backend/src/superTabs/mentions.tsindex 43f238326..f45feff0a 100644--- a/backend/src/superTabs/mentions.ts+++ b/backend/src/superTabs/mentions.ts@@ -107,7 +107,17 @@ export async function mentionsWaiting(tx: Tx, tabId: string, state: SuperTabStatexport async function waitingMentions(tx: Tx, tabId: string, state: SuperTabState, actor: Extract<Actor, { kind: 'person' }>,now: number): Promise<{ count: number; digest: string }> {const ids = (await readable(tx, tabId, state, actor, now, true)).map(({ row }) => row.id).sort()- return { count: ids.length, digest: createHash('sha256').update(ids.join('\n')).digest('base64url').slice(0, 16) }+ return { count: ids.length, digest: mentionsDigest(ids) }+}++/** Which of these Swarms hold a waiting tag for the person, by one plain match (the index on tabId, personId, createdAt+ * bounds it; Prisma would send `in` as an $expr that no index can). Raw, so a Swarm list counts a page of Swarms at once. */+export const swarmsWithTags = (tabIds: string[], personId: string, now: number) => [{ $match: { tabId: { $in: tabIds }, personId, resolvedAt: null,+ createdAt: { $gt: { $date: new Date(now - MENTION_EXPIRY_MS).toISOString() } } } }, { $group: { _id: '$tabId' } }]++/** The digest of a sorted list of waiting tag ids; a Swarm with none has this one. */+export function mentionsDigest(ids: string[]): string {+ return createHash('sha256').update(ids.join('\n')).digest('base64url').slice(0, 16)}export async function listMentions(tx: Tx, tabId: string, state: SuperTabState, actor: Extract<Actor, { kind: 'person' }>, now: number, open: boolean) {diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex 07ec0d861..d9ea7c38b 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -166,6 +166,9 @@ export interface Assignment {progressAt?: number/** While it needs a human: the person its agent asked (work.status with ask), whom its wait names (liveness.ts). */askedOf?: string+ /** When a review last found problems in its hand-off: the hand-off no longer pauses its quiet time (liveness.ts+ * waitingForReview). Its next status clears it. */+ reviewFoundAt?: number/** Why and when it was lost (status `lost`); after a usage limit whose screen gave a reset time, when its own agent may* take it back (work.resume) unless it was handed on first. */lost?: { reason: string; at: number; resumeAt?: string }diff --git a/backend/src/superTabs/pageReads.ts b/backend/src/superTabs/pageReads.tsindex d86569e2c..e16fba92e 100644--- a/backend/src/superTabs/pageReads.ts+++ b/backend/src/superTabs/pageReads.ts@@ -1,7 +1,9 @@-import type { Prisma, SuperTabDelivery } from '@prisma/client'+import type { Prisma, SuperTabDelivery, SuperTabMessage } from '@prisma/client'import { ms } from './parts/light.js'import type { ReactionRow } from './reactions.js'import { agentOnly, stableId, type Author } from './model.js'+import { readBy } from './parts/indexed.js'+import { prismaRow } from './rawRows.js'type Transaction = Prisma.TransactionClient@@ -30,6 +32,18 @@ export async function pageDeliveries(tx: Transaction, tabId: string, messageIds:deliveredAt: date(row.deliveredAt), answeredAt: date(row.answeredAt), createdAt: date(row.createdAt)!, updatedAt: date(row.updatedAt)! }))}+/** The deliveries a host is still told about (the rest are answered, cancelled or confirmed). */+export const OPEN_DELIVERY = ['queued', 'claimed', 'uncertain'] as const++/** An agent's open deliveries, oldest first and each conversation's tied rows in its order: one indexed read, and the tied+ * messages' sequences only when there are ties. */+export async function agentOpenDeliveries(tx: Transaction, tabId: string, agentId: string): Promise<SuperTabDelivery[]> {+ // By the agent index (parts/indexed.ts): Prisma sent `status: { in }` as an $expr $or, planned as one scan per status.+ const rows = await readBy(tx, 'SuperTabDelivery', 'agentOpen', [{ $match: { tabId, agentId, status: { $in: [...OPEN_DELIVERY] } } },+ { $sort: { createdAt: 1 } }, { $limit: 100 }])+ return inConversationOrder(tx, tabId, rows.map(row => prismaRow<SuperTabDelivery>('SuperTabDelivery', row)))+}+/** An agent's open deliveries, read by creation time, with each conversation's tied rows put in its message order. One* write's deliveries share a creation time, and Mongo breaks that tie by insertion order alone. Each conversation keeps its* places among the others; only tied rows have their messages' sequences read. */@@ -57,6 +71,28 @@ export async function inConversationOrder<T extends Pick<SuperTabDelivery, 'convreturn ordered}+/** Where a page of messages starts: past this sequence, and within it past this id when one is given. */+export interface MessageEdge { sequence: number; id?: string }++/**+ * Up to `limit` messages of one conversation past `edge` (from the newest or oldest without one), in (sequence, id) order+ * forward or backward. A cursor inside a sequence is two reads its index bounds: the rest of that sequence by id, then the+ * sequences past it. As one `$or`, the planner could not bound it: reading on from inside a sequence walked the whole+ * conversation before it (roadmap Phase 3.5; integration/superTabNamedReads.test.ts).+ */+export async function messagesPast(tx: Transaction, at: { tabId: string; conversationId: string; messageId?: string; thread?: string },+ edge: MessageEdge | undefined, forward: boolean, limit: number): Promise<SuperTabMessage[]> {+ const [op, dir] = forward ? ['$gt', 1] as const : ['$lt', -1] as const+ const index = at.messageId ? 'id' : at.thread ? 'thread' : 'sequence'+ const read = async (sequence: unknown, after: string | undefined, take: number) => take <= 0 ? [] : (await readBy(tx, 'SuperTabMessage', index, [+ { $match: { tabId: at.tabId, conversationId: at.conversationId, ...at.thread ? { thread: at.thread } : {},+ ...at.messageId || after !== undefined ? { _id: { ...at.messageId ? { $eq: at.messageId } : {}, ...after !== undefined ? { [op]: after } : {} } } : {},+ ...sequence !== undefined ? { sequence } : {} } },+ { $sort: { sequence: dir, _id: dir } }, { $limit: take }])).map(row => prismaRow<SuperTabMessage>('SuperTabMessage', row))+ const same = edge?.id !== undefined ? await read(edge.sequence, edge.id, limit) : []+ return [...same, ...await read(edge ? { [op]: edge.sequence } : undefined, undefined, limit - same.length)]+}+/** The Lead's notices that leave a copy in a task's chat when the Lead hears them in its own chat (terminal.ts toLead). */const LEAD_COPY_KINDS = new Set<unknown>(['work-lost', 'work-resumed'])diff --git a/backend/src/superTabs/parts/indexed.ts b/backend/src/superTabs/parts/indexed.tsindex 441a99e5c..d04bdcfd2 100644--- a/backend/src/superTabs/parts/indexed.ts+++ b/backend/src/superTabs/parts/indexed.ts@@ -26,27 +26,73 @@ export const GROUP_INDEX = {} as constexport type GroupIndex = keyof typeof GROUP_INDEX-/** The indexes SwarmGroup had when last listed; none until then. A read names only these: naming one the database lacks- * fails the read, and in a transaction aborts it. */-let present = new Set<GroupIndex>()+/** Every index a hot read names, by collection, as prisma/schema.prisma declares them (roadmap Phase 3). */+export const NAMED_INDEX = {+ SwarmGroup: GROUP_INDEX,+ SuperTab: {+ /** An owner's Swarms in id order: the grid poll. */+ owner: { autonomousEnv: 1, ownerId: 1, _id: 1 },+ /** A member's Swarms in id order: Swarm lists and Workspace removals. */+ members: { autonomousEnv: 1, memberIds: 1, _id: 1 },+ },+ /** Each part kind's changes since a cursor; machines also by when they were last read. */+ SwarmHead: { changes: { tabId: 1, changedAt: 1 } },+ SwarmMember: { changes: { tabId: 1, changedAt: 1 } },+ SwarmAgent: { changes: { tabId: 1, changedAt: 1 } },+ SwarmMachine: { changes: { tabId: 1, changedAt: 1 }, read: { tabId: 1, readAt: 1 } },+ SwarmStart: { changes: { tabId: 1, changedAt: 1 } },+ SwarmProgress: { changes: { tabId: 1, changedAt: 1 } },+ SuperTabMessage: {+ /** A conversation's page in (sequence, id) order. */+ sequence: { tabId: 1, conversationId: 1, sequence: 1, _id: 1 },+ /** One thread's page. */+ thread: { tabId: 1, conversationId: 1, thread: 1, sequence: 1 },+ /** One message. */+ id: { _id: 1 },+ },+ SuperTabDelivery: {+ /** An agent's deliveries by status and age: its open ones, oldest first. */+ agentOpen: { tabId: 1, agentId: 1, status: 1, createdAt: 1 },+ },+} as const+export type NamedCollection = keyof typeof NAMED_INDEX+export type NamedIndex<C extends NamedCollection> = keyof typeof NAMED_INDEX[C] & string++/** The named indexes each collection had when last listed; none until then. A read names only these: naming one the+ * database lacks fails the read, and in a transaction aborts it. */+let present = new Map<NamedCollection, Set<string>>()-/** Lists SwarmGroup's indexes, outside any transaction, and says which hot reads go without theirs. The worker's+const COLLECTIONS = Object.keys(NAMED_INDEX) as NamedCollection[]+const indexOf = (collection: NamedCollection, name: string) => (NAMED_INDEX[collection] as Record<string, Record<string, number>>)[name]!++/** Lists the named collections' indexes, outside any transaction, and says which hot reads go without theirs. The worker's* `prisma db push` builds a new index at startup (Dockerfile.k8s), possibly after a server first lists them. */-export async function listGroupIndexes(db: PrismaClient): Promise<void> {+export async function listNamedIndexes(db: PrismaClient): Promise<void> {const generation = drops- const reply = await db.$runCommandRaw({ listIndexes: 'SwarmGroup' }) as unknown as { cursor: { firstBatch: Array<{ key: Record<string, unknown> }> } }+ const listed = await Promise.all(COLLECTIONS.map(async collection => {+ const reply = await db.$runCommandRaw({ listIndexes: collection }).catch(error => {+ // A collection nothing has written yet has no indexes either.+ if (/NamespaceNotFound|ns does not exist/i.test(error instanceof Error ? error.message : String(error))) return null+ throw error+ }) as unknown as { cursor: { firstBatch: Array<{ key: Record<string, unknown> }> } } | null+ return [collection, new Set((reply?.cursor.firstBatch ?? []).map(index => Object.keys(index.key).join(',')))] as const+ }))// A read dropped the listing while this one was on its way: its reply may predate the removal (review of #1994).if (drops !== generation) return- const fields = new Set(reply.cursor.firstBatch.map(index => Object.keys(index.key).join(',')))- const names = Object.keys(GROUP_INDEX) as GroupIndex[]- present = new Set(names.filter(name => fields.has(Object.keys(GROUP_INDEX[name]).join(','))))- const missing = names.filter(name => !present.has(name))- if (missing.length) logger.error('[swarm-reads] SwarmGroup lacks indexes hot reads name; they read without them', { missing: missing.map(name => GROUP_INDEX[name]) })+ present = new Map(listed.map(([collection, fields]) => {+ const names = Object.keys(NAMED_INDEX[collection])+ const found = new Set(names.filter(name => fields.has(Object.keys(indexOf(collection, name)).join(','))))+ const missing = names.filter(name => !found.has(name))+ if (missing.length) logger.error(`[swarm-reads] ${collection} lacks indexes hot reads name; they read without them`, { missing: missing.map(name => indexOf(collection, name)) })+ return [collection, found] as const+ }))}+/** The SwarmGroup listing's older name: it lists every named collection now. */+export const listGroupIndexes = listNamedIndexes/** Lists the indexes now and every five minutes, until the process ends. */export function watchGroupIndexes(db: PrismaClient): void {- const list = () => listGroupIndexes(db).catch(error => logger.warn('[swarm-reads] listing SwarmGroup indexes failed', { error: error instanceof Error ? error.message : String(error) }))+ const list = () => listNamedIndexes(db).catch(error => logger.warn('[swarm-reads] listing Swarm indexes failed', { error: error instanceof Error ? error.message : String(error) }))void list()setInterval(list, 5 * 60_000).unref()}@@ -73,28 +119,35 @@ export async function retryStaleIndex<T>(run: () => Promise<T>): Promise<T> {}/**- * The rows of an `aggregateRaw` pipeline on SwarmGroup, through `index` once the database is known to have it. An index- * removed since the last listing (a rollback, an index replaced) fails the read: the listing is dropped, said, and the read- * runs without it at once outside a transaction. In one, the failed command aborted it, and Prisma may report only that:- * its runner runs it again (`listingDrops`).+ * The rows of an `aggregateRaw` pipeline on `collection`, through its index `name` once the database is known to have it.+ * An index removed since the last listing (a rollback, an index replaced) fails the read: the listing is dropped, said, and+ * the read runs without it at once outside a transaction. In one, the failed command aborted it, and Prisma may report only+ * that: its runner runs it again (`listingDrops`).*/-export async function groupsBy(tx: Transaction, index: GroupIndex, pipeline: Prisma.InputJsonValue[]): Promise<Array<Record<string, unknown>>> {- const run = async (hint?: Record<string, number>) => await tx.swarmGroup.aggregateRaw({ pipeline, ...hint ? { options: { hint } } : {} }) as unknown as+export async function readBy<C extends NamedCollection>(tx: Transaction, collection: C, name: NamedIndex<C>,+ pipeline: Prisma.InputJsonValue[]): Promise<Array<Record<string, unknown>>> {+ const model = (tx as unknown as Record<string, { aggregateRaw(args: unknown): Promise<unknown> }>)[collection[0]!.toLowerCase() + collection.slice(1)]!+ const run = async (hint?: Record<string, number>) => await model.aggregateRaw({ pipeline, ...hint ? { options: { hint } } : {} }) asArray<Record<string, unknown>>- if (rerun.getStore() || !present.has(index)) return run()+ if (rerun.getStore() || !present.get(collection)?.has(name)) return run()try {- return await run(GROUP_INDEX[index])+ return await run(indexOf(collection, name))} catch (error) {const message = error instanceof Error ? error.message : String(error)if (!/hint provided does not correspond to an existing index|has been aborted/.test(message)) throw error- present = new Set()+ present = new Map()drops++- logger.error('[swarm-reads] SwarmGroup lacks an index a hot read names; reads name none until the next listing', { index: GROUP_INDEX[index] })+ logger.error('[swarm-reads] A Swarm collection lacks an index a hot read names; reads name none until the next listing',+ { collection, index: indexOf(collection, name) })if (typeof (tx as { $transaction?: unknown }).$transaction === 'function') return run()throw error}}+/** The rows of an `aggregateRaw` pipeline on SwarmGroup through `index` (readBy). */+export const groupsBy = (tx: Transaction, index: GroupIndex, pipeline: Prisma.InputJsonValue[]): Promise<Array<Record<string, unknown>>> =>+ readBy(tx, 'SwarmGroup', index, pipeline)+/** A project's quiet conversations last active since `since`, as the project index serves them. A conversation stored with no* project belongs to the first one (projects.ts groupProject); a null match is a missing field too. */export function quietSince(tabId: string, projectId: string, since: number): Record<string, Prisma.InputJsonValue> {diff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.tsindex 6ee87a8bd..7717c8b8c 100644--- a/backend/src/superTabs/parts/light.test.ts+++ b/backend/src/superTabs/parts/light.test.ts@@ -6,7 +6,7 @@ import { FINISHED, GROUP_FIELDS } from './light.js'* here, and the test below until light.ts either projects it or names it as unread by reads (review of #1745). */const assignment: Required<Assignment> = {id: 'w', agentId: 'a', status: 'working', configuration: { engine: 'codex', model: null, effort: null, contextWindow: null, engineVersion: null },- execution: { machineId: 'm', harnessId: 'h', machineOwnerId: 'o' }, result: null, recordingProgress: { at: 1, revision: 1 }, leaseUntil: 1, progressAt: 1, askedOf: 'p',+ execution: { machineId: 'm', harnessId: 'h', machineOwnerId: 'o' }, result: null, recordingProgress: { at: 1, revision: 1 }, leaseUntil: 1, progressAt: 1, askedOf: 'p', reviewFoundAt: 1,lost: { reason: 'r', at: 1 },}const conversation: Required<Conversation> = {diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.tsindex 94a7ad713..f6e145a56 100644--- a/backend/src/superTabs/parts/light.ts+++ b/backend/src/superTabs/parts/light.ts@@ -28,7 +28,7 @@ export const GROUP_FIELDS = {'assignment.lost'],whenRunning: ['title', 'task.owns', 'assignment.execution', 'assignment.result'],unread: ['number', 'brief', 'reviewOf', 'checks', 'lastMessageSequence', 'lastMainSequence', 'pullRequestUrls', 'cards', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals', 'liveness', 'leadAction', 'stepUp',- 'assignment.configuration', 'assignment.recordingProgress', 'assignment.leaseUntil', 'assignment.progressAt', 'assignment.askedOf'],+ 'assignment.configuration', 'assignment.recordingProgress', 'assignment.leaseUntil', 'assignment.progressAt', 'assignment.askedOf', 'assignment.reviewFoundAt'],} as constconst LIGHT_GROUP = {_id: 0, key: 1, version: 1, changedAt: 1, ordinal: 1, dormant: 1,diff --git a/backend/src/superTabs/parts/load.ts b/backend/src/superTabs/parts/load.tsindex 5add075c9..ccc2fcc74 100644--- a/backend/src/superTabs/parts/load.ts+++ b/backend/src/superTabs/parts/load.ts@@ -5,7 +5,7 @@ import { PART_KINDS } from './types.js'import { noteChange } from '../cache.js'import { stableId } from '../model.js'import { ms } from './light.js'-import { groupsBy, type GroupIndex } from './indexed.js'+import { groupsBy, readBy, type GroupIndex, type NamedCollection } from './indexed.js'type Transaction = Prisma.TransactionClienttype Where = Record<string, unknown>@@ -17,6 +17,10 @@ const toPart = <T>(kind: PartKind, row: PartRow): Part<T> => ({ kind, key: row.k/** A group part as `aggregateRaw` returns it, as the PartRow Prisma would. */const rawGroupRow = (row: Record<string, unknown>): PartRow => ({ ...row, changedAt: new Date(ms(row.changedAt)) }) as unknown as PartRow+/** Any part as `aggregateRaw` returns it: a Float ordinal can come wrapped, and a part stored before `deleted` lacks it. */+const rawPartRow = (row: Record<string, unknown>): PartRow => ({ ...rawGroupRow(row), version: Number(row.version), deleted: !!row.deleted,+ ordinal: typeof row.ordinal === 'number' ? row.ordinal : Number((row.ordinal as { $numberDouble?: string; $numberInt?: string }).$numberDouble+ ?? (row.ordinal as { $numberInt?: string }).$numberInt) }) as PartRow/** The live groups these reads find, each once. */async function liveGroups(tx: Transaction, tabId: string, reads: GroupReads): Promise<PartRow[]> {@@ -130,15 +134,27 @@ export async function insertParts(tx: Transaction, parts: SwarmParts): Promise<vexport async function loadChanged(tx: Transaction, tabIds: string[], since: Date, kinds: readonly PartKind[] = PART_KINDS): Promise<Map<string, Part[]>> {const changed = new Map<string, Part[]>(tabIds.map(id => [id, []]))if (!tabIds.length) return changed+ // Plain matches that name each kind's (tabId, changedAt) index (parts/indexed.ts). Prisma sent `tabId: { in }` as an $expr+ // $or, one planned scan per Swarm, and could pick an index that is not bounded by time at all (roadmap Phase 3.5).+ const after = { $gt: { $date: since.toISOString() } }+ const read = (kind: PartKind) => readBy(tx, COLLECTION[kind], 'changes', [{ $match: { tabId: { $in: tabIds }, changedAt: after } }, { $project: CHANGED_FIELDS }])for (const kind of kinds) {- const after = kind === 'machine' ? { OR: [{ changedAt: { gt: since } }, { readAt: { gt: since } }] } : { changedAt: { gt: since } }- for (const row of await delegate(tx, kind).findMany({ where: { tabId: { in: tabIds }, ...after } })) {- changed.get(row.tabId)!.push({ ...toPart(kind, row), ...row.readAt ? { readAt: row.readAt.getTime() } : {} })+ // A machine read since the cursor counts as changed too: two bounded reads, not one $or the planner cannot bound.+ const rows = kind === 'machine' ? [...new Map([...await read(kind), ...await readBy(tx, 'SwarmMachine', 'read',+ [{ $match: { tabId: { $in: tabIds }, readAt: after } }, { $project: CHANGED_FIELDS }])].map(row => [row._id as string, row])).values()] : await read(kind)+ for (const row of rows) {+ const readAt = row.readAt == null ? null : ms(row.readAt)+ changed.get(row.tabId as string)!.push({ ...toPart(kind, rawPartRow(row)), ...readAt ? { readAt } : {} })}}return changed}+const COLLECTION = { head: 'SwarmHead', member: 'SwarmMember', agent: 'SwarmAgent', group: 'SwarmGroup', machine: 'SwarmMachine', start: 'SwarmStart',+ progress: 'SwarmProgress' } as const satisfies Record<PartKind, NamedCollection>+/** What a changed part is made of: its other fields are indexed copies of its data. */+const CHANGED_FIELDS = { tabId: 1, key: 1, version: 1, changedAt: 1, deleted: 1, ordinal: 1, data: 1, dormant: 1, readAt: 1 }+export const DORMANT_PAGE = 50/** Dormant groups the caller pages through, newest activity first, 50 at a time. A project's go through its index in thatdiff --git a/backend/src/superTabs/rawRows.ts b/backend/src/superTabs/rawRows.tsnew file mode 100644index 000000000..7ed084b07--- /dev/null+++ b/backend/src/superTabs/rawRows.ts@@ -0,0 +1,44 @@+import { Prisma } from '@prisma/client'+import { ms } from './parts/light.js'++// Rows that `aggregateRaw` returns, as Prisma's own reads return them: the id under its field name, dates as Dates, numbers+// as numbers, and a field an older document lacks as null (a list as [], a defaulted value as its default). Named-index reads+// (parts/indexed.ts) hand their callers the same rows a findMany did.++type Field = Prisma.DMMF.Field+const fieldsOf = new Map<string, readonly Field[]>()++function scalarFields(model: Prisma.ModelName): readonly Field[] {+ let fields = fieldsOf.get(model)+ if (!fields) {+ const found = Prisma.dmmf.datamodel.models.find(m => m.name === model)+ if (!found) throw new Error(`No Prisma model ${model}`)+ fields = found.fields.filter(field => field.kind === 'scalar' || field.kind === 'enum')+ fieldsOf.set(model, fields)+ }+ return fields+}++const fallback = (field: Field): unknown => {+ if (field.isList) return []+ const value = field.default+ return value !== undefined && (typeof value !== 'object' || value === null) ? value : null+}++function decode(field: Field, value: unknown): unknown {+ if (value === undefined || value === null) return value === null ? null : fallback(field)+ if (field.isList) return (value as unknown[]).map(item => decode({ ...field, isList: false }, item))+ switch (field.type) {+ case 'DateTime': return new Date(ms(value))+ case 'Int': case 'Float': return typeof value === 'number' ? value : Number((value as { $numberLong?: string; $numberDouble?: string; $numberInt?: string })+ .$numberLong ?? (value as { $numberDouble?: string }).$numberDouble ?? (value as { $numberInt?: string }).$numberInt)+ case 'BigInt': return BigInt((value as { $numberLong?: string }).$numberLong ?? String(value))+ case 'String': return typeof value === 'object' && '$oid' in (value as object) ? (value as { $oid: string }).$oid : value+ default: return value+ }+}++/** One `aggregateRaw` row of `model` as Prisma reads it, with every scalar field. */+export function prismaRow<T>(model: Prisma.ModelName, row: Record<string, unknown>): T {+ return Object.fromEntries(scalarFields(model).map(field => [field.name, decode(field, row[field.dbName ?? field.name])])) as T+}diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.tsindex 86b4b4a7c..d488c139e 100644--- a/backend/src/superTabs/read/contract.ts+++ b/backend/src/superTabs/read/contract.ts@@ -143,10 +143,13 @@ export interface CommandReply {legacyRevision?: number}-/** GET /api/super-tabs/list[?after=] */+/** GET /api/super-tabs/list[?after=][&mentions=1] */export interface SwarmList {/** `workspaceId` names its Workspace (null before the migration); a Swarm whose Workspace the person left is not listed. */- tabs: Array<{ id: string; name: string; ownerId: string; workspaceId: string | null; paused: boolean; lastChangedAt: number | null }>+ tabs: Array<{ id: string; name: string; ownerId: string; workspaceId: string | null; paused: boolean; lastChangedAt: number | null+ /** With `?mentions=1`: the person's waiting tags in the Swarm and their digest, as the Swarm's own state counts them (a+ * Swarm whose count cannot be told here has neither). */+ mentionsWaiting?: number; mentionsDigest?: string }>next: string | null}diff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.tsindex 6dc7dd4e7..acdf678b7 100644--- a/backend/src/superTabs/read/service.ts+++ b/backend/src/superTabs/read/service.ts@@ -6,7 +6,7 @@ import type { PrismaClient } from '@prisma/client'import type { AuthUser } from '../../lib/ssoAuth.js'import { isTeamSession, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../../lib/teamSession.js'import { author, fail, groupWithoutMachines, isLeads, seenMachineIds, visibleState, type Actor, type AgentStart, type SuperTabState } from '../model.js'-import { waitingMentions } from '../mentions.js'+import { mentionsDigest, swarmsWithTags, waitingMentions } from '../mentions.js'import { decisionsWaiting } from '../decisions.js'import { readMarks, writeReadMark } from '../readMarks.js'import type { SuperTabStore } from '../store.js'@@ -30,6 +30,7 @@ import { cursorFor, readCursor } from './cursor.js'import { changesFor } from './changes.js'import { envelope, groupView, readerView, seenIn, type ReaderView } from './views.js'import { decodeDormantPage, encodeDormantPage } from './dormantPage.js'+import { memberSwarms } from '../swarmRows.js'type LoadOptions = NonNullable<Parameters<typeof parts.loadActive>[2]> & Pick<NonNullable<Parameters<typeof parts.loadLight>[2]>, 'groups'>type Loader = (view: CacheView, tabId: string, opts: LoadOptions) => Promise<SwarmParts>@@ -182,10 +183,30 @@ export class SwarmReads {})}- async list(user: AuthUser, after?: string): Promise<SwarmList> {+ /** The waiting tags of each listed Swarm, as `/:tabId/mentions` and a Swarm's own state count them (readable conversations+ * only), so Desktop reads one list instead of one mentions call per Swarm (roadmap 2.5). One match over the page's+ * Swarms (swarmsWithTags) finds those with any tag at all; only those load their state to check what the person may still read. A Swarm+ * whose count cannot be told here is left out, and the client asks it itself. */+ private async mentionCounts(user: AuthUser, tabIds: string[]): Promise<Map<string, { count: number; digest: string }>> {+ const counts = new Map<string, { count: number; digest: string }>()+ if (!tabIds.length) return counts+ const tagged = await this.db.superTabMention.aggregateRaw({ pipeline: swarmsWithTags(tabIds, user.sub, this.now()) }) as unknown as Array<{ _id: string }>+ const withTags = new Set(tagged.map(row => row._id))+ const actor = { kind: 'person', userId: user.sub, email: user.email } as const+ for (const tabId of tabIds) {+ if (!withTags.has(tabId)) { counts.set(tabId, { count: 0, digest: mentionsDigest([]) }); continue }+ try {+ const { state } = await this.store.readLoad(user, tabId)+ await this.store.actor(this.db, user, state)+ counts.set(tabId, await waitingMentions(this.db, tabId, state, actor, this.now()))+ } catch { /* Not countable here: the client reads this Swarm's own mentions. */ }+ }+ return counts+ }++ async list(user: AuthUser, after?: string, withMentions = false): Promise<SwarmList> {if (isTeamSession(user)) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)- const rows = await this.db.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, memberIds: { has: user.sub },- ...(after ? { id: { gt: after } } : {}) }, orderBy: { id: 'asc' }, take: 101, select: { id: true, ownerId: true, format: true, workspaceId: true } })+ const rows = await memberSwarms(this.db, user.autonomousEnv, user.sub, { after, limit: 101 })// A Swarm of a Workspace the person is no longer in is not theirs to list, even before their removal from it has run.const workspaceIds = [...new Set(rows.flatMap(r => r.workspaceId ? [r.workspaceId] : []))]const current = new Set((workspaceIds.length ? await this.db.swarmWorkspaceMember.findMany({ where: { workspaceId: { in: workspaceIds }, userId: user.sub, removedAt: null },@@ -197,9 +218,12 @@ export class SwarmReads {const ids = page.filter(r => r.format === 2).map(r => r.id)// Every head changed after the epoch: one read of each listed Swarm's head part.const [heads, newest] = await transaction(this.db, tx => Promise.all([parts.loadChanged(tx, ids, new Date(0), ['head']), parts.lastChangedAt(tx, ids)]))+ const mentions = withMentions ? await this.mentionCounts(user, page.map(r => r.id)) : undefinedreturn { tabs: page.map(row => {const head = (heads.get(row.id)?.[0]?.data ?? legacy.find(l => l.id === row.id)?.state) as { name: string; paused: boolean }- return { id: row.id, name: head.name, ownerId: row.ownerId, workspaceId: row.workspaceId, paused: head.paused, lastChangedAt: newest.get(row.id) ?? null }+ const tags = mentions?.get(row.id)+ return { id: row.id, name: head.name, ownerId: row.ownerId, workspaceId: row.workspaceId, paused: head.paused, lastChangedAt: newest.get(row.id) ?? null,+ ...tags ? { mentionsWaiting: tags.count, mentionsDigest: tags.digest } : {} }}), next: rows.length > 100 ? rows[99]!.id : null }}diff --git a/backend/src/superTabs/routeDecisions.ts b/backend/src/superTabs/routeDecisions.tsindex e45d220aa..6a3f1606b 100644--- a/backend/src/superTabs/routeDecisions.ts+++ b/backend/src/superTabs/routeDecisions.ts@@ -40,7 +40,7 @@ export async function recentDecisions(tx: Tx, tabId: string, conversationIds: streturn rows.map(row => ({ id: row._id as string, tabId: row.tabId as string, conversationId: row.conversationId as string,record: row.record as Prisma.JsonValue, final: (row.final ?? null) as Prisma.JsonValue, override: (row.override ?? null) as Prisma.JsonValue,assignmentId: (row.assignmentId ?? null) as string | null, outcome: (row.outcome ?? null) as string | null, run: (row.run ?? null) as Prisma.JsonValue,- outcomeAt: row.outcomeAt == null ? null : new Date(ms(row.outcomeAt)), createdAt: new Date(ms(row.createdAt)) }))+ evidence: (row.evidence ?? null) as Prisma.JsonValue, outcomeAt: row.outcomeAt == null ? null : new Date(ms(row.outcomeAt)), createdAt: new Date(ms(row.createdAt)) }))}export async function writeRouteEffects(tx: Tx, tabId: string, effects: RouteDecisionEffect[], now: number): Promise<void> {diff --git a/backend/src/superTabs/routeRecord.ts b/backend/src/superTabs/routeRecord.tsindex 8f4029cd2..4a824be06 100644--- a/backend/src/superTabs/routeRecord.ts+++ b/backend/src/superTabs/routeRecord.ts@@ -1,6 +1,7 @@/** What `harness super-tab route` records (docs/superpowers/specs/2026-10-19-super-tab-routing-v1-design.md). */import { z } from 'zod'import type { RouteRun } from './costs/attempts.js'+import { JOB_KINDS } from './evidence/jobKind.js'const level = z.enum(['low', 'medium', 'high'])const candidateId = z.string().regex(/^c\d{1,2}$/)@@ -59,6 +60,8 @@ export const routeRecordSchema = z.object({stepUp: z.object({ attempt: z.number().int().min(2).max(3), reason: z.string().min(1).max(200) }).strict().optional(),/** Why a review runs on its Builder's own engine (rules.ts sameEngineReview), written by the server, never taken from the route. */sameEngine: z.string().min(1).max(300).optional(),+ /** The job's kind from the fixed list (evidence/jobKind.ts), written by the server from its group, never taken from the route. */+ jobKind: z.enum(JOB_KINDS).optional(),}).strict().refine(d => d.candidates.some(c => c.id === d.pick), 'The pick must be one of the candidates.').refine(d => new Set(d.candidates.map(c => c.id)).size === d.candidates.length, 'Candidate ids must be unique.')diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 00c2d8fd9..8ca563b97 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -12,7 +12,7 @@ import { applyCommand, authorizeCommandAccess, operationSchema, PAIR_CHAIN_LIMITimport { redactCredentials } from './credentials.js'import type { AvatarUpload } from './profile.js'import { reactionCounts, type ReactionTarget } from './reactions.js'-import { deliveredCopies, inConversationOrder, pageDeliveries, pageReactions, pageThreads } from './pageReads.js'+import { agentOpenDeliveries, deliveredCopies, messagesPast, OPEN_DELIVERY, type MessageEdge, pageDeliveries, pageReactions, pageThreads } from './pageReads.js'import { threadSummaries } from './threads.js'import { attachmentMime, attachmentName, AttachmentTooLarge, AVATAR_PURPOSE, AVATAR_TYPES, checkedType, MAX_ATTACHMENT_BYTES, MAX_AVATAR_BYTES, objectKeyFor, peekType, publicUrl, trimPrefix,type Attachment, type Attachments, type AttachmentStore, type AvatarStore } from './attachments.js'@@ -32,7 +32,8 @@ import { digestDue, digestMessageId, digestRequest, digestSince } from './digestimport { judgedMachines, loseTasks, sweepForLead, sweepLiveness, SWEEP_EVERY_MS } from './liveness.js'import { archivable, archiveLine, ASLEEP_FIELDS, asleepMatch, stopIdleWorkers, stoppedMachines, type GroupActivity } from './tidy.js'import { clock, insertParts, loadActive, loadObserved, reassemble, split, type HeadData, type SwarmParts } from './parts/index.js'-import { groupsBy, listingDrops, quietSince, withoutHints } from './parts/indexed.js'+import { groupsBy, listingDrops, quietSince, readBy, withoutHints } from './parts/indexed.js'+import { memberSwarms } from './swarmRows.js'import { commitParts, indexesOf, numberMessages, type Touch, type Written } from './parts/commit.js'import { loadDeliveryParts } from './parts/light.js'import { guardedWrite } from './parts/write.js'@@ -53,6 +54,7 @@ import { endedHolds, HOLDING, startedHolds, type WorkHold } from '../github/holdimport { accrueLent } from './leaderboard/lent.js'import { mayDrive, TERMINAL_ANSWER_MS, TERMINAL_EXPIRY_MS, TERMINAL_PICKUP_MS, TERMINAL_RECHECK_MS, type TerminalEffect } from './terminal.js'import { costRows, summarizeCosts } from './costs/read.js'+import { recordEvidence } from './evidence/store.js'import { closeAssignment, closeUnassignedStart, readDecision, recentDecisions, recordAttempts, timedDecisionOf, writeRouteEffects } from './routeDecisions.js'import { listMentions, markDone, mentionsWaiting, openTags, readMention, resolveByReply, writeMentions } from './mentions.js'import { answerable, fullFor, listDecisions, type DecisionList, readAskedDecision, recordAnswer, repeatOf, waitingIn, waitingInProject, writeDecisions } from './decisions.js'@@ -194,10 +196,7 @@ export function afterCommit(tx: Transaction, callback: () => void): void {if (!pending) throw new Error('afterCommit needs a client from a Swarm transaction (store.ts transaction).')pending.push(callback)}-/** An agent's open deliveries, oldest first and each conversation's tied rows in its order (pageReads.ts): one indexed- * read, and the tied messages' sequences only when there are ties. */-const openDeliveries = async (tx: Transaction, tabId: string, agentId: string) => inConversationOrder(tx, tabId,- await tx.superTabDelivery.findMany({ where: { tabId, agentId, status: { in: [...OPEN_DELIVERY] } }, orderBy: { createdAt: 'asc' }, take: 100 }))+const openDeliveries = agentOpenDeliveries/** The grants a held answer checks again: the agent's own and those of the agents that sent what it allowed. */function grantsOf(state: SuperTabState, agentId: string, allowed: SuperTabDelivery[]) {@@ -221,8 +220,6 @@ const pollKey = (user: AuthUser, tabId: string, agentId: string) =>const pollMemoryFailed = (error: unknown): void => {logger.warn('[super-tab] delivery poll memory unavailable', { error: error instanceof Error ? error.message : String(error) })}-/** The deliveries a host is still told about (the rest are answered, cancelled or confirmed). */-const OPEN_DELIVERY = ['queued', 'claimed', 'uncertain'] as const/** Callers kept for the quiet delivery poll before the stale ones are dropped. */const POLLED_CAP = 5_000@@ -775,8 +772,7 @@ export class SuperTabStore {async list(user: AuthUser, after?: string) {this.personOnly(user)- const rows = await this.db.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, memberIds: { has: user.sub },- ...(after ? { id: { gt: after } } : {}) }, orderBy: { id: 'asc' }, take: 101, select: SWARM_ROW })+ const rows = await memberSwarms(this.db, user.autonomousEnv, user.sub, { after, limit: 101 })const heads = await this.heads(rows.slice(0, 100))return { tabs: rows.slice(0, 100).flatMap(row => {const head = heads.get(row.id)@@ -1383,6 +1379,7 @@ export class SuperTabStore {if (command.type === 'work.status' && (command.status === 'done' || command.status === 'stopped')) {await closeAssignment(tx, tabId, command.assignmentId, command.status, context.now)}+ await recordEvidence(tx, tabId, original, effects.state, context.now)await this.writeMessages(tx, tabId, effects.state, effects.messages, sequences)if (command.type === 'message.send' && actor.kind === 'person') await resolveByReply(tx, tabId, command.conversationId, actor.userId, context.now)await writeMentions(tx, tabId, effects.state, effects.messages, context.now)@@ -1923,27 +1920,22 @@ export class SuperTabStore {// and why others could not (security review 2 of #2115). Left out like an agent-only notice, so no page is shorter.const buddy = isBuddyReader(state, actor)const forward = cursor.after !== undefined- const past = (sequence: number, id: string | undefined, direction: 'gt' | 'lt') => id === undefined ? { sequence: { [direction]: sequence } }- : { OR: [{ sequence: { [direction]: sequence } }, { sequence, id: { [direction]: id } }] }- const where = { tabId, conversationId,- ...(cursor.messageId ? { id: cursor.messageId } : {}),- // One thread: its root (its own thread) and its replies.- ...(cursor.thread ? { thread: cursor.thread } : {}),- ...(forward ? past(cursor.after!, cursor.afterId, 'gt') : cursor.before !== undefined ? past(cursor.before, cursor.beforeId, 'lt') : {}) }+ // One thread: its root (its own thread) and its replies.+ const at = { tabId, conversationId, messageId: cursor.messageId, thread: cursor.thread }+ const start: MessageEdge | undefined = forward ? { sequence: cursor.after!, id: cursor.afterId }+ : cursor.before !== undefined ? { sequence: cursor.before, id: cursor.beforeId } : undefined// An agent-only notice is listed for its own recipient alone. Hidden rows never shorten a page: Desktop reads on from the// last row it shows, so the page reads past them until it has 101 rows this reader may see, or reaches the end.// Each batch reads on from the last row of the one before, never by an offset that walks every row before it again.const rows: SuperTabMessage[] = []- const order = forward ? 'asc' as const : 'desc' as const- for (let edge: SuperTabMessage | undefined; rows.length <= 100;) {- const batch = await tx.superTabMessage.findMany({ where: edge ? { AND: [where, past(edge.sequence, edge.id, forward ? 'gt' : 'lt')] } : where,- orderBy: [{ sequence: order }, { id: order }], take: 101 })+ for (let edge = start; rows.length <= 100;) {+ const batch = await messagesPast(tx, at, edge, forward, 101)// A task chat's copy of a Lead's notice stored before it was marked is that notice: read by no one (pageReads.ts).const copies = await deliveredCopies(tx, tabId, batch)rows.push(...batch.filter(m => !copies.has(m.id) && (!agentOnly(m.source, m.recipientIds) || (actor.kind === 'agent' && m.recipientIds.includes(actor.agentId)))&& !(buddy && routingRow(m.source))))if (batch.length < 101) break- edge = batch.at(-1)+ edge = { sequence: batch.at(-1)!.sequence, id: batch.at(-1)!.id }}const page = rows.slice(0, 100)const next = rows.length > 100 ? { sequence: page.at(-1)!.sequence, id: page.at(-1)!.id } : null@@ -2112,7 +2104,9 @@ export class SuperTabStore {* with the add-on: a full load of each Swarm sent about 1 MB per Swarm per poll (Diego, 2026-10-28). */async hostGrids(user: AuthUser) {this.personOnly(user)- const rows = await this.db.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, ownerId: user.sub, format: 2 }, take: 100, select: { id: true } })+ // By the owner index (parts/indexed.ts): Prisma's $expr filter is bounded by the environment alone, every Swarm of it.+ const rows = (await readBy(this.db, 'SuperTab', 'owner', [{ $match: { autonomousEnv: user.autonomousEnv, ownerId: user.sub, format: 2 } },+ { $sort: { _id: 1 } }, { $limit: 100 }, { $project: { _id: 1 } }])).map(row => ({ id: row._id as string }))return transaction(this.db, async tx => {const heads = await tx.swarmHead.findMany({ where: { tabId: { in: rows.map(row => row.id) }, key: 'head' }, select: { tabId: true, data: true } })const withGrid = new Map(heads.map(head => [head.tabId, head.data as unknown as HeadData] as const).filter(([, head]) => head.localModels))@@ -2160,6 +2154,7 @@ export class SuperTabStore {const touches = judgedMachines(loaded.state, state, rows).filter(t => t.key !== machineId)await this.endRuns(tx, tabId, loaded.state, state)await recordAttempts(tx, tabId, loaded.state, state, now)+ await recordEvidence(tx, tabId, loaded.state, state, now)const version = (await this.save(tx, loaded, state, stamp, touches)).versions.get(`machine:${machineId}`) ?? 0await this.writeMessages(tx, tabId, state, rows, sequences, true)return { version }@@ -2443,6 +2438,7 @@ export class SuperTabStore {// second finds none).await this.endRuns(tx, tabId, loaded.state, state)await recordAttempts(tx, tabId, loaded.state, state, this.now())+ await recordEvidence(tx, tabId, loaded.state, state, this.now())if (ledProject(state, agentId)) {await this.releaseRuns(tx, tabId, await this.staleRuns(tx, tabId, state))}@@ -2634,6 +2630,7 @@ export class SuperTabStore {const project = group ? groupProject(state, group).id : undefinedawait this.save(tx, loaded, state, clock.next(), project && state.projects ? [{ kind: 'progress', key: project }] : [])await recordAttempts(tx, tabId, { ...state, conversations: before.conversations }, state, this.now())+ await recordEvidence(tx, tabId, { ...state, conversations: before.conversations }, state, this.now())await this.writeMessages(tx, tabId, state, notices, sequences)if (!prior) await tx.superTabStopReceipt.create({ data: { id, tabId, assignmentId, ...execution, receipt } })ended = endedHolds(before, state)diff --git a/backend/src/superTabs/swarmRows.ts b/backend/src/superTabs/swarmRows.tsnew file mode 100644index 000000000..de3065463--- /dev/null+++ b/backend/src/superTabs/swarmRows.ts@@ -0,0 +1,23 @@+import type { Prisma } from '@prisma/client'+import { readBy } from './parts/indexed.js'++type Transaction = Prisma.TransactionClient++// SuperTab rows found by who is in them. Prisma sends `memberIds: { has }` as $expr, which bounds only the autonomousEnv+// prefix: each list read examined every Swarm of the environment (roadmap Phase 3.3). These name the member index, so they+// examine only the person's Swarms, and take them off it in id order without a sort (integration/superTabNamedReads.test.ts).++export interface MemberSwarm { id: string; ownerId: string; revision: number; format: number; workspaceId: string | null }++/** The Swarms `userId` is in, by id after `after`, up to `limit` (all without one), with the fields lists show; only+ * `workspaceId`'s when given. */+export async function memberSwarms(db: Transaction, autonomousEnv: string, userId: string,+ page: { after?: string; limit?: number; workspaceId?: string }): Promise<MemberSwarm[]> {+ const rows = await readBy(db, 'SuperTab', 'members', [+ { $match: { autonomousEnv, memberIds: userId, ...page.after ? { _id: { $gt: page.after } } : {},+ ...page.workspaceId ? { workspaceId: page.workspaceId } : {} } },+ { $sort: { _id: 1 } }, ...page.limit ? [{ $limit: page.limit }] : [], { $project: { ownerId: 1, revision: 1, format: 1, workspaceId: 1 } }])+ // A Swarm stored before `format` existed is whole in `state` (schema default 1); one from before Workspaces has none.+ return rows.map(row => ({ id: row._id as string, ownerId: row.ownerId as string, revision: Number(row.revision ?? 0),+ format: Number(row.format ?? 1), workspaceId: (row.workspaceId ?? null) as string | null }))+}diff --git a/backend/src/superTabs/sweeps.ts b/backend/src/superTabs/sweeps.tsindex 0f98bc6fc..75b2e9dcb 100644--- a/backend/src/superTabs/sweeps.ts+++ b/backend/src/superTabs/sweeps.ts@@ -5,6 +5,7 @@ import { DORMANT_AFTER_MS, RETENTION_MS } from './parts/types.js'import { logger } from '../utils/logger.js'import { ensureIndex } from '../lib/db/indexes.js'import { swarmTransaction } from './cache.js'+import { expireEvidence } from './evidence/store.js'/** Parts whose key is never used twice (conversations, starts, projects' progress) lose their tombstone at `purgeAt`.* A person, agent or machine can come back under the same key, so its tombstone is kept for good, compacted to its@@ -125,7 +126,7 @@ async function expireInvitations(db: PrismaClient, now: number): Promise<number>/** One pass of every sweep (spec, Archive). Each part it changes is a guarded write, so a command in between wins. */export async function sweepSwarms(db: PrismaClient, now = Date.now()) {return { slept: await sleepQuietGroups(db, now), startsExpired: await expireStarts(db, now), invitationsExpired: await expireInvitations(db, now),- tombstonesCompacted: await compactTombstones(db, now) }+ tombstonesCompacted: await compactTombstones(db, now), evidenceExpired: await expireEvidence(db, now) }}/** Runs the sweeps every hour in the singleton worker. `finishWorkspaceRemovals` finishes Workspace removals whose Swarm removalsdiff --git a/backend/src/superTabs/workspaceStore.ts b/backend/src/superTabs/workspaceStore.tsindex ae24f272a..f2d70b280 100644--- a/backend/src/superTabs/workspaceStore.ts+++ b/backend/src/superTabs/workspaceStore.ts@@ -2,6 +2,7 @@ import type { Prisma, PrismaClient, SwarmWorkspaceMember, SwarmWorkspaceRemovalimport type { AuthUser } from '../lib/ssoAuth.js'import { fail, stableId, type SuperTabState } from './model.js'import { mayAssignRole, mayManageMember, WORKSPACE_LABEL, workspaceCan, type WorkspaceAction, type WorkspaceRole } from './workspaces.js'+import { memberSwarms } from './swarmRows.js'import { logger } from '../utils/logger.js'type Transaction = Prisma.TransactionClient@@ -292,8 +293,8 @@ export class SwarmWorkspaces {/** The removed person leaves each Swarm of the Workspace they are still in; the removal closes once none is left. Returns how* many Swarms could not be left now. */private async finish(removal: SwarmWorkspaceRemoval): Promise<number> {- const rows = await this.db.superTab.findMany({ where: { autonomousEnv: removal.autonomousEnv, workspaceId: removal.workspaceId, memberIds: { has: removal.userId } },- select: { id: true } })+ // Every Swarm of theirs in the Workspace: no page limit, as before; a person is in few Swarms.+ const rows = await memberSwarms(this.db, removal.autonomousEnv, removal.userId, { workspaceId: removal.workspaceId })let pending = 0for (const row of rows) {try { await this.deps.leave(personOf(removal, removal.autonomousEnv), row.id, stableId('workspace-removal', removal.id)) } catch (error) {diff --git a/backend/src/worker.ts b/backend/src/worker.tsindex 6f578294d..fdb91c4c3 100644--- a/backend/src/worker.ts+++ b/backend/src/worker.ts@@ -14,6 +14,7 @@ import {} from './lib/db/migrate.js'import { ensurePlans } from './lib/db/seed.js'import { prisma } from './lib/prisma.js'+import { startQueryStats } from './lib/queryStats.js'import { releaseSchema } from './lib/db/schemaRelease.js'import { startSwarmSweeps } from './superTabs/sweeps.js'import { startLegacyDrop } from './superTabs/migration/dropLegacyJob.js'@@ -33,6 +34,9 @@ import { logger } from './utils/logger.js'// Singleton background process. HTTP/WS server.ts runs as a PM2 cluster and must never own schema// writes, catalog syncs, migrations or periodic jobs; otherwise every live server worker races them.async function start(): Promise<void> {+ // Every minute, this process's queries by model.action and filter shape (lib/queryStats.ts, DB roadmap Phase 1); its+ // jobs and startup migrations count as background.+ const stopQueryStats = startQueryStats()// Existing production data was created against staging upstreams. Stamp it before Prisma swaps// the old global unique indexes for their per-environment replacements.await migrateAutonomousEnvironment()@@ -70,6 +74,8 @@ async function start(): Promise<void> {stopArchive()stopDeliveries()stopReceiptSweep()+ // The last partial minute, before the database closes.+ stopQueryStats()void Promise.allSettled([prisma.$disconnect(), closeBus()]).finally(() => process.exit(0))}process.on('SIGINT', () => shutdown('SIGINT'))diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.tsindex 8c64b72fa..0e697995b 100644--- a/backend/vitest.super-tabs.config.ts+++ b/backend/vitest.super-tabs.config.ts@@ -1,8 +1,10 @@import { defineConfig } from 'vitest/config'export default defineConfig({ test: { include: ['integration/superTabs.test.ts', 'integration/superTabSharing.test.ts', 'integration/superTabGithub.test.ts', 'integration/superTabTeam.test.ts', 'integration/superTabWorkspaces.test.ts',- 'integration/superTabRead.test.ts', 'integration/superTabReadMarks.test.ts', 'integration/superTabLeaderboard.test.ts', 'integration/superTabMigration.test.ts', 'integration/superTabLiveness.test.ts', 'integration/superTabTidy.test.ts',- 'integration/superTabProfile.test.ts', 'integration/superTabLegacyDrop.test.ts', 'integration/shareRaces.test.ts',- 'integration/superTabIndexes.test.ts', 'integration/superTabHotReads.test.ts', 'integration/swarmSweepStarts.test.ts', 'integration/superTabGroupPlans.test.ts', 'integration/superTabInvitationPlans.test.ts', 'integration/superTabCache.test.ts', 'integration/superTabObserver.test.ts', 'integration/productUsageConflicts.test.ts', 'integration/productUsageReceipts.test.ts', 'integration/schemaRelease.test.ts', 'integration/superTabBuddies.test.ts', 'integration/superTabBuddyProbes.test.ts', 'integration/superTabCosts.test.ts',- 'integration/harnessSharesList.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/cacheOn.test-support.ts'],+ 'integration/superTabRead.test.ts', 'integration/superTabReadMarks.test.ts', 'integration/superTabLeaderboard.test.ts', 'integration/superTabMigration.test.ts', 'integration/superTabLiveness.test.ts',+ 'integration/superTabTidy.test.ts', 'integration/superTabProfile.test.ts', 'integration/superTabLegacyDrop.test.ts', 'integration/shareRaces.test.ts', 'integration/superTabIndexes.test.ts',+ 'integration/superTabHotReads.test.ts', 'integration/swarmSweepStarts.test.ts', 'integration/superTabGroupPlans.test.ts', 'integration/superTabInvitationPlans.test.ts', 'integration/superTabCache.test.ts',+ 'integration/superTabObserver.test.ts', 'integration/productUsageConflicts.test.ts', 'integration/productUsageReceipts.test.ts', 'integration/schemaRelease.test.ts', 'integration/superTabBuddies.test.ts',+ 'integration/superTabBuddyProbes.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts',+ 'integration/superTabEvidence.test.ts', 'integration/superTabNamedReads.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/cacheOn.test-support.ts'],fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })diff --git a/desktop/lib/super_tabs/client.dart b/desktop/lib/super_tabs/client.dartindex a3a0f96e1..4d39326e2 100644--- a/desktop/lib/super_tabs/client.dart+++ b/desktop/lib/super_tabs/client.dart@@ -63,6 +63,14 @@ class SuperTabClient {/// menu bar lists.final void Function()? onNotices;final _tagCounts = <String, int>{};++ /// The digest of each Swarm's tags as the list last told it, for the tags+ /// last counted: the list says they moved when it changes.+ final _tagDigests = <String, String>{};++ /// Whether the list is asked for each Swarm's tags (`?mentions=1`). Off for+ /// the session once a backend refuses the query.+ bool _listMentions = true;final _tagsSeen = <String, Set<String>>{};/// The tags waiting for this account in a Swarm: its own state once open,@@ -203,7 +211,10 @@ class SuperTabClient {if (away && _viewSaves.containsKey(entry.key)) _saveView(entry.key);// Back on screen, the Swarm reads its own tags: the count discovery// kept while it was away is stale from now on.- if (!away && entry.value.away) _tagCounts.remove(entry.key);+ if (!away && entry.value.away) {+ _tagCounts.remove(entry.key);+ _tagDigests.remove(entry.key);+ }entry.value.away = away;}}@@ -365,7 +376,9 @@ class SuperTabClient {_creating.clear();_visibility.clear();_tagCounts.clear();+ _tagDigests.clear();_tagsSeen.clear();+ _listMentions = true;discoveryError = null;for (final controller in _loaded.values) {controller.revokeAccess('The account changed. Open this Swarm again.');@@ -451,13 +464,11 @@ class SuperTabClient {await _readHidden(account, generation);if (generation != _generation) return;final tabs = <String, SuperTabListing>{};+ final tags = <String, ({int count, String digest})>{};final cursors = <String>{};String? after;do {- final page = await map(- 'GET',- '/api/super-tabs/list${after == null ? '' : '?after=${Uri.encodeComponent(after)}'}',- );+ final page = await _readListPage(after);if (generation != _generation) return;if (page['tabs'] is! List) {throw const FormatException('Missing tabs');@@ -469,6 +480,14 @@ class SuperTabClient {}final id = row['id'] as String;tabs[id] = (id: id, name: row['name'] as String);+ // Told only by a backend that counts them (and only when asked).+ if (row['mentionsWaiting'] case final int count+ when row['mentionsDigest'] is String) {+ tags[id] = (+ count: count,+ digest: row['mentionsDigest'] as String,+ );+ }}after = page['next'] as String?;if (after != null && !cursors.add(after)) {@@ -487,12 +506,16 @@ class SuperTabClient {.catchError((Object _) {}),);}- await _readTags([- for (final id in tabs.keys)- if (!hidden.contains(id) &&- (!_loaded.containsKey(id) || _paused(id)))- id,- ], generation);+ await _readTags(+ [+ for (final id in tabs.keys)+ if (!hidden.contains(id) &&+ (!_loaded.containsKey(id) || _paused(id)))+ id,+ ],+ generation,+ tags,+ );} catch (error) {if (generation == _generation) {discoveryError = error;@@ -506,6 +529,30 @@ class SuperTabClient {});}+ /// One page of the Swarm list, with each Swarm's waiting tags while the+ /// backend counts them. A backend from before that refuses the query: the+ /// page is read without it, and every page after it for the session.+ Future<Map<String, dynamic>> _readListPage(String? after) async {+ String path() {+ final query = [+ if (_listMentions) 'mentions=1',+ if (after != null) 'after=${Uri.encodeComponent(after)}',+ ];+ return '/api/super-tabs/list${query.isEmpty ? '' : '?${query.join('&')}'}';+ }++ try {+ return await map('GET', path());+ } on SuperTabFailure catch (failure) {+ if (!_listMentions ||+ (failure.statusCode != 400 && failure.code != 'VALIDATION_ERROR')) {+ rethrow;+ }+ _listMentions = false;+ return map('GET', path());+ }+ }+Future<Object?> request(String method,String path, {@@ -660,6 +707,7 @@ class SuperTabClient {SuperTabDecisions.of(controller).addListener(changed);}_tagCounts.remove(id);+ _tagDigests.remove(id);_loaded[id] = controller;void drawSaved(Map<String, dynamic>? view) {if (view != null && generation == _generation) {@@ -691,9 +739,34 @@ class SuperTabClient {/// One light read per Swarm tab that is not open: its waiting tags. A/// failed read, a backend before tags included, changes nothing and is/// tried again on the next round.- Future<void> _readTags(List<String> ids, int generation) async {+ Future<void> _readTags(+ List<String> ids,+ int generation,+ Map<String, ({int count, String digest})> listed,+ ) async {var changed = false;for (final id in ids) {+ if (generation != _generation) break;+ if (_loaded.containsKey(id) && !_paused(id)) continue;+ // The list told this Swarm's tags: unchanged, there is nothing to ask;+ // none, there is nothing to list. Otherwise their text is read.+ final counted = listed[id];+ if (counted != null) {+ if (_tagCounts[id] == counted.count &&+ _tagDigests[id] == counted.digest) {+ continue;+ }+ if (counted.count == 0) {+ // The baseline a later tag is new against.+ _tagsSeen[id] ??= {};+ _tagDigests[id] = counted.digest;+ if (_tagCounts[id] != 0) {+ _tagCounts[id] = 0;+ changed = true;+ }+ continue;+ }+ }try {final answer = await map('GET',@@ -726,6 +799,7 @@ class SuperTabClient {// Not news again when the Swarm is shown and reads its own.mentions?.seen(told);_tagsSeen[id] = {...?seen, for (final m in waiting) m.id};+ if (counted != null) _tagDigests[id] = counted.digest;if (_tagCounts[id] != waiting.length) {_tagCounts[id] = waiting.length;changed = true;diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex 1094f548d..7a1f85c03 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -391,6 +391,17 @@ class SuperTabController extends ChangeNotifier {});}+ /// How often the idle poll reads: every [pollInterval], or+ /// [SuperTabReading.awayPoll] while the Swarm is away (never more often+ /// than [pollInterval]). A push is not an idle poll: [_readGap] keeps+ /// reading a told change at [pollInterval], so a tag reaches an away+ /// Swarm's badge and notice as fast as before.+ Duration get _every {+ final away = _policy.awayPoll;+ if (away == null || !_away) return pollInterval;+ return away > pollInterval ? away : pollInterval;+ }+/// How often the poll read before pushes: every [pollInterval], or/// [SuperTabReading.quietPoll] once the person has been quiet a while.Duration get _readGap {@@ -472,7 +483,19 @@ class SuperTabController extends ChangeNotifier {set away(bool value) {if (_away == value) return;_away = value;- if (!_policy.pausesAway || _startedAt == null || _disposed) return;+ if (_startedAt == null || _disposed) return;+ if (!_policy.pausesAway) {+ // Going away slows the poll; coming back reads at once unless a poll+ // just did ([SuperTabReading.awayPoll]).+ if (_policy.awayPoll == null) return;+ final last = _lastFullRead;+ if (!value &&+ (last == null || clock.now().difference(last) >= pollInterval)) {+ unawaited(refresh());+ }+ _schedule();+ return;+ }if (value) {_poll?.cancel();return;@@ -1373,13 +1396,13 @@ class SuperTabController extends ChangeNotifier {_poll?.cancel();if (_disposed || updateRequired || pollInterval <= Duration.zero) return;if (!_policy.adapts) {- _poll = Timer.periodic(pollInterval, (_) {+ _poll = Timer.periodic(_every, (_) {if (_pollDue) unawaited(refresh());});return;}if (accessRevoked || (_policy.pausesAway && _away)) return;- final wait = after ?? pollInterval;+ final wait = after ?? _every;_poll = Timer(wait > Duration.zero ? wait : Duration.zero,() => unawaited(_tick()),@@ -1397,7 +1420,7 @@ class SuperTabController extends ChangeNotifier {? refresh(): _readMessages(selectedId, light: true));}- _schedule(pollInterval - clock.now().difference(began));+ _schedule(_every - clock.now().difference(began));}bool get _fullReadDue {@@ -2170,13 +2193,19 @@ class SuperTabController extends ChangeNotifier {_lastFullRead = clock.now();// Taken as the read starts: a push heard while it is out reads once more,// on the next allowed read, unless it repeats a time already told.+ final told = _toldMain || _toldMachine;_toldMain = _toldMachine = false;final took = Stopwatch()..start();// The open conversation's messages, asked for beside the state// ([SuperTabReading.messagesWithState]); dropped if the state moves the// selection elsewhere.final earlyId = selectedId;- final earlyQuery = _earlyQuery(earlyId);+ // Only when something may have happened: a first read, a saved view, a+ // push, a message waiting for its receipt. Otherwise the messages wait+ // for the state to say there is news (roadmap 2.5).+ final earlyQuery = told || !_messagesCurrent(earlyId)+ ? _earlyQuery(earlyId)+ : null;final early = earlyQuery == null? null: (request('GET', '${_messagesPath(earlyId)}$earlyQuery')..ignore());@@ -2291,14 +2320,21 @@ class SuperTabController extends ChangeNotifier {_readUnreadBuddyChats();_partsReadAt = clock.now();error = null;- await (selectedId == earlyId && messagesRead != null- ? messagesRead- : _readMessages(- selectedId,- early: selectedId == earlyId && early != null- ? (query: earlyQuery!, page: early)- : null,- ));+ // A state that moved nothing, over messages read at that very state,+ // has no news for the conversation: no read of it (roadmap 2.5).+ if (early != null ||+ !_messagesCurrent(selectedId) ||+ read.full ||+ read.changed) {+ await (selectedId == earlyId && messagesRead != null+ ? messagesRead+ : _readMessages(+ selectedId,+ early: selectedId == earlyId && early != null+ ? (query: earlyQuery!, page: early)+ : null,+ ));+ }if (stateReads == 1) {// Where a first open's time went, from the tab asking to the chat it shows.appLog.debug(@@ -2591,6 +2627,22 @@ class SuperTabController extends ChangeNotifier {return tail != null ? '?after=$tail' : '';}+ /// The state's last change when [id]'s newest messages were read: while the+ /// state has not moved past it, nothing new can be in the conversation.+ final _messagesAt = <String, int>{};++ /// [id]'s messages are as new as the state held, and nothing outside the+ /// state is waited for: no receipt, no saved page, no newer page asked for.+ bool _messagesCurrent(String id) =>+ _policy.messagesWhenChanged &&+ !_showingSaved &&+ snapshot != null &&+ _messages[id] != null &&+ _messagesAt[id] == lastChangedAt &&+ !_holding(id) &&+ !_latestWanted.contains(id) &&+ !_receiptOpen(id);+/// The query of [id]'s messages read to start beside a state read, or null./// On first open only for the conversation the saved state named; after/// that, for a conversation the state has and no read of it under way.@@ -2674,6 +2726,8 @@ class SuperTabController extends ChangeNotifier {// A light check asks only for new messages, which wait while holding.if (light && _holding(id)) return;final generation = _heldGeneration[id];+ // What the Swarm's state had said when this read was asked for.+ final stateAt = lastChangedAt;// What [id] held was replaced while newer messages were on their way.bool replaced() => !older && _heldGeneration[id] != generation;try {@@ -2861,6 +2915,7 @@ class SuperTabController extends ChangeNotifier {}_dropShownSends(id);if (reactionSeq is int) _reactionSeq[id] = reactionSeq;+ if (!older && !holding) _messagesAt[id] = stateAt;if (older || replacing || !_before.containsKey(id)) {_before[id] = SuperTabPage.read(answer['next']);}diff --git a/desktop/lib/super_tabs/reading.dart b/desktop/lib/super_tabs/reading.dartindex 83234ee0a..c4e40dc7a 100644--- a/desktop/lib/super_tabs/reading.dart+++ b/desktop/lib/super_tabs/reading.dart@@ -9,6 +9,8 @@ class SuperTabReading {this.quietPoll,this.quietAfter = const Duration(seconds: 30),this.pausesAway = false,+ this.awayPoll,+ this.messagesWhenChanged = false,this.readsOnConnect = false,this.connectGrace = Duration.zero,this.messagesWithState = false,@@ -20,6 +22,8 @@ class SuperTabReading {/// once, and a Swarm seen before asks only for what changed since, drawing/// nothing kept until that read has said what the reader may still see.static const desktop = SuperTabReading(+ awayPoll: Duration(seconds: 15),+ messagesWhenChanged: true,messagesWithState: true,drawsSaved: true,confirmsSaved: true,@@ -37,6 +41,19 @@ class SuperTabReading {/// hidden, and reads at once when it is shown again.final bool pausesAway;+ /// Null polls an away Swarm as often as the one on screen. Otherwise a+ /// Swarm that is not the one on screen, or the whole app in the background,+ /// polls this often (as the web does), and reads at once when shown again.+ /// Unlike [pausesAway] it keeps reading: Desktop's badges and notices come+ /// from the Swarms it is not showing.+ final Duration? awayPoll;++ /// True reads the open conversation's messages only when something may+ /// have happened: a first read, a push, a state that moved since they were+ /// read, a message waiting for its receipt. A poll whose state read finds+ /// nothing new then asks for the state alone.+ final bool messagesWhenChanged;+/// True reads at once when a machine able to serve Swarm reads connects,/// instead of at the next poll.final bool readsOnConnect;diff --git a/desktop/test/super_tab_discovery_test.dart b/desktop/test/super_tab_discovery_test.dartindex a148bafc9..b882d5eae 100644--- a/desktop/test/super_tab_discovery_test.dart+++ b/desktop/test/super_tab_discovery_test.dart@@ -37,7 +37,11 @@ class _Catalog {return server.request(method, path, body: body);}expectSync(method, 'GET');- paths.add(path);+ // These tests are about the pages, not the tags the list also carries.+ final plain = path+ .replaceFirst('?mentions=1&', '?')+ .replaceFirst('?mentions=1', '');+ paths.add(plain);final after = Uri.parse(path).queryParameters['after'];final index = after == null? 0@@ -45,7 +49,7 @@ class _Catalog {final rows = index < tabs.length ? [Map.of(tabs[index])] : [];final next = index + 1 < tabs.length ? tabs[index]['id'] : null;if (hold case final waiting?) await waiting.future;- if (fail == path) throw StateError('Connection lost');+ if (fail == plain) throw StateError('Connection lost');return {'tabs': rows, 'next': next};}}diff --git a/desktop/test/super_tab_list_mentions_test.dart b/desktop/test/super_tab_list_mentions_test.dartnew file mode 100644index 000000000..dcd9a1f4a--- /dev/null+++ b/desktop/test/super_tab_list_mentions_test.dart@@ -0,0 +1,177 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/super_tabs/client.dart';+import 'package:harness/super_tabs/controller.dart';++import 'support/super_tab_fixture.dart';+import 'swarm_state_test.dart' show MemoryStore;++/// Stability roadmap 2.5: the Swarm list tells each Swarm's waiting tags+/// (`/api/super-tabs/list?mentions=1`), so discovery asks a Swarm for its tags+/// only when they changed, not once per Swarm every round.+class _Backend {+ _Backend({this.listsMentions = true});++ /// A backend from before the list carried tags: it refuses the query.+ final bool listsMentions;+ final server = ConversationServer();+ final lists = <String>[];++ /// What the list says of 'tab': set to null for a row with no tag counts.+ String? digest = 'd0';+ bool counted = true;++ Future<Object?> call(+ String method,+ String path, {+ Map<String, dynamic>? body,+ }) async {+ final uri = Uri.parse(path);+ if (uri.path != '/api/super-tabs/list') {+ return server.request(method, path, body: body);+ }+ lists.add(path);+ final asked = uri.queryParameters['mentions'] == '1';+ if (asked && !listsMentions) {+ throw const SuperTabFailure(+ 'VALIDATION_ERROR',+ 'Unrecognized key: "mentions"',+ statusCode: 400,+ );+ }+ return {+ 'tabs': [+ {+ 'id': 'tab',+ 'name': 'Pilot',+ if (asked && counted) ...{+ 'mentionsWaiting': server.mentions.length,+ 'mentionsDigest': '${digest}x${server.mentions.length}',+ },+ },+ ],+ 'next': null,+ };+ }+}++SuperTabClient _client(+ _Backend backend, {+ List<String>? arrived,+ void Function()? onTagCounts,+}) {+ final client = SuperTabClient(+ storage: MemoryStore(),+ transport: backend.call,+ discoveryInterval: Duration.zero,+ onTabs: (_, _) {},+ onMention: (_, mention) => arrived?.add(mention.text),+ onTagCounts: onTagCounts,+ );+ addTearDown(client.dispose);+ return client..bind('owner');+}++void main() {+ test(+ 'a list that tells no tags for a Swarm costs no mentions read',+ () async {+ final backend = _Backend();+ final client = _client(backend);+ await client.refreshTabs();+ expect(backend.lists.single, contains('mentions=1'));+ expect(client.waitingTags('tab'), 0);+ expect(backend.server.mentionReads, 0);+ },+ );++ test(+ 'reads a Swarm\'s tags once, then only when the list says they moved',+ () async {+ final backend = _Backend();+ backend.server.tag('message-1', text: 'Old');+ final arrived = <String>[];+ final client = _client(backend, arrived: arrived);+ await client.refreshTabs();+ expect(client.waitingTags('tab'), 1);+ expect(backend.server.mentionReads, 1);+ await client.refreshTabs();+ await client.refreshTabs();+ expect(backend.server.mentionReads, 1);+ expect(arrived, isEmpty);+ backend.server.tag('message-2', text: 'New');+ await client.refreshTabs();+ expect(backend.server.mentionReads, 2);+ expect(client.waitingTags('tab'), 2);+ expect(arrived, ['New']);+ },+ );++ test('a tag answered elsewhere lowers the count without a read, and a later tag is announced', () async {+ final backend = _Backend();+ backend.server.tag('message-1', text: 'Old');+ final arrived = <String>[];+ var changes = 0;+ final client = _client(+ backend,+ arrived: arrived,+ onTagCounts: () => changes++,+ );+ await client.refreshTabs();+ expect(changes, 1);+ backend.server.mentions.clear();+ await client.refreshTabs();+ expect(client.waitingTags('tab'), 0);+ expect(changes, 2);+ expect(backend.server.mentionReads, 1);+ backend.server.tag('message-3', text: 'Fresh');+ // The fixture numbers tags by how many it holds: a new one, not the old.+ backend.server.mentions.last['id'] = 'mention-9';+ await client.refreshTabs();+ expect(client.waitingTags('tab'), 1);+ expect(arrived, ['Fresh']);+ });++ test(+ 'a Swarm with no tags at the first look announces the first one that comes',+ () async {+ final backend = _Backend();+ final arrived = <String>[];+ final client = _client(backend, arrived: arrived);+ await client.refreshTabs();+ backend.server.tag('message-1', text: 'First');+ await client.refreshTabs();+ expect(arrived, ['First']);+ expect(client.waitingTags('tab'), 1);+ },+ );++ test(+ 'a row without counts is asked for its tags itself, as before',+ () async {+ final backend = _Backend()..counted = false;+ backend.server.tag('message-1');+ final client = _client(backend);+ await client.refreshTabs();+ await client.refreshTabs();+ expect(client.waitingTags('tab'), 1);+ expect(backend.server.mentionReads, 2);+ },+ );++ test(+ 'a backend that refuses the query is asked without it, and not again',+ () async {+ final backend = _Backend(listsMentions: false);+ backend.server.tag('message-1');+ final client = _client(backend);+ await client.refreshTabs();+ expect(client.waitingTags('tab'), 1);+ expect(client.discoveryError, isNull);+ expect(backend.lists, hasLength(2));+ expect(backend.lists.last, isNot(contains('mentions')));+ await client.refreshTabs();+ expect(backend.lists, hasLength(3));+ expect(backend.lists.last, isNot(contains('mentions')));+ },+ );+}diff --git a/desktop/test/super_tab_mentions_test.dart b/desktop/test/super_tab_mentions_test.dartindex fba8ca2f9..7af8cdc45 100644--- a/desktop/test/super_tab_mentions_test.dart+++ b/desktop/test/super_tab_mentions_test.dart@@ -950,7 +950,7 @@ void main() {final client = SuperTabClient(storage: MemoryStore(),transport: (method, path, {body}) async =>- path == '/api/super-tabs/list'+ Uri.parse(path).path == '/api/super-tabs/list'? {'tabs': [{'id': 'tab', 'name': 'Pilot'},@@ -992,7 +992,7 @@ void main() {final client = SuperTabClient(storage: MemoryStore(),transport: (method, path, {body}) async {- if (path == '/api/super-tabs/list') {+ if (Uri.parse(path).path == '/api/super-tabs/list') {return {'tabs': [{'id': 'gone', 'name': 'Older'},diff --git a/desktop/test/super_tab_quiet_mode_test.dart b/desktop/test/super_tab_quiet_mode_test.dartnew file mode 100644index 000000000..0d783c115--- /dev/null+++ b/desktop/test/super_tab_quiet_mode_test.dart@@ -0,0 +1,243 @@+import 'dart:async';++import 'package:clock/clock.dart';+import 'package:fake_async/fake_async.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/reading.dart';++import 'support/super_tab_fixture.dart';++bool _isStateRead(String path) =>+ path == '/api/super-tabs/tab/parts' ||+ path.startsWith('/api/super-tabs/tab/changes?');++/// Every read the controller made, in order.+class _Reads {+ _Reads(this.server);+ final ConversationServer server;+ final paths = <String>[];++ Future<Map<String, dynamic>> call(+ String method,+ String path, {+ Map<String, dynamic>? body,+ }) {+ if (method == 'GET') paths.add(path);+ return server.request(method, path, body: body);+ }++ int get states => paths.where(_isStateRead).length;+ int get messageReads => paths.where((p) => p.contains('/messages')).length;+ void clear() => paths.clear();+}++SuperTabController _controller(_Reads reads) => SuperTabController(+ tabId: 'tab',+ accountId: 'owner',+ request: reads.call,+ save: reads.server.save,+ reading: SuperTabReading.desktop,+);++const _poll = Duration(seconds: 3);++/// Stability roadmap 2.5: Desktop asks for less when nothing happens, and+/// when a Swarm is not the one in front.+void main() {+ group('a poll that finds the Swarm unchanged', () {+ test('reads the state and no messages', () {+ fakeAsync((async) {+ final reads = _Reads(ConversationServer()..append('Hello'));+ final c = _controller(reads)..start();+ async.flushMicrotasks();+ reads.clear();+ async.elapse(_poll);+ expect(reads.states, 1);+ expect(reads.messageReads, 0);+ async.elapse(_poll * 4);+ expect(reads.messageReads, 0);+ c.dispose();+ });+ });++ test('still shows a reply that arrived since the last poll', () {+ fakeAsync((async) {+ final server = ConversationServer()..append('Hello');+ final reads = _Reads(server);+ final c = _controller(reads)..start();+ async.flushMicrotasks();+ server.append('A reply');+ async.elapse(_poll);+ expect(c.messages('lead').map((m) => m.text), ['Hello', 'A reply']);+ c.dispose();+ });+ });++ test('still shows a reaction that was made since the last poll', () {+ fakeAsync((async) {+ final server = ConversationServer()..append('Hello');+ final reads = _Reads(server);+ final c = _controller(reads)..start();+ async.flushMicrotasks();+ final id = c.messages('lead').single.id;+ // Another reader's reaction, as the backend keeps it.+ unawaited(+ server.request(+ 'POST',+ '/api/super-tabs/tab/commands',+ body: {+ 'operationId': 'react-1',+ 'command': {+ 'type': 'message.react',+ 'conversationId': 'lead',+ 'messageId': id,+ 'emoji': 'rocket',+ 'on': true,+ },+ },+ ),+ );+ async.flushMicrotasks();+ async.elapse(_poll);+ expect(c.messages('lead').single.reactions, isNotEmpty);+ c.dispose();+ });+ });++ test(+ 'keeps reading the messages while the own message awaits a receipt',+ () {+ fakeAsync((async) {+ final server = ConversationServer()..append('Hi');+ Map<String, dynamic> delivery(String status) => {+ 'id': 'd1',+ 'messageId': server.messages.last['id'],+ 'agentId': 'agent',+ 'status': status,+ };+ server.messages.last['deliveries'] = [delivery('queued')];+ final reads = _Reads(server);+ final c = _controller(reads)..start();+ async.flushMicrotasks();+ server.messages.last['deliveries'] = [delivery('answered')];+ async.elapse(_poll);+ expect(+ c.messages('lead').single.deliveries.single['status'],+ 'answered',+ );+ reads.clear();+ async.elapse(_poll);+ expect(reads.messageReads, 0);+ c.dispose();+ });+ },+ );++ test('reads the messages again after a read of them failed', () {+ fakeAsync((async) {+ final server = ConversationServer()..append('Hello');+ final reads = _Reads(server);+ final c = _controller(reads)..start();+ async.flushMicrotasks();+ server.append('A reply');+ server.failReads = true;+ async.elapse(_poll);+ server.failReads = false;+ async.elapse(_poll);+ expect(c.messages('lead').map((m) => m.text), ['Hello', 'A reply']);+ c.dispose();+ });+ });+ });++ group('a Swarm that is not the one in front', () {+ test('is read every 15 s, not every 3 s', () {+ fakeAsync((async) {+ final reads = _Reads(ConversationServer()..append('Hello'));+ final c = _controller(reads)..start();+ async.flushMicrotasks();+ c.away = true;+ reads.clear();+ async.elapse(const Duration(seconds: 14));+ expect(reads.states, 0);+ async.elapse(const Duration(seconds: 1));+ expect(reads.states, 1);+ async.elapse(const Duration(seconds: 15));+ expect(reads.states, 2);+ c.dispose();+ });+ });++ test('is read at once when it comes to the front, then every 3 s', () {+ fakeAsync((async) {+ final reads = _Reads(ConversationServer()..append('Hello'));+ final c = _controller(reads)..start();+ async.flushMicrotasks();+ c.away = true;+ async.elapse(const Duration(seconds: 10));+ reads.clear();+ c.away = false;+ async.flushMicrotasks();+ expect(reads.states, 1);+ async.elapse(_poll * 3);+ expect(reads.states, 4);+ c.dispose();+ });+ });++ test('does not read again when it returns within one poll of a read', () {+ fakeAsync((async) {+ final reads = _Reads(ConversationServer()..append('Hello'));+ final c = _controller(reads)..start();+ async.flushMicrotasks();+ c.away = true;+ async.elapse(const Duration(seconds: 1));+ reads.clear();+ c.away = false;+ async.flushMicrotasks();+ expect(reads.states, 0);+ c.dispose();+ });+ });++ // A tag is news for the badge and a notice: a push for an away Swarm is+ // read at the old pace (the 3 s gap), not held for the idle 15 s.+ test('shows a tag the server pushes within the old 3 s gap', () {+ fakeAsync((async) {+ final server = ConversationServer()..append('Hello');+ final reads = _Reads(server);+ final c = _controller(reads)..start();+ async.flushMicrotasks();+ c.pushUntil = clock.now().add(kSwarmPushLease);+ c.away = true;+ async.elapse(const Duration(seconds: 1));+ expect(c.snapshot!.mentionsWaiting, 0);+ server.tag('message-2');+ c.told(main: true);+ async.elapse(const Duration(seconds: 2));+ expect(c.snapshot!.mentionsWaiting, 1);+ c.dispose();+ });+ });++ test('is read when told, within 15 s while the server pushes', () {+ fakeAsync((async) {+ final server = ConversationServer()..append('Hello');+ final reads = _Reads(server);+ final c = _controller(reads)..start();+ async.flushMicrotasks();+ c.pushUntil = clock.now().add(kSwarmPushLease);+ c.away = true;+ async.elapse(const Duration(seconds: 1));+ reads.clear();+ server.append('A reply');+ c.told(main: true);+ async.elapse(const Duration(seconds: 15));+ expect(c.messages('lead').last.text, 'A reply');+ expect(reads.states, 1);+ c.dispose();+ });+ });+ });+}diff --git a/desktop/test/super_tab_quiet_requests_test.dart b/desktop/test/super_tab_quiet_requests_test.dartnew file mode 100644index 000000000..3a37bfa2a--- /dev/null+++ b/desktop/test/super_tab_quiet_requests_test.dart@@ -0,0 +1,160 @@+import 'package:fake_async/fake_async.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/super_tabs/client.dart';+import 'package:harness/super_tabs/reading.dart';++import 'support/super_tab_fixture.dart';+import 'swarm_state_test.dart' show MemoryStore;++/// Stability roadmap 2.5, the KPI: Desktop requests per person per minute,+/// counted by kind at the transport. One person in six Swarms: one on screen+/// (a message arrives in it every 30 s), two open behind it, three not+/// opened (one holds a tag waiting for them).+///+/// [_before] is what main measured with this same test before the change+/// (1a034eb26, 2026-10-29); each test holds the new count to its share of it.+const _ids = ['t1', 't2', 't3', 't4', 't5', 't6'];+const _window = Duration(minutes: 10);++/// Requests per minute on main, by scenario.+const _before = (pushOn: 19.1, pushOff: 194.1, background: 194.1);++class _Counts {+ final byKind = <String, int>{};+ int get total => byKind.values.fold(0, (a, b) => a + b);+ void add(String kind) => byKind[kind] = (byKind[kind] ?? 0) + 1;+ double perMinute() => total / _window.inMinutes;+ @override+ String toString() =>+ '${perMinute().toStringAsFixed(1)}/min ${(byKind.keys.toList()..sort()).map((k) => '$k ${(byKind[k]! / _window.inMinutes).toStringAsFixed(1)}').join(', ')}';+}++class _Backend {+ _Backend() {+ for (final id in _ids) {+ servers[id] = ConversationServer()+ ..state['id'] = id+ ..append('Hello');+ }+ // A tag waiting in a Swarm not opened.+ servers['t5']!.tag('message-1');+ }++ final servers = <String, ConversationServer>{};+ final counts = _Counts();+ bool counting = false;++ Future<Object?> call(+ String method,+ String path, {+ Map<String, dynamic>? body,+ }) async {+ final uri = Uri.parse(path);+ if (uri.path == '/api/super-tabs/list') {+ if (counting) counts.add('list');+ final asked = uri.queryParameters['mentions'] == '1';+ return {+ 'tabs': [+ for (final id in _ids)+ {+ 'id': id,+ 'name': id,+ if (asked) ...{+ 'mentionsWaiting': servers[id]!.mentions.length,+ 'mentionsDigest': 'd${servers[id]!.mentions.length}',+ },+ },+ ],+ 'next': null,+ };+ }+ final segments = uri.pathSegments;+ final route = segments[3];+ if (counting) {+ counts.add(+ route == 'parts' || route == 'changes'+ ? 'state'+ : route == 'conversations'+ ? 'messages'+ : route,+ );+ }+ return servers[segments[2]]!.request(method, path, body: body);+ }+}++/// Runs the scenario for [_window] and returns what was asked.+_Counts _measure({required bool pushing, required bool foreground}) {+ final backend = _Backend();+ late final _Counts result;+ fakeAsync((async) {+ final client = SuperTabClient(+ transport: backend.call,+ storage: MemoryStore(),+ onTabs: (_, _) {},+ )..reading = SuperTabReading.desktop;+ client+ ..bind('owner')+ ..show('t1')+ ..pageVisible = foreground;+ for (final id in ['t1', 't2', 't3']) {+ client.open(id);+ }+ void push() {+ if (pushing) client.swarmChanged({});+ }++ push();+ client.refreshTabs();+ async.elapse(const Duration(seconds: 30));+ backend+ ..counts.byKind.clear()+ ..counting = true;+ var elapsed = Duration.zero;+ while (elapsed < _window) {+ async.elapse(const Duration(seconds: 30));+ elapsed += const Duration(seconds: 30);+ backend.servers['t1']!.append('Update ${elapsed.inSeconds}');+ if (pushing) {+ client.swarmChanged({+ 'tabId': 't1',+ 'parts': ['main'],+ });+ }+ if (elapsed.inSeconds % 240 == 0) push();+ }+ result = backend.counts;+ client.dispose();+ });+ return result;+}++void main() {+ // Pushes are on in production: most of main's polls were already gone, and+ // what is left is the tag reads and the reads that found nothing new.+ test('the server pushes, the app in front: at most 55% of before', () {+ final counts = _measure(pushing: true, foreground: true);+ // ignore: avoid_print+ print('KPI push on, foreground: $counts (before ${_before.pushOn}/min)');+ expect(counts.perMinute(), lessThanOrEqualTo(_before.pushOn * 0.55));+ expect(counts.byKind['mentions'], isNull);+ });++ // The fallback, when a server does not push.+ test('no pushes, the app in front: at most 30% of before', () {+ final counts = _measure(pushing: false, foreground: true);+ // ignore: avoid_print+ print('KPI push off, foreground: $counts (before ${_before.pushOff}/min)');+ expect(counts.perMinute(), lessThanOrEqualTo(_before.pushOff * 0.3));+ expect(counts.byKind['mentions'], isNull);+ });++ test('no pushes, the app in the background: at most 10% of before', () {+ final counts = _measure(pushing: false, foreground: false);+ // ignore: avoid_print+ print(+ 'KPI push off, background: $counts (before ${_before.background}/min)',+ );+ expect(counts.perMinute(), lessThanOrEqualTo(_before.background * 0.1));+ });+}diff --git a/desktop/test/super_tab_reading_client_test.dart b/desktop/test/super_tab_reading_client_test.dartindex 5d6b01d13..c834ec697 100644--- a/desktop/test/super_tab_reading_client_test.dart+++ b/desktop/test/super_tab_reading_client_test.dart@@ -347,6 +347,8 @@ void main() {reading: SuperTabReading.desktop,storage: storage,)..bind('owner');+ // The Swarm in front polls every 3 s; one behind it only every 15 s.+ client.show('tab');client.open('tab').ignore();async.flushMicrotasks();client.release('tab');diff --git a/desktop/test/super_tab_reading_workspace_test.dart b/desktop/test/super_tab_reading_workspace_test.dartindex d723ad919..73413be2c 100644--- a/desktop/test/super_tab_reading_workspace_test.dart+++ b/desktop/test/super_tab_reading_workspace_test.dart@@ -111,27 +111,28 @@ Future<void> _mountApp(}void main() {- testWidgets('Desktop: a Swarm tab not shown keeps its 3 s poll', (- tester,- ) async {- final f = SuperTabLaunchFixture();- f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');- await _mount(tester, f);- final swarm = f.app.activeSwarmId;- f.app.newSwarm();- await tester.pump();- final before = _stateReads(f);- await tester.pump(const Duration(seconds: 30));- expect(_stateReads(f) - before, 10);- f.app.selectSwarm(swarm);- _hide(tester);- final hidden = _stateReads(f);- await tester.pump(const Duration(seconds: 30));- expect(_stateReads(f) - hidden, 10);- _reveal(tester);- await tester.pumpWidget(const SizedBox());- f.dispose();- });+ testWidgets(+ 'Desktop: a Swarm tab not shown, or a hidden app, polls every 15 s',+ (tester) async {+ final f = SuperTabLaunchFixture();+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');+ await _mount(tester, f);+ final swarm = f.app.activeSwarmId;+ f.app.newSwarm();+ await tester.pump();+ final before = _stateReads(f);+ await tester.pump(const Duration(seconds: 30));+ expect(_stateReads(f) - before, 2);+ f.app.selectSwarm(swarm);+ _hide(tester);+ final hidden = _stateReads(f);+ await tester.pump(const Duration(seconds: 30));+ expect(_stateReads(f) - hidden, 2);+ _reveal(tester);+ await tester.pumpWidget(const SizedBox());+ f.dispose();+ },+ );testWidgets('web: another tab or a hidden page stops the Swarm tab reading', (tester,