Skip to content

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.

Merge batch 11-02 1102-l: #2559 #2571 #2572 #2574 #2576 #2540 (#2580)

0xken152826547cbb18
diff --git a/backend/integration/superTabTeam.test.ts b/backend/integration/superTabTeam.test.ts
index 18b5b1b61..eee70b10d 100644
--- a/backend/integration/superTabTeam.test.ts
+++ b/backend/integration/superTabTeam.test.ts
@@ -158,6 +158,86 @@ describe('a team session hosting its own machine', () => {
})
})
+// Audit H2: Team-written code stays out of the main account, through the real store, and the mark survives a save and a load.
+describe('a task a Team agent worked on', () => {
+ const owners = async (tab: string, conversationId: string) => String((await run(tab, { type: 'agent.add', conversationId, machineId: 'owner-host',
+ harnessId: randomUUID(), name: 'Owner Reviewer', configuration: config, lead: false })).result.agentId)
+ const task = async (tab: string, title: string) => String((await run(tab, { type: 'conversation.create', projectId: 'lead', title, brief: 'Do it', checks: [] })).result.conversationId)
+ const step = async (tab: string, reviewOf: string) => String((await run(tab, { type: 'conversation.create', projectId: 'lead', title: 'Review', brief: 'Read it', reviewOf, step: 'Review', checks: [] })).result.conversationId)
+
+ it('keeps its mark through a save and a load, and refuses the main account\'s agent on its step', async () => {
+ const { tab, builder, teamGroup } = await fixture()
+ const free = await task(tab, 'Free')
+ const main = await owners(tab, free)
+ await run(tab, { type: 'work.assign', conversationId: teamGroup, agentId: builder })
+ expect((await storedState(tab)).conversations.find(c => c.id === teamGroup)?.teamWritten).toBe(true)
+ const review = await step(tab, teamGroup)
+ await expect(run(tab, { type: 'work.assign', conversationId: review, agentId: main })).rejects.toMatchObject({ code: 'TEAM_WRITTEN_WORK', status: 403 })
+ expect((await storedState(tab)).conversations.find(c => c.id === review)?.assignment ?? null).toBeNull()
+ })
+
+ it('takes GitHub\'s record through the store: a bot\'s push on a clean task\'s pull request marks it for good', async () => {
+ const { tab } = await fixture()
+ const clean = await task(tab, 'Owner work'), main = await owners(tab, clean), review = await step(tab, clean)
+ const read = vi.fn(async () => 'team' as const)
+ const asked = new SuperTabStore(db, Date.now, undefined, { pushOrigin: read })
+ const state = await storedState(tab)
+ state.conversations.find(c => c.id === clean)!.pullRequestUrls = ['https://github.com/acme/app/pull/7']
+ await saveState(tab, state)
+ await expect(asked.execute(owner, tab, { operationId: randomUUID(), command: { type: 'work.assign', conversationId: review, agentId: main } }))
+ .rejects.toMatchObject({ code: 'TEAM_WRITTEN_WORK' })
+ expect(read).toHaveBeenCalledWith(null, ['https://github.com/acme/app/pull/7'])
+ // The refusal rolled its command back, and the mark still stays: the same agent cannot be added right after.
+ expect((await storedState(tab)).conversations.find(c => c.id === clean)?.teamWritten).toBe(true)
+ await expect(run(tab, { type: 'conversation.agent', conversationId: review, agentId: main, present: true, lead: false })).rejects.toMatchObject({ code: 'TEAM_WRITTEN_WORK' })
+ await expect(run(tab, { type: 'work.assign', conversationId: review, agentId: main })).rejects.toMatchObject({ code: 'TEAM_WRITTEN_WORK' })
+ })
+
+ it('stores a mark set from a step on its task, and tells the main-account members in their own chats', async () => {
+ const { tab, builder } = await fixture()
+ const clean = await task(tab, 'Owner work'), main = await owners(tab, clean), review = await step(tab, clean)
+ const state = await storedState(tab)
+ state.conversations.find(c => c.id === clean)!.pullRequestUrls = ['https://github.com/acme/app/pull/9']
+ await saveState(tab, state)
+ const asked = new SuperTabStore(db, Date.now, undefined, { pushOrigin: async () => 'team' })
+ await asked.execute(owner, tab, { operationId: randomUUID(), command: { type: 'work.assign', conversationId: review, agentId: builder } })
+ expect((await storedState(tab)).conversations.find(c => c.id === clean)?.teamWritten).toBe(true)
+ const told = await db.superTabMessage.findMany({ where: { tabId: tab, conversationId: clean, text: { startsWith: 'Stop: GitHub shows' } } })
+ expect(told).toHaveLength(1)
+ expect(JSON.stringify(told[0])).toContain(main)
+ })
+
+ it('reads the pull request a step\'s brief names, and refuses the main account on a step that names none', async () => {
+ const { tab } = await fixture()
+ const state0 = await storedState(tab)
+ state0.projects!.find(p => p.id === 'lead')!.repository = { machineId: 'owner-host', cwd: '/repo', repositoryUrl: 'https://github.com/acme/app' }
+ await saveState(tab, state0)
+ const clean = await task(tab, 'Owner work'), main = await owners(tab, clean), bare = await step(tab, clean)
+ const named = String((await run(tab, { type: 'conversation.create', projectId: 'lead', title: 'Review', brief: 'Read PR #2500', reviewOf: clean, step: 'Review 2', checks: [] })).result.conversationId)
+ const read = vi.fn(async () => 'clean' as const)
+ const asked = new SuperTabStore(db, Date.now, undefined, { pushOrigin: read })
+ const assign = (conversationId: string) => asked.execute(owner, tab, { operationId: randomUUID(), command: { type: 'work.assign', conversationId, agentId: main } })
+ await expect(assign(bare)).rejects.toMatchObject({ code: 'TEAM_WRITTEN_WORK' })
+ expect(read).not.toHaveBeenCalled()
+ await expect(assign(named)).resolves.toBeTruthy()
+ expect(read).toHaveBeenCalledWith('https://github.com/acme/app', ['https://github.com/acme/app/pull/2500'])
+ })
+
+ it('refuses the main account while GitHub cannot say, and takes it once GitHub answers clean', async () => {
+ const { tab } = await fixture()
+ const clean = await task(tab, 'Owner work'), main = await owners(tab, clean), review = await step(tab, clean)
+ const state = await storedState(tab)
+ state.conversations.find(c => c.id === clean)!.pullRequestUrls = ['https://github.com/acme/app/pull/8']
+ await saveState(tab, state)
+ const answer = vi.fn<() => Promise<'unknown' | 'clean'>>().mockResolvedValueOnce('unknown').mockResolvedValueOnce('clean')
+ const asked = new SuperTabStore(db, Date.now, undefined, { pushOrigin: answer })
+ const assign = () => asked.execute(owner, tab, { operationId: randomUUID(), command: { type: 'work.assign', conversationId: review, agentId: main } })
+ await expect(assign()).rejects.toMatchObject({ code: 'TEAM_WRITTEN_WORK' })
+ expect((await storedState(tab)).conversations.find(c => c.id === clean)?.teamWritten).toBeUndefined()
+ await expect(assign()).resolves.toBeTruthy()
+ })
+})
+
describe('a team session speaking in a Swarm', () => {
it('reads and posts as an agent on its own machine', async () => {
const f = await fixture()
diff --git a/backend/integration/superTabTidy.test.ts b/backend/integration/superTabTidy.test.ts
index 307ffcd8d..2bbfe16c0 100644
--- a/backend/integration/superTabTidy.test.ts
+++ b/backend/integration/superTabTidy.test.ts
@@ -279,8 +279,9 @@ describe('a review nobody reviews', () => {
await ready(`Ready: yes, revision abc..def. ${PR}`)
const opened = String((await f.execute({ type: 'conversation.create', title: 'Review: Parser v2', brief: `Review ${PR} against the task.`,
reviewOf: reviewed, checks: [{ description: 'Verdict', independent: false }] }, host, builder)).result.conversationId)
+ let reviewer = ''
if (withReviewer) {
- const reviewer = await f.add('lead', 'test-host', randomUUID(), 'Reviewer')
+ reviewer = await f.add('lead', 'test-host', randomUUID(), 'Reviewer')
await f.execute({ type: 'work.assign', conversationId: opened, agentId: reviewer }, host, builder)
}
const reviews = async () => (await db.swarmGroup.findMany({ where: { tabId: f.tab, deleted: false } }))
@@ -289,7 +290,7 @@ describe('a review nobody reviews', () => {
const closeLines = async () => (await db.superTabMessage.findMany({ where: { tabId: f.tab, conversationId: review.key } }))
.filter(m => (m.source as { kind?: string } | null)?.kind === 'auto-archive')
const isArchived = async () => (await db.swarmGroup.findUniqueOrThrow({ where: { id: review.id } })).archived
- return { ...f, reviewed, builder, work, ready, reviews, review, closeLines, isArchived }
+ return { ...f, reviewed, builder, work, ready, reviews, review, closeLines, isArchived, reviewer }
}
// Task steps design (#2511): a review is a step of the work it reviews and archives with that task, never on its own clock,
@@ -328,14 +329,111 @@ describe('a review nobody reviews', () => {
expect(await f.isArchived()).toBe(false)
})
- it('is found once the worker marks it at startup when it was written before reviews took the mark', async () => {
+ /** The Reviewer's verdict: its step done, with its check recorded. */
+ async function verdict(f: Awaited<ReturnType<typeof waiting>>) {
+ const row = await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: f.review.key } })
+ const data = row.data as { assignment: { id: string }; checks: Array<{ id: string }> }
+ for (const check of data.checks) {
+ await f.execute({ type: 'work.check', conversationId: f.review.key, assignmentId: data.assignment.id, checkId: check.id, passed: true, evidence: 'Read it' }, host, f.reviewer)
+ }
+ await f.execute({ type: 'work.status', conversationId: f.review.key, assignmentId: data.assignment.id, status: 'done', result: 'Passed at def' }, host, f.reviewer)
+ }
+ const marked = async (f: { tab: string }, key: string) => (await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key } })).workFinished
+
+ // Task steps design (#2511), found in #2544's review: an archived step refuses the re-check, which then fails silently.
+ it('a step that finished is not archived after a worker restart while its task is open, and takes a second round', async () => {
+ const f = await waiting(true)
+ await verdict(f)
+ await markFinishedGroups(db)
+ expect(await marked(f, f.review.key)).toBe(false)
+ f.clock.now += 40 * MINUTE
+ await archiveFinishedGroups(db, f.timed, github({ [PR]: 'merged' }), f.clock.now)
+ expect(await f.isArchived()).toBe(false)
+ await f.execute({ type: 'work.assign', conversationId: f.review.key, agentId: f.reviewer }, host, f.builder)
+ expect(((await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: f.review.key } })).data as { assignment: { status: string } }).assignment.status).toBe('working')
+ })
+
+ it('a step nobody holds is not marked at a worker restart while its task is open', async () => {
const f = await waiting()
await db.swarmGroup.update({ where: { id: f.review.id }, data: { workFinished: false } })
+ await markFinishedGroups(db)
+ expect(await marked(f, f.review.key)).toBe(false)
f.clock.now += 40 * MINUTE
await archiveFinishedGroups(db, f.timed, github({ [PR]: 'merged' }), f.clock.now)
expect(await f.isArchived()).toBe(false)
- expect(await markFinishedGroups(db)).toBeGreaterThanOrEqual(1)
+ })
+
+ it('a mark an earlier startup left on a step of an open task is taken back, and the pass would not act on it anyway', async () => {
+ const f = await waiting(true)
+ await verdict(f)
+ await db.swarmGroup.update({ where: { id: f.review.id }, data: { workFinished: true } })
+ f.clock.now += 40 * MINUTE
+ // The mark left by the release before this one, read by a pass before the worker's startup clears it. The pass does not
+ // even ask for the write, which would refuse by itself (below).
+ const archiveFinished = vi.fn(async () => false)
+ await archiveFinishedGroups(db, { archiveFinished }, github({ [PR]: 'merged' }), f.clock.now)
+ expect(archiveFinished.mock.calls.filter(call => (call as unknown[])[1] === f.review.key)).toEqual([])
await archiveFinishedGroups(db, f.timed, github({ [PR]: 'merged' }), f.clock.now)
+ expect(await f.isArchived()).toBe(false)
+ await markFinishedGroups(db)
+ expect(await marked(f, f.review.key)).toBe(false)
+ })
+
+ it('the write itself refuses a step whose task is open, or a task it was not told to read', async () => {
+ const f = await waiting(true)
+ await verdict(f)
+ f.clock.now += 40 * MINUTE
+ // As if the pass read the task done, and the task was handed on again before this write.
+ expect(await f.timed.archiveFinished(f.tab, f.review.key, { [PR]: 'merged' }, f.reviewed)).toBe(false)
+ expect(await f.timed.archiveFinished(f.tab, f.review.key, { [PR]: 'merged' })).toBe(false)
+ expect(await f.isArchived()).toBe(false)
+ })
+
+ // Forced by a security review of #2572: the other write commits after this one loaded the task and before it saved.
+ it('a task handed on while the write runs keeps its step: the touch on the task makes the write retry and decline', async () => {
+ const f = await waiting(true)
+ await verdict(f)
+ await f.execute({ type: 'work.cancel', conversationId: f.reviewed, assignmentId: f.work, reason: 'Landed outside the Swarm' }, host, f.lead)
+ f.clock.now += 40 * MINUTE
+ const store = f.timed as unknown as { save: (...args: unknown[]) => Promise<unknown> }
+ const save = store.save
+ let raced = false
+ store.save = async function (this: unknown, ...args: unknown[]) {
+ if (!raced) {
+ raced = true
+ await f.execute({ type: 'work.assign', conversationId: f.reviewed, agentId: f.builder })
+ }
+ return save.apply(this, args)
+ }
+ try {
+ expect(await f.timed.archiveFinished(f.tab, f.review.key, { [PR]: 'merged' }, f.reviewed)).toBe(false)
+ } finally { store.save = save }
+ expect(raced).toBe(true)
+ expect(await f.isArchived()).toBe(false)
+ expect(((await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: f.reviewed } })).data as { assignment: { status: string } }).assignment.status).toBe('working')
+ })
+
+ it('is marked at a worker restart once its task ended, and archives then alone only when the task\'s pull requests are settled', async () => {
+ const SECOND = 'https://github.com/example/parser/pull/10'
+ const f = await waiting(true)
+ await verdict(f)
+ // Linked to the task alone: the step's own brief names only the first.
+ await f.execute({ type: 'message.send', conversationId: f.reviewed, text: `Follow-up: ${SECOND}`, replyTo: null, recipientIds: [] })
+ await f.execute({ type: 'work.cancel', conversationId: f.reviewed, assignmentId: f.work, reason: 'Landed outside the Swarm' }, host, f.lead)
+ expect(await marked(f, f.review.key)).toBe(false)
+ expect(await markFinishedGroups(db)).toBeGreaterThanOrEqual(1)
+ expect(await marked(f, f.review.key)).toBe(true)
+ f.clock.now += 40 * MINUTE
+ // The task's other pull request is still open: neither the pass nor the write takes its step.
+ const archiveFinished = vi.fn(async () => false)
+ await archiveFinishedGroups(db, { archiveFinished }, github({ [PR]: 'merged', [SECOND]: 'open' }), f.clock.now)
+ expect(archiveFinished.mock.calls.filter(call => (call as unknown[])[1] === f.review.key)).toEqual([])
+ expect(await f.timed.archiveFinished(f.tab, f.review.key, { [PR]: 'merged' }, f.reviewed)).toBe(false)
+ await archiveFinishedGroups(db, f.timed, github({ [PR]: 'merged', [SECOND]: 'open' }), f.clock.now)
+ expect(await f.isArchived()).toBe(false)
+ // A task archived before steps archived with it, so only its step is left to the pass.
+ await db.swarmGroup.updateMany({ where: { tabId: f.tab, key: f.reviewed }, data: { archived: true, workFinished: false } })
+ await archiveFinishedGroups(db, f.timed, github({ [PR]: 'merged', [SECOND]: 'merged' }), f.clock.now)
expect(await f.isArchived()).toBe(true)
})
diff --git a/backend/src/github/app.test.ts b/backend/src/github/app.test.ts
index 9f1944233..d910ce14f 100644
--- a/backend/src/github/app.test.ts
+++ b/backend/src/github/app.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from 'vitest'
import { ACTIONS_READ_PERMISSIONS, CI_LOAD_TTL_MS, CI_MAX_CALLS, CI_MAX_RUNS, CI_READS_PER_HOUR, CI_STALE_MS, SERVER_PROCESSES_MAX, cacheSecret, githubAppConfig, GitHubAppError, PULL_READ_PERMISSIONS, readPrivateKey, TOKEN_PERMISSIONS } from './app.js'
import { FAKE_API, fakeApp, fakeGitHub, throwawayKey } from './fakeGitHub.js'
import { githubRepository } from './repository.js'
+import { GitHubApp } from './app.js'
const key = throwawayKey()
const repo = githubRepository('https://github.com/acme/app')!
@@ -414,3 +415,57 @@ describe('the CI load', () => {
expect([...(app as unknown as { ciReads: Map<string, unknown> }).ciReads.keys()]).toEqual(['acme/app', 'acme/fresh'])
})
})
+
+describe('who pushed a pull request, through the app', () => {
+ const head = 'head-sha'
+ const fixture = (first = { after: head, actor: { login: 'ken', type: 'User' }, timestamp: '2026-11-02T08:00:00Z' }) => {
+ const { privateKey, publicKey } = throwawayKey()
+ let now = Date.parse('2026-11-02T09:00:00Z')
+ const github = fakeGitHub({ publicKey, appId: '7', now: () => now })
+ github.installed.set('acme/app', 1)
+ const paths: string[] = []
+ let activity: 'answer' | 'fail' = 'answer'
+ const sha = head
+ const fetch: typeof github.fetch = async (input, init) => {
+ const url = new URL(String(input))
+ if (!/\/repos\/acme\/app\/pulls|\/activity$/.test(url.pathname)) return github.fetch(input, init)
+ paths.push(url.pathname + url.search)
+ const json = (body: unknown, headers: Record<string, string> = {}) => new Response(JSON.stringify(body), { status: 200, headers })
+ if (url.pathname.endsWith('/commits')) return json([{ sha: head, commit: { author: { email: '[email protected]' }, committer: { email: '[email protected]' } } }])
+ if (url.pathname.endsWith('/activity')) {
+ if (activity === 'fail') return new Response('{}', { status: 502 })
+ if (url.searchParams.get('actor')) return json([])
+ return url.searchParams.get('after') ? json([first]) : json([], { link: `<https://api.github.com/repositories/1/activity?ref=fix&per_page=100&after=abc>; rel="next"` })
+ }
+ return json({ head: { sha, ref: 'fix', repo: { full_name: 'acme/app' } }, created_at: '2026-11-02T07:00:00Z' })
+ }
+ const app = new GitHubApp({ appId: '7', privateKey, slug: 'harness-fixture' }, { fetch, apiUrl: FAKE_API, now: () => now })
+ return { app, paths, fail: (down: boolean) => { activity = down ? 'fail' : 'answer' }, pass: (ms: number) => { now += ms } }
+ }
+ const repository = githubRepository('https://github.com/acme/app')!
+
+ it('asks for its own bot by login, follows the log\'s next link, and reads the pull request once, so a push in between files nothing under another commit', async () => {
+ const f = fixture()
+ expect(await f.app.pushOrigin(repository, 7)).toBe('clean')
+ expect(f.paths.filter(p => /\/pulls\/7$/.test(p))).toHaveLength(1)
+ expect(f.paths.some(p => p.includes(`actor=${encodeURIComponent('harness-fixture[bot]')}`))).toBe(true)
+ expect(f.paths.some(p => p.includes('after=abc'))).toBe(true)
+ })
+
+ it('keeps an answer for a head, and asks again after a minute when GitHub could not say', async () => {
+ const f = fixture()
+ f.fail(true)
+ expect(await f.app.pushOrigin(repository, 7)).toBe('unknown')
+ const logReads = () => f.paths.filter(p => p.includes('/activity')).length, once = logReads()
+ expect(await f.app.pushOrigin(repository, 7)).toBe('unknown')
+ expect(logReads()).toBe(once)
+ f.pass(61_000)
+ f.fail(false)
+ expect(await f.app.pushOrigin(repository, 7)).toBe('clean')
+ expect(logReads()).toBeGreaterThan(once)
+ const settled = logReads()
+ f.pass(3_600_000)
+ expect(await f.app.pushOrigin(repository, 7)).toBe('clean')
+ expect(logReads()).toBe(settled)
+ })
+})
diff --git a/backend/src/github/app.ts b/backend/src/github/app.ts
index 61b96c14e..97e35bf5f 100644
--- a/backend/src/github/app.ts
+++ b/backend/src/github/app.ts
@@ -7,6 +7,7 @@
* crypto signs the app's JWT. Nothing here logs a token or the private key.
*/
import { createPrivateKey, hkdfSync, sign, type KeyObject } from 'node:crypto'
+import { readPushOrigin, type GitHubRead, type PushOrigin } from './pushOrigin.js'
import { githubRepository, type GitHubRepository } from './repository.js'
/** What a Swarm agent's token may do, and nothing more: push to and read the repository, open and update pull requests,
@@ -18,6 +19,10 @@ export const PREPARE_PERMISSIONS = { contents: 'read', metadata: 'read' } as con
export const PULL_READ_PERMISSIONS = { pull_requests: 'read', metadata: 'read' } as const
/** What the route's read of running CI jobs may do: read workflow runs and their jobs, nothing more. */
export const ACTIONS_READ_PERMISSIONS = { actions: 'read', metadata: 'read' } as const
+/** What reading who pushed a pull request's commits may do (pushOrigin.ts): read the pull request and the repository's activity log. */
+export const PUSH_ORIGIN_PERMISSIONS = { contents: 'read', pull_requests: 'read', metadata: 'read' } as const
+const PUSH_ORIGINS_KEPT = 1000
+const PUSH_UNKNOWN_MS = 60_000
export type TokenPermissions = Readonly<Record<string, 'read' | 'write'>>
/** Jobs running and waiting on a repository's GitHub Actions, in all and on macOS runners: counts only. */
export interface CiLoad { running: number; queued: number; macosRunning: number; macosQueued: number }
@@ -123,6 +128,7 @@ export class GitHubApp {
private readonly shownNames = new Map<string, { name: string; until: number }>()
/** Each repository's CI load while fresh, or being read ([ciLoad]), by its name in lower case; per server process. */
private readonly ciLoads = new Map<string, { value: Promise<CiLoad | null>; until: number }>()
+ private readonly pushOrigins = new Map<string, { origin: PushOrigin; until: number }>()
/** Each repository's CI reads in the last hour, and its last load read, for [CI_READS_PER_HOUR]. */
private readonly ciReads = new Map<string, { at: number[]; last: { load: CiLoad | null; at: number } | null }>()
/** When each repository's "not installed" was last forgotten on request ([forget]). */
@@ -188,7 +194,7 @@ export class GitHubApp {
return jwt
}
- private async call(method: string, path: string, auth: string | null, body?: unknown): Promise<{ status: number; body: Record<string, unknown> | unknown[] }> {
+ private async call(method: string, path: string, auth: string | null, body?: unknown): Promise<{ link?: string | null; status: number; body: Record<string, unknown> | unknown[] }> {
let response: Response
try {
response = await this.fetch(`${this.apiUrl}${path}`, {
@@ -203,7 +209,8 @@ export class GitHubApp {
const text = await response.text().catch(() => '')
let parsed: unknown = {}
try { parsed = text ? JSON.parse(text) : {} } catch { parsed = {} }
- return { status: response.status, body: parsed && typeof parsed === 'object' ? parsed as Record<string, unknown> : {} }
+ return { status: response.status, body: parsed && typeof parsed === 'object' ? parsed as Record<string, unknown> : {},
+ link: response.headers.get('link') }
}
private misconfigured(): GitHubAppError {
@@ -374,6 +381,59 @@ export class GitHubApp {
return value
}
+ /**
+ * Who pushed the pull request [number]'s commits (pushOrigin.ts), remembered by its head alone. A failure never reads as clean.
+ */
+ async pushOrigin(repository: GitHubRepository, number: number): Promise<PushOrigin> {
+ try {
+ const resolved = await this.resolve(repository)
+ if (!resolved) return 'unknown'
+ const { token } = await this.createToken(resolved.installation, resolved.repository, PUSH_ORIGIN_PERMISSIONS)
+ const auth = `Bearer ${token}`, name = `${resolved.repository.owner}/${resolved.repository.name}`
+ const call: GitHubRead = async path => {
+ const answer = await this.call('GET', path, auth)
+ const next = /<https:\/\/[^/>]+(\/[^>]+)>;\s*rel="next"/.exec(answer.link ?? '')?.[1]
+ return { status: answer.status, body: answer.body, ...(next ? { next } : {}) }
+ }
+ const pullPath = `/repos/${name}/pulls/${number}`
+ const pull = await call(pullPath)
+ const sha = (pull.body as { head?: { sha?: unknown } }).head?.sha
+ const key = typeof sha === 'string' ? `${name.toLowerCase()}@${sha}` : null
+ const known = key ? this.pushOrigins.get(key) : undefined
+ if (known && known.until > this.now()) return known.origin
+ // The same read of the pull request decides the head and the answer, so a push in between cannot file it under another commit.
+ const read: GitHubRead = path => path === pullPath ? Promise.resolve(pull) : call(path)
+ const identity = await this.commitIdentity(token)
+ const bot = /\+([^@]+\[bot\])@/.exec(identity?.email ?? '')?.[1] ?? null
+ const origin = await readPushOrigin(read, name, number, bot)
+ if (key) {
+ if (this.pushOrigins.size >= PUSH_ORIGINS_KEPT) this.pushOrigins.delete(this.pushOrigins.keys().next().value!)
+ // An answer for a head holds for good. An `unknown` is asked again a minute later, so retries cost no more than that.
+ this.pushOrigins.set(key, { origin, until: origin === 'unknown' ? this.now() + PUSH_UNKNOWN_MS : Infinity })
+ }
+ return origin
+ } catch {
+ return 'unknown'
+ }
+ }
+
+ /** Who pushed [branch]: the default branch is clean, as it passed review; any other reads its one open pull request, and with none is unknown. */
+ async branchOrigin(repository: GitHubRepository, branch: string): Promise<PushOrigin> {
+ try {
+ const resolved = await this.resolve(repository)
+ if (!resolved) return 'unknown'
+ const { token } = await this.createToken(resolved.installation, resolved.repository, PUSH_ORIGIN_PERMISSIONS)
+ const auth = `Bearer ${token}`, { owner, name } = resolved.repository
+ const about = await this.call('GET', `/repos/${owner}/${name}`, auth)
+ if (about.status === 200 && (about.body as { default_branch?: unknown }).default_branch === branch) return 'clean'
+ const listed = await this.call('GET', `/repos/${owner}/${name}/pulls?state=open&head=${encodeURIComponent(`${owner}:${branch}`)}&per_page=2`, auth)
+ const number = Array.isArray(listed.body) && listed.body.length === 1 ? (listed.body[0] as { number?: unknown }).number : null
+ return listed.status === 200 && typeof number === 'number' ? await this.pushOrigin(repository, number) : 'unknown'
+ } catch {
+ return 'unknown'
+ }
+ }
+
private async readCiLoad(repository: GitHubRepository): Promise<CiLoad | null> {
const resolved = await this.resolve(repository)
if (!resolved) return null
diff --git a/backend/src/github/pushOrigin.test.ts b/backend/src/github/pushOrigin.test.ts
new file mode 100644
index 000000000..fb27e4a9c
--- /dev/null
+++ b/backend/src/github/pushOrigin.test.ts
@@ -0,0 +1,109 @@
+import { describe, expect, it } from 'vitest'
+import { pullRequestsIn, readPushOrigin, type GitHubRead } from './pushOrigin.js'
+
+const BOT = 'harness-for-acme[bot]', REPO = 'acme/app', HEAD = 'head-sha', BASE_COMMIT = 'older-sha'
+const person = { login: 'ken', type: 'User' }, bot = { login: 'harness-for-acme[bot]', type: 'Bot' }
+const commit = (sha: string, email = '[email protected]', author: unknown = person) => ({ sha, author, committer: person,
+ commit: { author: { email }, committer: { email: '[email protected]' } } })
+const push = (after: string, actor: unknown = person, timestamp = '2026-11-02T08:00:00Z') => ({ id: 1, after, actor, timestamp })
+const pull = { head: { sha: HEAD, ref: 'fix', repo: { full_name: REPO } }, created_at: '2026-11-02T07:00:00Z' }
+
+/** A fake GitHub of one pull request, its commits and pages of its activity log, filtered by actor or by ref as GitHub does. */
+const github = (options: { pull?: unknown; commits?: unknown[]; activity?: unknown[][]; failing?: RegExp } = {}): GitHubRead => async path => {
+ if (options.failing?.test(path)) return { status: 502, body: {} }
+ if (path.includes('/commits')) return { status: 200, body: options.commits ?? [commit(HEAD), commit(BASE_COMMIT)] }
+ if (path.includes('/activity')) {
+ const pages = options.activity ?? [[push(HEAD), push(BASE_COMMIT)]]
+ const query = new URLSearchParams(path.split('?')[1])
+ const actor = query.get('actor')
+ const shown = pages.map(page => page.filter(e => !actor || (e as { actor?: { login?: string } | null }).actor?.login === actor))
+ .filter((page, index) => page.length || index === 0)
+ const page = Number(query.get('after') ?? 0)
+ return { status: 200, body: shown[page] ?? [], ...(page + 1 < shown.length ? { next: `/repos/${REPO}/activity?${actor ? `actor=${encodeURIComponent(actor)}&` : ''}${query.get('ref') ? `ref=${query.get('ref')}&` : ''}per_page=100&after=${page + 1}` } : {}) }
+ }
+ return { status: 200, body: options.pull ?? pull }
+}
+const origin = (options: Parameters<typeof github>[0] = {}) => readPushOrigin(github(options), REPO, 7, BOT)
+
+describe('who pushed a pull request', () => {
+ it('reads clean only when a person pushed its head and no bot pushed any of its commits', async () => {
+ expect(await origin()).toBe('clean')
+ })
+
+ it('reads team when a bot pushed its head', async () => {
+ expect(await origin({ activity: [[push(HEAD, bot)]] })).toBe('team')
+ })
+
+ it('reads team for a batch branch: a person pushed its head, a bot pushed a commit inside it', async () => {
+ expect(await origin({ activity: [[push(HEAD), push(BASE_COMMIT, bot)]] })).toBe('team')
+ })
+
+ it('finds a bot\'s push on a later page', async () => {
+ expect(await origin({ activity: [[push(HEAD), ...Array(99).fill(push('other'))], [push(BASE_COMMIT, bot)]] })).toBe('team')
+ })
+
+ it('does not take a forged author as clean: the log names the bot whatever the commit says', async () => {
+ expect(await origin({ commits: [commit(HEAD, '[email protected]', person)], activity: [[push(HEAD, bot)]] })).toBe('team')
+ })
+
+ it('reads team on a Team account\'s or a bot\'s commit address and author', async () => {
+ expect(await origin({ commits: [commit(HEAD, '[email protected]')] })).toBe('team')
+ expect(await origin({ commits: [commit(HEAD, '42+harness[bot]@users.noreply.github.com')] })).toBe('team')
+ expect(await origin({ commits: [commit(HEAD, '[email protected]', bot)] })).toBe('team')
+ })
+
+ it('reads unknown when the log does not show who pushed its head, or names nobody', async () => {
+ expect(await origin({ activity: [[push('other')]] })).toBe('unknown')
+ expect(await origin({ activity: [[push(HEAD, null)]] })).toBe('unknown')
+ })
+
+ it('reads unknown for a fork, whose pushes this log never shows', async () => {
+ expect(await origin({ pull: { ...pull, head: { sha: HEAD, ref: 'fix', repo: { full_name: 'mallory/app' } } } })).toBe('unknown')
+ expect(await origin({ pull: { ...pull, head: { sha: HEAD, ref: 'fix', repo: null } } })).toBe('unknown')
+ })
+
+ it('reads unknown on any failed read, never clean', async () => {
+ for (const failing of [/\/pulls\/7$/, /\/commits/, /\/activity/]) expect(await origin({ failing }), String(failing)).toBe('unknown')
+ expect(await readPushOrigin(async () => { throw new Error('down') }, REPO, 7, BOT)).toBe('unknown')
+ })
+
+ it('reads unknown on a page limit: too many commits, or a log too long to reach the start', async () => {
+ expect(await origin({ commits: Array.from({ length: 100 }, (_, i) => commit(i ? `c${i}` : HEAD)) })).toBe('unknown')
+ expect(await origin({ activity: Array.from({ length: 25 }, () => [push('other', bot)]) })).toBe('unknown')
+ })
+
+ it('reads back past the pull request\'s week to its oldest commit: a batch opened today holds a Team push from weeks ago', async () => {
+ const dated = (sha: string, date: string) => ({ sha, author: person, committer: person, commit: { author: { email: '[email protected]' }, committer: { email: '[email protected]', date } } })
+ const commits = [dated(HEAD, '2026-11-02T06:00:00Z'), dated(BASE_COMMIT, '2026-10-01T00:00:00Z')]
+ const late = push('other', bot, '2026-10-20T00:00:00Z')
+ expect(await origin({ commits, activity: [[push(HEAD), late], [push(BASE_COMMIT, bot, '2026-10-02T00:00:00Z')]] })).toBe('team')
+ })
+
+ it('names the pull requests a brief speaks of, in this repository only', () => {
+ expect(pullRequestsIn('Review PR #2500 and pull request #12, not #7, and https://github.com/acme/app/pull/9 or https://github.com/other/app/pull/4', 'https://github.com/acme/app'))
+ .toEqual(['https://github.com/acme/app/pull/9', 'https://github.com/other/app/pull/4', 'https://github.com/acme/app/pull/2500', 'https://github.com/acme/app/pull/12'])
+ expect(pullRequestsIn('Review PR #2500', null)).toEqual([])
+ })
+
+ it('reads clean on a busy repository: thousands of people\'s pushes do not hide the head, and only the bot\'s are walked', async () => {
+ const busy = Array.from({ length: 30 }, () => Array(100).fill(push('other')))
+ const paths: string[] = []
+ const counted: GitHubRead = async path => { paths.push(path); return github({ activity: [[push(HEAD)], ...busy] })(path) }
+ expect(await readPushOrigin(counted, REPO, 7, BOT)).toBe('clean')
+ expect(paths.filter(p => p.includes('/activity')).length).toBeLessThan(5)
+ expect(paths.some(p => p.includes(`actor=${encodeURIComponent(BOT)}`))).toBe(true)
+ expect(paths.some(p => p.includes('ref=fix'))).toBe(true)
+ })
+
+ it('stops reading the bot\'s pushes once they are a week older than the pull request', async () => {
+ let reads = 0
+ const log = [[push(HEAD), push('recent', bot)], [push('old', bot, '2026-10-01T00:00:00Z')], [push('older', bot)]]
+ const counted: GitHubRead = async path => { if (path.includes('actor=')) reads++; return github({ activity: log })(path) }
+ expect(await readPushOrigin(counted, REPO, 7, BOT)).toBe('clean')
+ expect(reads).toBe(2)
+ })
+
+ it('reads unknown when the app\'s own login is not known: the bot\'s pushes cannot be asked for', async () => {
+ expect(await readPushOrigin(github(), REPO, 7, null)).toBe('unknown')
+ })
+})
diff --git a/backend/src/github/pushOrigin.ts b/backend/src/github/pushOrigin.ts
new file mode 100644
index 000000000..f238b3610
--- /dev/null
+++ b/backend/src/github/pushOrigin.ts
@@ -0,0 +1,132 @@
+/**
+ * Who pushed a pull request's commits (audit H2, docs/plans/2026-11-02-team-written-branch-plan.md). A Team agent pushes with
+ * the Harness GitHub App's token, and GitHub's activity log names each push's actor, which the pusher cannot write. A commit's
+ * author can be written by anyone, so it can show a branch is Team-written, and never that it is clean.
+ *
+ * `clean` needs proof: a person's push of the head, and no bot's push among its commits. Anything GitHub cannot show is
+ * `unknown`, which callers treat as Team-written. The answer is the verdict alone: no name, branch or title.
+ */
+import { githubRepository, type GitHubRepository } from './repository.js'
+
+export type PushOrigin = 'clean' | 'team' | 'unknown'
+
+/** One GET: `next` is the following page's path from GitHub's Link header, when there is one. */
+export type GitHubRead = (path: string) => Promise<{ status: number; body: unknown; next?: string }>
+
+/** The pull requests [text] speaks of: its links, and "PR #N" or "pull request #N" of this project's repository. A bare "#N" may be a task's number, so it is left out. */
+export function pullRequestsIn(text: string, repositoryUrl: string | null): string[] {
+ const links = [...text.matchAll(/https:\/\/github\.com\/[A-Za-z0-9_-]+\/[A-Za-z0-9_.-]+\/pull\/[1-9][0-9]*\b/g)].map(m => m[0])
+ const repository = githubRepository(repositoryUrl)
+ if (!repository) return [...new Set(links)]
+ const named = [...text.matchAll(/\b(?:PR|pull request)\s*#([1-9][0-9]*)\b/gi)].map(m => `https://github.com/${repository.fullName}/pull/${m[1]}`)
+ return [...new Set([...links, ...named])]
+}
+
+/**
+ * The worst answer among [urls], for the Swarm's store. Only pull requests of the project's own repository are read: a link
+ * to another repository can never add or clear a mark, and a task with no such link has nothing to read.
+ */
+export const projectPushOrigin = (app: { pushOrigin(repository: GitHubRepository, number: number): Promise<PushOrigin> }) =>
+ async (repositoryUrl: string | null, urls: string[]): Promise<PushOrigin> => {
+ const repository = githubRepository(repositoryUrl)
+ if (!repository) return 'unknown'
+ const own = urls.flatMap(url => {
+ const match = /^https:\/\/github\.com\/([^/]+\/[^/]+)\/pull\/(\d+)$/.exec(url)
+ return match && match[1]!.toLowerCase() === repository.fullName.toLowerCase() ? [Number(match[2])] : []
+ })
+ const answers = await Promise.all(own.slice(0, MAX_PULLS).map(number => app.pushOrigin(repository, number)))
+ return answers.includes('team') ? 'team' : answers.includes('unknown') || own.length > MAX_PULLS ? 'unknown' : 'clean'
+ }
+
+export const projectBranchOrigin = (app: { branchOrigin(repository: GitHubRepository, branch: string): Promise<PushOrigin> }) =>
+ async (repositoryUrl: string | null, branch: string): Promise<PushOrigin> => {
+ const repository = githubRepository(repositoryUrl)
+ return repository ? app.branchOrigin(repository, branch) : 'unknown'
+ }
+
+const MAX_PULLS = 5
+const MAX_PR_COMMITS = 250
+const COMMIT_PAGES = 3
+const REF_PAGES = 3
+const ACTIVITY_PAGES = 20
+/** How long before a pull request opened its commits may have been pushed, for the log's scan to stop. */
+const BEFORE_PULL_MS = 7 * 24 * 3_600_000
+const TEAM_ADDRESS = /\[bot\]@|^harnessteam@/i
+
+type Json = Record<string, unknown>
+const object = (value: unknown): Json => value && typeof value === 'object' ? value as Json : {}
+const isBot = (user: unknown): boolean => {
+ const { type, login } = object(user)
+ return type === 'Bot' || (typeof login === 'string' && login.endsWith('[bot]'))
+}
+
+/**
+ * Reads the pull request [number] of `owner/name` [repository] through [read]. A failed or partial read is `unknown`.
+ * [bot] is the app's own login. The whole log is too long to walk: 2,000 events reached 3.3 days on this project's repository
+ * (review 1 of #2559). So it asks two narrow questions: who pushed this branch's head, and which of this pull request's
+ * commits the app's bot ever pushed, on any branch.
+ */
+export async function readPushOrigin(read: GitHubRead, repository: string, number: number, bot: string | null): Promise<PushOrigin> {
+ const base = `/repos/${repository}`
+ if (!bot) return 'unknown'
+ try {
+ const pull = await read(`${base}/pulls/${number}`)
+ if (pull.status !== 200) return 'unknown'
+ const head = object(object(pull.body).head), created = Date.parse(String(object(pull.body).created_at))
+ const headRepository = object(head.repo).full_name
+ // A fork's pushes are not in this repository's log.
+ if (typeof headRepository !== 'string' || headRepository.toLowerCase() !== repository.toLowerCase()
+ || typeof head.sha !== 'string' || typeof head.ref !== 'string' || !Number.isFinite(created)) return 'unknown'
+
+ const commits: Json[] = []
+ for (let page = 1; page <= COMMIT_PAGES; page++) {
+ const answer = await read(`${base}/pulls/${number}/commits?per_page=100&page=${page}`)
+ if (answer.status !== 200 || !Array.isArray(answer.body)) return 'unknown'
+ commits.push(...answer.body.map(object))
+ if (answer.body.length < 100) break
+ }
+ if (!commits.length || commits.length >= MAX_PR_COMMITS) return 'unknown'
+ const shas = new Set(commits.map(c => c.sha))
+ if (!shas.has(head.sha)) return 'unknown'
+ let oldest = created
+ for (const commit of commits) {
+ const detail = object(commit.commit)
+ if (isBot(commit.author) || isBot(commit.committer)) return 'team'
+ if ([object(detail.author).email, object(detail.committer).email].some(email => typeof email === 'string' && TEAM_ADDRESS.test(email))) return 'team'
+ // Only ever widens the scan. A batch opened today holds commits pushed weeks ago; a forged later date changes nothing here.
+ const date = Date.parse(String(object(detail.committer).date))
+ if (Number.isFinite(date) && date < oldest) oldest = date
+ }
+ const until = oldest - BEFORE_PULL_MS
+
+ // Who pushed the head, on its own branch.
+ let path: string | undefined = `${base}/activity?ref=${encodeURIComponent(head.ref)}&per_page=100`, headByPerson = false
+ for (let page = 0; page < REF_PAGES && path && !headByPerson; page++) {
+ const answer: Awaited<ReturnType<GitHubRead>> = await read(path)
+ if (answer.status !== 200 || !Array.isArray(answer.body)) return 'unknown'
+ for (const entry of answer.body.map(object)) {
+ if (!shas.has(entry.after)) continue
+ if (!entry.actor) return 'unknown'
+ if (isBot(entry.actor)) return 'team'
+ if (entry.after === head.sha) headByPerson = true
+ }
+ path = answer.next
+ }
+ if (!headByPerson) return 'unknown'
+
+ // Whether the app's bot pushed any of these commits, on any branch: how a batch holds a Team agent's commits.
+ path = `${base}/activity?actor=${encodeURIComponent(bot)}&per_page=100`
+ for (let page = 0; page < ACTIVITY_PAGES; page++) {
+ const answer: Awaited<ReturnType<GitHubRead>> = await read(path)
+ if (answer.status !== 200 || !Array.isArray(answer.body)) return 'unknown'
+ const entries = answer.body.map(object)
+ if (entries.some(entry => shas.has(entry.after))) return 'team'
+ if (!answer.next || Date.parse(String(entries.at(-1)?.timestamp)) < until) return 'clean'
+ path = answer.next
+ }
+ // Twenty pages of the bot's pushes did not reach the time these commits could have been pushed.
+ return 'unknown'
+ } catch {
+ return 'unknown'
+ }
+}
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.ts
index ec2f0514e..8edb394f6 100644
--- a/backend/src/routes/superTabs.ts
+++ b/backend/src/routes/superTabs.ts
@@ -20,6 +20,7 @@ import { holdReason } from '../superTabs/holdReason.js'
import { GitHubAppError } from '../github/app.js'
import { projectGitHubAccess } from '../github/projectAccess.js'
import { projectCiLoad } from '../github/ciLoad.js'
+import { projectBranchOrigin, projectPushOrigin } from '../github/pushOrigin.js'
import { githubSignIn, PrismaApprovals, readState, signState, stateSecret, type Approvals, type GitHubSignIn } from '../github/approvals.js'
import type { GitHubRepository } from '../github/repository.js'
import { githubRepository } from '../github/repository.js'
@@ -238,6 +239,7 @@ async function productionStore(github: GitHubTokens | null): Promise<SuperTabSto
workStarted: (tabId, started) => { void github?.resume(tabId, started).catch(error => logger.warn('[github] resume failed', { tabId, error: String(error) })) },
// A team account has no git login of its own: without the app it takes no teammates' work.
teamAccountsIdle: !github,
+ ...(github ? { pushOrigin: projectPushOrigin(github.app), branchPushOrigin: projectBranchOrigin(github.app) } : {}),
// Every server answers the quiet delivery poll from any server's full one, and tells the agent's machine of new work
// through whichever server holds its daemon socket (stability roadmap 2.4). Both only ever drop, never fail, on Redis.
polls: redisPollMemory(bus.pub),
diff --git a/backend/src/superTabs/archive.ts b/backend/src/superTabs/archive.ts
index 8b9af9158..2e2a2f97d 100644
--- a/backend/src/superTabs/archive.ts
+++ b/backend/src/superTabs/archive.ts
@@ -10,8 +10,9 @@ import { logger } from '../utils/logger.js'
// A finished group archives by itself (roadmap, December: nobody tidies a Swarm by hand): its task done or cancelled, quiet
// for 30 minutes, no person's decision waiting there, and every pull request it links merged or closed. Only GitHub says
// that, over the network, so this runs in the singleton worker and never inside a Swarm's write; the write itself checks
-// everything the Swarm knows again (store.ts archiveFinished). A review nobody is reviewing closes the same way once every
-// pull request of the work it reviews is merged or closed (tidy.ts reviewClosable).
+// everything the Swarm knows again (store.ts archiveFinished). A step (a linked group: a review, a test) archives with its
+// task, in the task's write (steps.ts endSteps), and never on its own clock while that task is open (task steps design): it
+// is taken here only once its task is done or cancelled and every pull request of both is merged or closed.
export type PullRequestState = 'open' | 'merged' | 'closed' | null
/** What a sweep asks GitHub: a pull request's state (null: it cannot say), and `done` once the sweep is over. */
@@ -51,20 +52,37 @@ export function appPullRequests(app: GitHubApp): PullRequests {
}
const BATCH = 500
+const ended = (group: Conversation): boolean => ['done', 'cancelled'].includes(group.assignment?.status ?? '')
-/** Marks every part written before the finished mark whose task is done or cancelled, and every open review written before
- * reviews took the mark while nobody reviews them, so the pass finds it: run once by the worker at startup, as its other
- * index work is. Every later write of a part sets the mark itself (parts/write.ts). */
+/**
+ * Run once by the worker at startup, as its other index work is, so the pass finds what it should. Marks every part written
+ * before the finished mark whose task is done or cancelled, a step not among them. A step's mark goes by its task, which an
+ * update of one document cannot read: any mark on an open step is taken back (an earlier release marked every step nobody
+ * held, so the pass archived it under an open task), and it is set again on those with nobody working whose task has ended.
+ * Every later write of a part sets the mark itself, and of a step clears it (parts/write.ts). Returns how many it marked.
+ */
export async function markFinishedGroups(db: PrismaClient): Promise<number> {
- const answer = await db.$runCommandRaw({ update: 'SwarmGroup', updates: [
- { q: { workFinished: { $exists: false }, deleted: false, 'data.assignment.status': { $in: ['done', 'cancelled'] } }, u: { $set: { workFinished: true } }, multi: true },
- // Open groups only (the mark's index leads with it and archived): the reviews waiting for a Reviewer on 2026-10-30.
- // Measured on prod that day: about 290 index keys and documents examined, 1 ms; it marked 35. Remove it in the
- // release after #2322's, once every part has been written or marked by it.
- { q: { workFinished: { $in: [false, null] }, archived: false, deleted: false, 'data.reviewOf': { $type: 'string' },
- $or: [{ 'data.assignment': null }, { 'data.assignment.status': { $in: ['done', 'stopped', 'cancelled', 'lost'] } }] }, u: { $set: { workFinished: true } }, multi: true },
+ const step = { $type: 'string' }
+ const modified = (answer: unknown) => Number((answer as { nModified?: number }).nModified ?? 0)
+ const written = modified(await db.$runCommandRaw({ update: 'SwarmGroup', updates: [
+ { q: { workFinished: { $exists: false }, deleted: false, 'data.reviewOf': { $not: step }, 'data.assignment.status': { $in: ['done', 'cancelled'] } }, u: { $set: { workFinished: true } }, multi: true },
+ ] }))
+ await db.$runCommandRaw({ update: 'SwarmGroup', updates: [
+ { q: { workFinished: true, archived: false, deleted: false, 'data.reviewOf': step }, u: { $set: { workFinished: false } }, multi: true },
] })
- return Number((answer as { nModified?: number }).nModified ?? 0)
+ // Open groups only (the mark's index leads with it and archived), one indexed read of its task for each open step.
+ const rows = await db.swarmGroup.aggregateRaw({ pipeline: [
+ { $match: { workFinished: { $in: [false, null] }, archived: false, deleted: false, 'data.reviewOf': step,
+ $or: [{ 'data.assignment': null }, { 'data.assignment.status': { $in: ['done', 'stopped', 'cancelled', 'lost'] } }] } },
+ { $lookup: { from: 'SwarmGroup', let: { tabId: '$tabId', task: '$data.reviewOf' }, as: 'task', pipeline: [
+ { $match: { $expr: { $and: [{ $eq: ['$tabId', '$$tabId'] }, { $eq: ['$key', '$$task'] }] } } }, { $project: { status: '$data.assignment.status' } }] } },
+ { $match: { 'task.status': { $in: ['done', 'cancelled'] } } },
+ { $project: { _id: 1 } },
+ ] }) as unknown as Array<{ _id: string }>
+ if (!rows.length) return written
+ return written + modified(await db.$runCommandRaw({ update: 'SwarmGroup', updates: [
+ { q: { _id: { $in: rows.map(row => row._id) } }, u: { $set: { workFinished: true } }, multi: true },
+ ] }))
}
/** One pass: every unarchived group quiet for ARCHIVE_QUIET_MS whose task is done or cancelled (its finished mark), in a Swarm that keeps
@@ -101,8 +119,8 @@ export async function archiveFinishedGroups(db: PrismaClient, store: Pick<SuperT
orderBy: [{ lastActivityAt: 'asc' }, { id: 'asc' }], take: BATCH, select: { id: true, tabId: true, key: true, lastActivityAt: true, data: true } })
for (const row of rows) {
const group = row.data as unknown as Conversation
- const finished = ['done', 'cancelled'].includes(group.assignment?.status ?? ''), review = !!group.reviewOf && !activeWork(group)
- if (group.audience || !(finished || review) || !await tidyOn(row.tabId)) continue
+ const finished = ended(group), step = !!group.reviewOf
+ if (group.audience || !(finished || (step && !activeWork(group))) || !await tidyOn(row.tabId)) continue
const checked: Record<string, 'merged' | 'closed'> = {}
// Stops at the first pull request still open, or that GitHub cannot read.
const settled = async (urls: string[]) => {
@@ -114,11 +132,16 @@ export async function archiveFinishedGroups(db: PrismaClient, store: Pick<SuperT
return true
}
const own = group.pullRequestUrls ?? []
- if (finished && await settled(own) && await archive(row, checked)) { archived++; continue }
- if (!review) continue
- const reviewed = (await db.swarmGroup.findUnique({ where: { tabId_key: { tabId: row.tabId, key: group.reviewOf! } }, select: { data: true } }))?.data as unknown as Conversation | undefined
- const urls = [...new Set([...own, ...reviewed?.pullRequestUrls ?? []])]
- if (urls.length && await settled(urls) && await archive(row, checked, group.reviewOf)) archived++
+ if (!step) {
+ if (await settled(own) && await archive(row, checked)) archived++
+ continue
+ }
+ // A mark left by an earlier release, or a task handed on again since the mark: the task says, not the mark.
+ const task = (await db.swarmGroup.findUnique({ where: { tabId_key: { tabId: row.tabId, key: group.reviewOf! } }, select: { data: true } }))?.data as unknown as Conversation | undefined
+ if (!task || !ended(task)) continue
+ const urls = [...new Set([...own, ...task.pullRequestUrls ?? []])]
+ // A step nobody finished needs a pull request to say its work is settled (tidy.ts reviewClosable).
+ if ((finished || urls.length) && await settled(urls) && await archive(row, checked, group.reviewOf)) archived++
}
if (rows.length < BATCH) return archived
after = { at: rows.at(-1)!.lastActivityAt, id: rows.at(-1)!.id }
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 66f212c6f..38a41fb38 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -1,3 +1,5 @@
+import { applyPushOrigin, failPushUnknown, failTeamWritten, hasStep, mainAccountMembers, markTeamWritten, requireNameable, requireTeamWrittenAccount, requireTeamWrittenMachine, TEAM_WRITTEN_REASON, TEAM_WRITTEN_STOP, teamWrittenTask } from './teamWritten.js'
+import type { PushOrigin } from '../github/pushOrigin.js'
import { admitMachineStart, defaultProfileId, storedProfileId, BUDDY_WINDOWS_REFUSAL, buddyHomeFolder, buddyProjectsOn, SWARM_BUDDY_CAPABILITY, cleanupOverdue, dropIdleBuddyMachines, NOT_SWARM_MACHINE, downSince, expireRemoval, expireRemovals, failTeamWork, removalEnded, machineContribution, machineOffline, machineSlots, contributedEngines, ownedMachine, productManagerOn, projectFolder, projectsOnMachine, requireTeamWork, teamMachineFor, teamAccountPool, teamPoolsOf, teamStartRequest, teamWorkCheck, type ContributedMachine } from './machines.js'
import { agentDisplayName, assignAgentDisplayNames } from './agentNames.js'
import { keepUsernames, setUsername, swarmUsernames, usernameOf } from './usernames.js'
@@ -182,6 +184,7 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('project.role.remove'), projectId: id, roleId }).strict(),
z.object({ type: z.literal('project.roles.reset'), projectId: id, roles: roleSet }).strict(),
// `audience`: a private conversation that only these people and the project's Lead read (projects.ts canReadGroup).
+ z.object({ type: z.literal('work.teamWritten'), conversationId: id }).strict(),
z.object({ type: z.literal('conversation.create'), projectId: id.optional(), title, brief: z.string().trim().max(8000).optional(), task: task.optional(), reviewOf: id.optional(),
// A step of the task `reviewOf` names (task steps design): its name as the instructions give it, free text in any language.
// No line break or control character: the name is printed in agents' terminals (final review, minor 10).
@@ -455,6 +458,8 @@ export interface CommandContext {
teamMachines?: string[]
/** Each contributed machine's CLI version as its daemon last connected (store.ts machineFacts), read with [teamMachines]. */
machineVersions?: Record<string, string>
+ /** Who pushed the pull requests of a work.assign's or a Ready for review's task, read before the command (store.ts pushOriginFor). */
+ pushOrigin?: PushOrigin
/** The person's role in the Swarm's Workspace, read by the store for invitations (workspaces.ts); absent outside a Workspace. */
workspaceRole?: WorkspaceRole
/** Machines of this Swarm also contributed to a Swarm of another Workspace (store.ts otherWorkspaceMachines). */
@@ -818,9 +823,34 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
/** An agent added to a task may work on it, so one added by a post or by opening it takes that project's work only where
* conversation.agent would add it (machines.ts teamWorkCheck; spec, "Kept as access"). */
- const teamJoin = (project: SwarmProject, agentId: string) => {
+ const teamJoin = (project: SwarmProject, agentId: string, group?: Conversation) => {
const member = agent(state, agentId)
requireTeamWork(state, member.machineId, member.contributorId, project, context.now, context.teamMachines, context.otherWorkspaceMachines)
+ // A named agent or a poster joins a task as an assignment would: Team-written code stays in a Team account (audit H2).
+ if (group) {
+ requireTeamWrittenAccount(state, group, member)
+ // Joining a chat is not working on the task: a Team Reviewer or Tester with a step on it does not mark it (review 1 of #2559).
+ if (!hasStep(state, group, member)) marking(group, () => markTeamWritten(state, group, member))
+ }
+ }
+ /** Runs [mark], and tells every main-account member when it just marked [group]'s task: nothing else reaches a session
+ * that already has the branch, or a member the workflow would ask again (teamWritten.ts, audit H2). */
+ const marking = (group: Conversation, mark: () => void) => {
+ const was = teamWrittenTask(state, group)
+ mark()
+ if (was || !teamWrittenTask(state, group)) return
+ for (const told of mainAccountMembers(state, group, actor.kind === 'agent' ? actor.agentId : undefined)) {
+ effects.messages.push({ id: stableId(operationId, 'team-written-stop', told.conversationId), conversationId: told.conversationId, author: sender,
+ text: TEAM_WRITTEN_STOP, replyTo: null, recipients: told.agentIds, source: SYSTEM_ROW })
+ }
+ }
+ /** What GitHub's read says for an agent about to take [group]'s work (store.ts pushOriginFor): a bot's push marks the task and
+ * refuses the main account, and the store keeps that mark after this command is refused. Unknown refuses it unmarked. */
+ const pushedRefusal = (group: Conversation, worker: Agent) => {
+ marking(group, () => applyPushOrigin(state, group, context.pushOrigin))
+ if (onTeamAccount(state, worker) || ledProject(state, worker.id)?.id === groupProject(state, group).id) return
+ if (context.pushOrigin === 'unknown') failPushUnknown()
+ if (context.pushOrigin === 'team') failTeamWritten({ pushed: true })
}
/** A session already in the Swarm that a person's agent.add names joins [group] as conversation.agent adds one (security
* review S2): a Buddy stays in its own chat; it is of the group's project; a stopping one joins nowhere; a teammate's agent
@@ -831,6 +861,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
sameProject(state, group, member)
if (member.workDecision === 'stop') fail('STOP_REQUESTED', 'This agent is stopping. Wait for its execution host.')
requireTeamWork(state, member.machineId, member.contributorId, groupProject(state, group), context.now, context.teamMachines, context.otherWorkspaceMachines)
+ requireTeamWrittenAccount(state, group, member)
+ marking(group, () => markTeamWritten(state, group, member))
}
/** The project chat is the people's and is never archived: its work, name and records are its coordinator's or a person's,
* as its members are (conversation.agent, joinsProject; security review L2). A task's are any agent's of its project. */
@@ -978,7 +1010,11 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
// A new agent never starts on a Buddy-only machine; an agent its person added there runs as one on a machine outside the Swarm.
if (!member && state.machines?.some(m => m.machineId === candidate.machineId && m.buddyOnly)) return { code: 'NOT_SWARM_MACHINE' as const, reason: NOT_SWARM_MACHINE }
// A new agent on a Mac for a teammate's project runs in the Mac's Harness Team account (machines.ts teamStartRequest).
- const machineId = member?.machineId ?? teamMachineFor(state, candidate.machineId, project, context.teamAccountsIdle, context.teamMachines)
+ const group = conversation(state, conversationId), written = teamWrittenTask(state, group)
+ const machineId = member?.machineId ?? teamMachineFor(state, candidate.machineId, project, context.teamAccountsIdle, context.teamMachines, written)
+ // Team-written code takes a Team account only (audit H2). Its own check below says nothing for the owner's own account.
+ if (written && !(member ? onTeamAccount(state, member) : teamAccountPool(state.machines?.find(m => m.machineId === machineId)))
+ && !(member && ledProject(state, member.id)?.id === project.id)) return { code: 'TEAM_WRITTEN_WORK' as const, reason: TEAM_WRITTEN_REASON }
const contributor = member?.contributorId ?? state.machines?.find(m => m.machineId === machineId)?.contributorId ?? starter
return teamWorkCheck(state, machineId, contributor, project, context.now, context.teamMachines, context.otherWorkspaceMachines)
}
@@ -1413,6 +1449,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
// project's instructions cannot choose a model before any agent reads them (project instructions, design call).
const asked = withRoleDefaults(request, BUILT_IN_ROLE_DEFAULTS.lead)
const start = placeLead(state, project, person(state, actor.userId), machineId, asked, operationId, context)
+ // A branch a Team agent pushed, or GitHub cannot place, never starts a PM in the main account (audit H2).
+ if (context.pushOrigin && context.pushOrigin !== 'clean' && !teamAccountPool(state.machines?.find(m => m.machineId === start.request.machineId))) failTeamWritten()
Object.assign(result, { startId: start.id, machineId: start.request.machineId })
break
}
@@ -1791,7 +1829,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
state.groupCounter = number
// The agent that opens a task is in it, so an Engineer that opens its own review can post there and pass its checks.
const creator = actor.kind === 'agent' && actor.agentId !== leadId ? [actor.agentId] : []
- for (const id of creator) teamJoin(project, id)
+ for (const id of creator) teamJoin(project, id, command.reviewOf ? conversation(state, command.reviewOf) : undefined)
// A step's opener is in its task too: the task's chat is where the step's work is talked over (task steps design).
if (command.step && command.reviewOf) {
const owning = conversation(state, command.reviewOf)
@@ -1800,6 +1838,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
state.conversations.push({ id: operationId, ...(state.projects ? { projectId: project.id } : {}),
number, title: command.title, leadId, agentIds: [...leadId ? [leadId] : [], ...creator],
archived: false, brief, ...(command.task ? { task: command.task } : {}), ...(command.reviewOf ? { reviewOf: command.reviewOf } : {}),
+ // A Team agent's own task is Team-written from its first line, and a step keeps its task's mark (teamWritten.ts, audit H2).
+ ...((command.reviewOf ? teamWrittenTask(state, conversation(state, command.reviewOf)) : creator.some(id => onTeamAccount(state, agent(state, id)))) ? { teamWritten: true as const } : {}),
...(command.step ? { step: command.step } : {}),
assignment: null, lastMessageSequence: 0,
checks: storedChecks(command.checks, operationId),
@@ -1999,7 +2039,15 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
// A teammate's project started on a Mac runs in that Mac's Harness Team account, never as its owner (machines.ts). A start
// that names no model runs its engine's own: role defaults live in the project's instructions now.
- const request = teamStartRequest(state, named, home, context.teamAccountsIdle, context.teamMachines)
+ // So does a start for code a Team agent wrote, whoever's project it is, with its project settings off (audit H2).
+ const startGroup = conversation(state, command.request.conversationId)
+ marking(startGroup, () => applyPushOrigin(state, startGroup, context.pushOrigin))
+ const written = teamWrittenTask(state, startGroup)
+ const moved = teamStartRequest(state, named, home, context.teamAccountsIdle, context.teamMachines, written)
+ if (written) requireTeamWrittenMachine(state, startGroup, moved.machineId)
+ // A branch GitHub cannot place stays out of the main account too, unmarked, as it may yet read clean.
+ else if (context.pushOrigin === 'unknown' && !teamAccountPool(state.machines?.find(m => m.machineId === moved.machineId))) failPushUnknown()
+ const request: AgentStartRequest = written ? { ...moved, projectSettings: 'off' } : moved
const pool = admitMachineStart(state, request, context.now, undefined, context.teamMachines, context.otherWorkspaceMachines)
// Off the Machines list, a teammate's project never runs: nothing there shows a privacy check (machines.ts).
if (!pool) requireTeamWork(state, request.machineId, grant.contributorId, home, context.now, context.teamMachines, context.otherWorkspaceMachines)
@@ -2544,6 +2592,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
// An agent added to a task may work on it, so a teammate's agent is added only where it may take that project's work,
// as an assignment checks (machines.ts teamWorkCheck).
requireTeamWork(state, member.machineId, member.contributorId, groupProject(state, group), context.now, context.teamMachines, context.otherWorkspaceMachines)
+ pushedRefusal(group, member)
+ requireTeamWrittenAccount(state, group, member)
+ marking(group, () => markTeamWritten(state, group, member))
if (!group.agentIds.includes(command.agentId)) group.agentIds.push(command.agentId)
// Added to a task, it is reused, as an assignment reuses a worker: its finished-work mark goes.
delete member.workDecision
@@ -2617,7 +2668,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
case 'message.send': {
const joining = actor.kind === 'agent' && !state.conversations.find(c => c.id === command.conversationId)?.agentIds.includes(actor.agentId)
const group = postable(state, actor, command.conversationId)
- if (joining) teamJoin(groupProject(state, group), actor.agentId)
+ if (joining) teamJoin(groupProject(state, group), actor.agentId, group)
const ids = [...new Set(command.attachmentIds ?? [])]
const attachments = ids.map(id => context.attachments?.find(a => a.id === id) ?? fail('ATTACHMENT_UNAVAILABLE', 'Upload this file again before sending it.', 400))
if (!command.text && !attachments.length) fail('TEXT_REQUIRED', 'Write a message or attach a file.', 400)
@@ -2686,13 +2737,15 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
const recipients = [...new Set([...addressed, ...memberToLead, ...(addressed.length || !automatic ? [] : [automatic])])]
for (const id of recipients) {
const target = agent(state, id)
+ // Naming an agent asks it to act, and a re-test is asked this way: a post's default addressee is only told (audit H2).
+ if (actor.kind === 'agent' && addressed.includes(id)) requireNameable(state, group, agent(state, actor.agentId), target)
// In a Buddy chat a session hears its own thread alone, and the main Buddy none of it.
if (session && (session.inSession ? id !== session.to : !!target.buddySession)) fail('INVALID_RECIPIENT', 'Choose an agent in this conversation.', 400)
// An agent of this project that another agent names from outside the group joins it, so it can read and answer there
// (joinsProject). A person's message adds nobody: a person adds an agent to a task with conversation.agent.
if (!group.agentIds.includes(id)) {
if (actor.kind !== 'agent' || !joinsProject(state, group, id)) fail('INVALID_RECIPIENT', 'Choose an agent in this conversation.', 400)
- teamJoin(groupProject(state, group), id)
+ teamJoin(groupProject(state, group), id, group)
group.agentIds.push(id)
}
}
@@ -2842,6 +2895,13 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
bindTaskCard(group, effects.messages.at(-1)!)
break
}
+ case 'work.teamWritten': {
+ // Only on the server's own read: a refused command rolled its mark back (store.ts execute), and no client's word marks a task.
+ if (context.pushOrigin !== 'team') fail('NOT_FOUND', 'This conversation is unavailable.', 404)
+ const group = open(state, command.conversationId)
+ marking(group, () => applyPushOrigin(state, group, 'team'))
+ break
+ }
case 'work.assign': {
chatOnly(command.conversationId)
projectChatWork(command.conversationId)
@@ -2858,6 +2918,10 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
const home = groupProject(state, group)
// A teammate's agent on a personal machine keeps what it has; it takes no new task for another person's project.
requireTeamWork(state, worker.machineId, worker.contributorId, home, context.now, context.teamMachines, context.otherWorkspaceMachines)
+ // Team-written code runs only in a Team account, and a Team agent's work marks the task (teamWritten.ts, audit H2).
+ pushedRefusal(group, worker)
+ requireTeamWrittenAccount(state, group, worker)
+ marking(group, () => markTeamWritten(state, group, worker))
if (worker.workDecision === 'stop') fail('STOP_REQUESTED', 'This worker is stopping. Wait for its execution host.')
if (state.conversations.some(c => activeWork(c) && c.assignment?.agentId === worker.id)) fail('AGENT_BUSY', 'This agent already owns an active assignment.')
// An older client assigns in a custom role: kept for older readers, and the role name it means for a worker without
@@ -2929,6 +2993,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
else 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.`
}
+ // A Team agent's push can land on any branch: its Ready reads who pushed (teamWritten.ts, audit H2).
+ if (command.status === 'review') marking(group, () => applyPushOrigin(state, group, context.pushOrigin))
const changed = assignment.status !== command.status || assignment.result !== command.result || !!command.ask, previous = assignment.status
const waited = waitingForReview(assignment)
assignment.status = command.status
diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.ts
index b29704d95..59ca70c5a 100644
--- a/backend/src/superTabs/machines.ts
+++ b/backend/src/superTabs/machines.ts
@@ -260,7 +260,7 @@ export function observedPrivacy(previous: StoredPrivacy | undefined, reported: M
return { ...reported, seenAt: same ? previous.seenAt : now }
}
-export type TeamWorkCode = 'MACHINE_OFFLINE' | 'TEAM_ACCOUNT_REQUIRED' | 'PRIVACY_UNCHECKED' | 'PRIVACY_CHECK_FAILED' | 'PRIVACY_CHECK_STALE'
+export type TeamWorkCode = 'TEAM_WRITTEN_WORK' | 'MACHINE_OFFLINE' | 'TEAM_ACCOUNT_REQUIRED' | 'PRIVACY_UNCHECKED' | 'PRIVACY_CHECK_FAILED' | 'PRIVACY_CHECK_STALE'
| 'MACHINE_IN_OTHER_WORKSPACE' | 'NOT_SWARM_MACHINE'
export interface TeamWorkRefusal { code: TeamWorkCode; reason: string }
/** Refusals that hold until a person acts on the machine; a stale check or an offline machine may pass again by itself. */
@@ -400,11 +400,12 @@ export function productManagerOn(state: SuperTabState, machineId: string): strin
/** Where a new agent for [project] runs when a start names [machineId]: the Mac's team account when the project is not
* its contributor's own and the Mac has one in this Swarm, else the machine named. */
-export function teamMachineFor(state: SuperTabState, machineId: string, project: SwarmProject, idle = false, live?: readonly string[]): string {
+export function teamMachineFor(state: SuperTabState, machineId: string, project: SwarmProject, idle = false, live?: readonly string[], teamWritten = false): string {
// With no GitHub App on this server a team account cannot fetch or push, so the work stays on the Mac, as before.
if (idle) return machineId
const pool = state.machines?.find(m => m.machineId === machineId)
- if (!pool || project.ownerId === pool.contributorId) return machineId
+ // [teamWritten]: code a Team agent wrote takes the Team account even in its owner's own project (teamWritten.ts, audit H2).
+ if (!pool || (!teamWritten && project.ownerId === pool.contributorId)) return machineId
return teamPoolOf(state, pool, live)?.machineId ?? machineId
}
@@ -446,8 +447,8 @@ export function buddyProjectsOn(state: SuperTabState, pool: ContributedMachine,
* stay with the owner's daemon, and a Mac without a team account here refuses it as before (teamWorkCheck).
*/
export function teamStartRequest(state: SuperTabState, request: AgentStartRequest, project: SwarmProject, idle = false,
- live?: readonly string[]): AgentStartRequest {
- const machineId = teamMachineFor(state, request.machineId, project, idle, live)
+ live?: readonly string[], teamWritten = false): AgentStartRequest {
+ const machineId = teamMachineFor(state, request.machineId, project, idle, live, teamWritten)
if (machineId === request.machineId) return request
const pool = state.machines!.find(m => m.machineId === request.machineId)!, team = state.machines!.find(m => m.machineId === machineId)!
return { ...request, machineId, cwd: request.cwd === projectFolder(pool, project) ? projectFolder(team, project) : request.cwd }
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 85da1b11b..7b9cff793 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -139,6 +139,8 @@ export interface AgentStartRequest {
cwd: string
worktree: boolean
branchRef?: string
+ /** Stamped by the server for Team-written code (teamWritten.ts): the agent reads no project settings and its folder gets no trust. */
+ projectSettings?: 'off'
permissionMode?: string
codexHome?: string
gridModel?: string
@@ -300,6 +302,9 @@ export interface Conversation {
task?: WorkTask
/** A review group names the group whose work it reviews; only a Reviewer is assigned it, and a Reviewer nothing else. */
reviewOf?: string
+ /** A Harness Team agent worked on this task, or GitHub shows the app's bot pushed to its branch: its code runs only in a
+ * Team account (teamWritten.ts, audit H2). Set once and never cleared. */
+ teamWritten?: true
/** A step of the task `reviewOf` names (task steps design, 2026-11-02): its name as the instructions give it, in any
* language. Readers show it inside its task, never as a task of its own. Absent on a linked group opened before steps. */
step?: string
diff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.ts
index ba0c52eb2..3e898aded 100644
--- a/backend/src/superTabs/parts/light.test.ts
+++ b/backend/src/superTabs/parts/light.test.ts
@@ -13,7 +13,7 @@ const assignment: Required<Assignment> = {
}
const conversation: Required<Conversation> = {
id: 'g', kind: 'leads', projectId: 'p', number: 1, title: 't', leadId: null, agentIds: [], archived: false, brief: '',
- task: { goal: '', changes: '', constraints: '', owns: [] }, reviewOf: 'r', step: 'Review', reviewStamp: { assignmentId: 'w', handoff: 1 }, checks: [], assignment, lastMessageSequence: 0, lastMainSequence: 0, pullRequestUrls: [], cards: {},
+ task: { goal: '', changes: '', constraints: '', owns: [] }, reviewOf: 'r', teamWritten: true, step: 'Review', reviewStamp: { assignmentId: 'w', handoff: 1 }, checks: [], assignment, lastMessageSequence: 0, lastMainSequence: 0, pullRequestUrls: [], cards: {},
messageSeq: 0, reportSeq: 0, dormant: false, lastActivityAt: '', audience: { people: [] }, lostAttempt: { id: 'w', agentId: 'a' }, reactionSeq: 0,
requesterId: 'p', ledger: {}, proposals: [], buddyName: 'Sparky', buddySessions: [], buddyDownTold: true, liveness: { state: 'quiet', why: 'silent', since: 1 }, leadAction: { kind: 'post', at: 1 },
stepUp: { attempt: 2, floor: 2, reason: 'r', at: 1, carry: '' },
diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.ts
index 64139de28..b89a6909d 100644
--- a/backend/src/superTabs/parts/light.ts
+++ b/backend/src/superTabs/parts/light.ts
@@ -27,7 +27,7 @@ export const GROUP_FIELDS = {
always: ['id', 'kind', 'projectId', 'leadId', 'agentIds', 'archived', 'audience', 'dormant', 'assignment.id', 'assignment.agentId', 'assignment.status',
'assignment.lost'],
whenRunning: ['title', 'task.owns', 'assignment.execution', 'assignment.result'],
- unread: ['number', 'brief', 'reviewOf', 'step', 'reviewStamp', 'checks', 'lastMessageSequence', 'lastMainSequence', 'pullRequestUrls', 'cards', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals', 'buddyName', 'buddySessions', 'buddyDownTold', 'liveness', 'leadAction', 'stepUp',
+ unread: ['number', 'brief', 'reviewOf', 'teamWritten', 'step', 'reviewStamp', 'checks', 'lastMessageSequence', 'lastMainSequence', 'pullRequestUrls', 'cards', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals', 'buddyName', 'buddySessions', 'buddyDownTold', 'liveness', 'leadAction', 'stepUp',
'assignment.configuration', 'assignment.recordingProgress', 'assignment.leaseUntil', 'assignment.progressAt', 'assignment.askedOf', 'assignment.reviewFoundAt', 'assignment.changesRequestedAt',
'assignment.handoffs', 'assignment.verdicts'],
} as const
diff --git a/backend/src/superTabs/parts/write.ts b/backend/src/superTabs/parts/write.ts
index d923957e2..facacb3cf 100644
--- a/backend/src/superTabs/parts/write.ts
+++ b/backend/src/superTabs/parts/write.ts
@@ -68,8 +68,8 @@ export function extracted(kind: PartKind, data: unknown, stamp: number): Record<
agentIds: group.agentIds, executionMachineId: activeWork(group) ? group.assignment!.execution.machineId : null,
messageSeq: group.messageSeq ?? 0, reportSeq: group.reportSeq ?? 0,
lastActivityAt: group.lastActivityAt ? new Date(group.lastActivityAt) : new Date(stamp), hostDigest: hostDigest(group),
- // A review with no active Reviewer is read by the archive pass too: it closes once its pull requests are (tidy.ts reviewClosable).
- // A step is never: it archives with its task (task steps design; steps.ts closeSteps), not on its own clock.
+ // A step is never marked by a write: it archives with its task (task steps design; steps.ts endSteps), not on its own clock.
+ // Only the worker's startup marks one, once its task has ended (archive.ts markFinishedGroups).
workFinished: !group.reviewOf && (['done', 'cancelled'].includes(group.assignment?.status ?? '') || (!!group.reviewOf && !activeWork(group))) }
}
case 'agent': {
diff --git a/backend/src/superTabs/steps.ts b/backend/src/superTabs/steps.ts
index f5c7bda88..37f34f8cf 100644
--- a/backend/src/superTabs/steps.ts
+++ b/backend/src/superTabs/steps.ts
@@ -13,6 +13,11 @@ export const isStep = (group: Pick<Conversation, 'reviewOf'>): boolean => !!grou
/** A step's name: the one it was opened with, else its title (a linked group opened without one). */
export const stepName = (group: Pick<Conversation, 'step' | 'title'>): string => group.step ?? group.title
+/** Whether [step]'s task is done or cancelled, as far as [state] loaded it. Only then may the archive pass take a step: one
+ * archived under an open task refuses the next round, and that re-check fails silently. A task not loaded has not ended. */
+export const taskEnded = (state: SuperTabState, step: Pick<Conversation, 'reviewOf'>): boolean =>
+ ['done', 'cancelled'].includes(state.conversations.find(c => c.id === step.reviewOf)?.assignment?.status ?? '')
+
/** The steps of task [taskId], in creation order. */
export const stepsOf = (state: SuperTabState, taskId: string): Conversation[] =>
state.conversations.filter(c => c.reviewOf === taskId)
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 52b1279bf..f2d78c1e1 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -7,6 +7,8 @@ import { isDeepStrictEqual } from 'node:util'
import type { Machine, Prisma, PrismaClient, SuperTabDelivery, SuperTabMessage } from '@prisma/client'
import type { AuthUser } from '../lib/ssoAuth.js'
import { machineAlive } from '../lib/prisma.js'
+import { pullRequestsIn, type PushOrigin } from '../github/pushOrigin.js'
+import { githubRepository } from '../github/repository.js'
import { isTeamSession, teamMachine, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../lib/teamSession.js'
import { machineShareGrant, sharedVia } from '../lib/machineSharePolicy.js'
import { machineBillingAllowsDataPlane } from '../lib/billingState.js'
@@ -61,6 +63,7 @@ import { WORKSPACE_LABEL, type WorkspaceRole } from './workspaces.js'
import { STATUS_LABELS,
activeWork, actorKey, agent, agentOnly, appendPullRequestUrls, author, conversation, createSuperTab, fail, person, stableId, visibleState, finishWorker,
SuperTabError, isLeads, knownKind, parkLaterConversations, type Actor, type Agent, type Assignment, type Author, type CommandEffects, type Conversation, type MessageDraft, type Person, type SuperTabState,
+ pullRequestLinks,
} from './model.js'
import { QUIET_CLAIM, type HoldReason } from './holdReason.js'
import { stuck } from './deliverySettle.js'
@@ -297,6 +300,10 @@ export interface SuperTabStoreHooks {
/** Tasks newly in progress, or in progress again under the same id (resumed after a usage limit): GitHub tokens forget
* that such a task ended (github/tokens.ts resume). */
workStarted?: (tabId: string, started: WorkHold[]) => void
+ /** Who pushed these pull requests of a project's repository (github/pushOrigin.ts): the worst of their answers. Absent with no GitHub App. */
+ pushOrigin?: (repositoryUrl: string | null, pullRequestUrls: string[]) => Promise<PushOrigin>
+ /** The same for a branch a start names: its open pull request's answer, clean for the default branch, unknown with no pull request. */
+ branchPushOrigin?: (repositoryUrl: string | null, branch: string) => Promise<PushOrigin>
/** No Harness GitHub App on this server: a Mac's Harness Team account joins no Swarm and takes no teammates' work, since
* it has no git login to fetch or push with (commands.ts `teamAccountsIdle`). */
teamAccountsIdle?: boolean
@@ -1194,6 +1201,12 @@ export class SuperTabStore {
return done
} catch (error) {
if (input.command?.type === 'message.send' && input.command.newSession && error instanceof SuperTabError) logger.info('Buddy session refused', { tabId, code: error.code })
+ // A refusal for a bot's push rolled its mark back. The mark stays, so a post or a join that reads no GitHub is refused next (review 1 of #2559).
+ const pushedOn = input.command && 'conversationId' in input.command ? input.command.conversationId : undefined
+ if (error instanceof SuperTabError && error.details?.pushed === true && typeof pushedOn === 'string') {
+ await this.executeOnce(user, tabId, { operationId: `team-written-${stableId(input.operationId, pushedOn)}`, command: { type: 'work.teamWritten', conversationId: pushedOn } }, asAgentId, hostMachineId)
+ .catch(failure => logger.warn('Team-written mark failed', { tabId, error: String(failure) }))
+ }
// A queued start its machine will not take for good — no Harness Team account, or one that is not private — fails
// with that reason instead of waiting there: its host would otherwise try to launch it on every pass, and it would
// hold a slot. A stale check or an offline machine may pass again by itself, so that start keeps waiting.
@@ -1214,9 +1227,56 @@ export class SuperTabStore {
}
}
+ /**
+ * Who pushed the pull requests of the task a work.assign or a Ready for review is about (github/pushOrigin.ts, audit H2).
+ * Read outside the command's transaction, as GitHub may take seconds, so it can only ever add a mark. Undefined when there is
+ * nothing to read, or this reader cannot read that task: the command then refuses as it would.
+ */
+ private async pushOriginFor(user: AuthUser, tabId: string, command: unknown): Promise<PushOrigin | undefined> {
+ const hook = this.hooks.pushOrigin
+ const asked = command as { type?: unknown; conversationId?: unknown; status?: unknown; result?: unknown; present?: unknown; projectId?: unknown; branchRef?: unknown;
+ request?: { branchRef?: unknown; conversationId?: unknown } } | null
+ if (!asked) return undefined
+ // A start that names a branch: a person or the PM can name any branch, whoever pushed it.
+ const ref = asked.type === 'agent.start' ? asked.request?.branchRef : asked.type === 'lead.start' ? asked.branchRef : undefined
+ try {
+ if (typeof ref === 'string' && this.hooks.branchPushOrigin) {
+ const branch = ref.replace(/^refs\/(heads|remotes\/origin)\//, '')
+ const repositoryUrl = await transaction(this.db, async tx => {
+ const { state } = await this.load(tx, user, tabId, namedFor(command as Command))
+ if (asked.type === 'lead.start') return projectsOf(state).find(p => p.id === asked.projectId)?.repository?.repositoryUrl ?? null
+ const group = state.conversations.find(c => c.id === asked.request?.conversationId)
+ return group ? groupProject(state, group).repository?.repositoryUrl ?? null : undefined
+ })
+ return repositoryUrl === undefined ? undefined : await this.hooks.branchPushOrigin(repositoryUrl, branch)
+ }
+ const reads = asked.type === 'work.assign' || asked.type === 'work.teamWritten' || (asked.type === 'conversation.agent' && asked.present === true) || (asked.type === 'work.status' && asked.status === 'review')
+ if (!hook || typeof asked.conversationId !== 'string' || !reads) return undefined
+ const facts = await transaction(this.db, async tx => {
+ const { state } = await this.load(tx, user, tabId, namedFor(command as Command))
+ const group = state.conversations.find(c => c.id === asked.conversationId)
+ if (!group) return null
+ const task = group.reviewOf ? state.conversations.find(c => c.id === group.reviewOf) : undefined
+ const repositoryUrl = groupProject(state, group).repository?.repositoryUrl ?? null
+ const urls = [...group.pullRequestUrls ?? [], ...task?.pullRequestUrls ?? [],
+ ...[group.brief, group.title, task?.brief, task?.title, typeof asked.result === 'string' ? asked.result : ''].flatMap(text => text ? pullRequestsIn(text, repositoryUrl) : [])]
+ return { repositoryUrl, urls: [...new Set(urls)], step: !!group.reviewOf }
+ })
+ if (!facts) return undefined
+ if (facts.urls.length) return await hook(facts.repositoryUrl, facts.urls)
+ // A step reads or runs a branch, and with no pull request named nothing shows whose. It may name one in a sentence no read
+ // can parse, and then its agent runs `gh pr checkout` itself (security review 2 of #2559).
+ return facts.step && facts.repositoryUrl && githubRepository(facts.repositoryUrl) ? 'unknown' : undefined
+ } catch (error) {
+ if (error instanceof SuperTabError) return undefined
+ return 'unknown'
+ }
+ }
+
private async executeOnce(user: AuthUser, tabId: string, input: { operationId: string; command: Command }, asAgentId?: string, hostMachineId?: string,
workspaceLeave = false) {
const { operationId, command } = operationSchema.parse(input)
+ const pushOrigin = await this.pushOriginFor(user, tabId, command)
let ended: WorkHold[] = [], started: WorkHold[] = []
const done = await transaction(this.db, async tx => {
// A retried attempt starts again: only the attempt that commits says which tasks ended or started.
@@ -1449,6 +1509,7 @@ export class SuperTabStore {
context.otherWorkspaceMachines = await this.otherWorkspaceMachines(tx, original)
if (this.hooks.teamAccountsIdle) context.teamAccountsIdle = true
}
+ if (pushOrigin) context.pushOrigin = pushOrigin
if (command.type === 'agent.screen' || command.type === 'agent.input') {
// A machine that is gone or no longer shared refuses at once instead of leaving the request to time out.
await this.agentGrant(tx, original, agent(original, command.agentId))
@@ -3486,9 +3547,10 @@ export class SuperTabStore {
/** Archives a finished group whose pull requests `checked` were all read merged or closed (archive.ts), only if it still
* qualifies inside this write: no message and no pull request linked since the read. A decision still waiting there
- * closes as withdrawn (decisions.ts withdrawIn), and its waiting deliveries end, as a person's archive ends them. With
- * `reviewOf`, the group the pass read as the one it reviews, a review nobody is reviewing closes the same way once those
- * of the work it reviews are too (tidy.ts reviewClosable). True when it archived. */
+ * closes as withdrawn (decisions.ts withdrawIn), and its waiting deliveries end, as a person's archive ends them. A step
+ * needs `reviewOf`, the group the pass read as its task, which this write reads again: it stays open unless that task is
+ * done or cancelled and that task's pull requests are settled too. A review nobody is reviewing closes the same way
+ * (tidy.ts reviewClosable). True when it archived. */
async archiveFinished(tabId: string, groupId: string, checked: Readonly<Record<string, 'merged' | 'closed'>>, reviewOf?: string): Promise<boolean> {
return transaction(this.db, async tx => {
const row = await tx.superTab.findUnique({ where: { id: tabId }, select: SWARM_ROW })
@@ -3498,7 +3560,8 @@ export class SuperTabStore {
const now = this.now()
if (!group) return false
const read = (urls: readonly string[]) => urls.every(url => checked[url] === 'merged' || checked[url] === 'closed')
- const finished = archivable(state, group, now) && read(group.pullRequestUrls ?? [])
+ // A step's task's pull requests count too: it may yet be handed back while one is open, and need its step again.
+ const finished = archivable(state, group, now) && read(reviewPullRequests(state, group))
// Only the group it reviews as the pass read it: one this write did not load would hide its open pull requests.
const review = !finished && !!reviewOf && group.reviewOf === reviewOf && reviewClosable(state, group, now) && read(reviewPullRequests(state, group))
if (!finished && !review) return false
@@ -3517,7 +3580,8 @@ export class SuperTabStore {
// A review's close also writes the work it reviews (review of #2322): a Ready for review committed since the load linked
// a new pull request and saw this review still open, so it opened none. The touch makes one of the two writes retry,
// and the retry sees the other: this one declines (a pull request not read), or that one opens a new review.
- await this.save(tx, loaded, state, clock.next(), review ? [{ kind: 'group', key: group.reviewOf! }] : [])
+ // A finished step's too: its task handed on again since the load must not lose the step it will need.
+ await this.save(tx, loaded, state, clock.next(), group.reviewOf ? [{ kind: 'group', key: group.reviewOf }] : [])
await this.writeMessages(tx, tabId, state, rows, sequences)
return true
})
diff --git a/backend/src/superTabs/teamWritten.test.ts b/backend/src/superTabs/teamWritten.test.ts
new file mode 100644
index 000000000..21ceed0ba
--- /dev/null
+++ b/backend/src/superTabs/teamWritten.test.ts
@@ -0,0 +1,286 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, type Command, type CommandContext } from './commands.js'
+import type { ContributedMachine } from './machines.js'
+import { createSuperTab, SuperTabError, type Actor, type AgentConfiguration, type SuperTabState } from './model.js'
+import { LEAD_CAPABILITY } from './leadStart.js'
+import { TEAM_WRITTEN_STOP, TEAM_WRITTEN_WORK, teamWrittenTask } from './teamWritten.js'
+
+// Audit H2: a branch a Team agent wrote runs only in a Team account, whoever's project it is, so nothing the branch
+// carries runs with the main account's rights (docs/plans/2026-11-02-team-written-branch-plan.md).
+const NOW = 50_000_000
+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
+const config: AgentConfiguration = { engine: 'claude', model: 'fixture-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }
+const requirements = { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false }
+const resources = { cpuPercent: 1, memoryTotalBytes: 8, memoryUsedBytes: 1, diskFreeBytes: 8, diskTotalBytes: 8, projectDiskFreeBytes: 8,
+ deviceType: null, chip: null, os: null, gpuPercent: null }
+const reading = (sessionKind: 'team' | 'computer') => ({ generation: 'g1', receivedAt: NOW, sessionKind, resources, tools: {}, quotas: [], runningHarnessIds: [], stoppedHarnessIds: [],
+ ...(sessionKind === 'team' ? { privacy: { mode: 'account' as const, passed: true as const, checkedAt: NOW - 1000, seenAt: NOW - 1000 } } : {}) })
+
+function swarm() {
+ let state: SuperTabState = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')
+ let sequence = 0
+ const generation = state.people.find(p => p.id === 'owner')!.generation
+ const pool = (machineId: string, sessionKind: 'team' | 'computer', extra: Partial<ContributedMachine> = {}): ContributedMachine => ({ machineId, name: machineId, contributorId: 'owner',
+ membershipGeneration: generation, generation: 'g1', cwd: '/swarm', scope: 'swarm', engines: ['claude'], maxAgents: 4, paused: false, observation: reading(sessionKind), ...extra })
+ state.machines = [pool('mac', 'computer'), pool('mac-team', 'team', { hostMachineId: 'mac' })]
+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {
+ const effects = applyCommand(state, actor, command, { now: NOW, operationId: `op-${++sequence}`, teamMachines: ['mac-team'],
+ contribution: { machineOwnerId: 'owner', contributorId: 'owner', hostGrant: null }, ...context })
+ state = effects.state
+ return effects
+ }
+ const member = (id: string, machineId: string) => {
+ state.agents.push({ id, machineId, harnessId: `harness-${id}`, projectId: 'lead', machineOwnerId: 'owner', contributorId: 'owner',
+ membershipGeneration: generation, hostGrant: null, name: id, configuration: config })
+ return id
+ }
+ const group = (extra: Partial<Extract<Command, { type: 'conversation.create' }>> = {}, actor: Actor = owner) => String(run({ type: 'conversation.create', projectId: 'lead', title: 'Work', brief: 'Build it.',
+ checks: [], ...extra }, actor).result.conversationId)
+ const start = (conversationId: string, machineId: string) => run({ type: 'agent.start', request: { conversationId, machineId, engine: 'claude', name: 'Reviewer', cwd: '/swarm/lead', worktree: true, requirements } })
+ /** A task a Team agent was assigned, with its finished assignment left behind so a review can begin. */
+ const written = () => {
+ const task = group()
+ run({ type: 'work.assign', conversationId: task, agentId: member('team-builder', 'mac-team') })
+ return task
+ }
+ return { run, group, member, start, written, get state() { return state } }
+}
+const refusal = (body: () => unknown): string | null => {
+ try { body(); return null } catch (error) { if (error instanceof SuperTabError) return error.code; throw error }
+}
+
+describe('a task a Team agent worked on', () => {
+ it('keeps its mark after the Team agent leaves it', () => {
+ const f = swarm(), task = f.written()
+ const stored = () => f.state.conversations.find(c => c.id === task)!
+ expect(stored().teamWritten).toBe(true)
+ stored().assignment = null
+ expect(teamWrittenTask(f.state, stored())).toBe(true)
+ })
+
+ it('is marked when a Team agent opens it or is added to it', () => {
+ const f = swarm()
+ const opened = f.group({}, { kind: 'agent', agentId: f.member('team-a', 'mac-team'), machineOwnerId: 'owner' })
+ expect(f.state.conversations.find(c => c.id === opened)!.teamWritten).toBe(true)
+ const added = f.group()
+ f.run({ type: 'conversation.agent', conversationId: added, agentId: f.member('team-b', 'mac-team'), present: true, lead: false })
+ expect(f.state.conversations.find(c => c.id === added)!.teamWritten).toBe(true)
+ })
+
+ it('refuses an agent in the main account: assigned to its step, or to the task itself', () => {
+ const f = swarm(), task = f.written(), main = f.member('main-reviewer', 'mac')
+ const step = f.group({ reviewOf: task, step: 'Review' })
+ expect(refusal(() => f.run({ type: 'work.assign', conversationId: step, agentId: main }))).toBe(TEAM_WRITTEN_WORK)
+ f.state.conversations.find(c => c.id === task)!.assignment = null
+ expect(refusal(() => f.run({ type: 'work.assign', conversationId: task, agentId: main }))).toBe(TEAM_WRITTEN_WORK)
+ })
+
+ it('refuses joining the main account\'s agent to it, by a person or by another agent\'s post', () => {
+ const f = swarm(), task = f.written(), main = f.member('main-reviewer', 'mac')
+ expect(refusal(() => f.run({ type: 'conversation.agent', conversationId: task, agentId: main, present: true, lead: false }))).toBe(TEAM_WRITTEN_WORK)
+ expect(refusal(() => f.run({ type: 'message.send', conversationId: task, text: 'Please test this.', replyTo: null, recipientIds: [main] },
+ { kind: 'agent', agentId: 'team-builder', machineOwnerId: 'owner' }))).toBe(TEAM_WRITTEN_WORK)
+ })
+
+ it('takes a Team agent as its Reviewer, and that does not mark a clean task', () => {
+ const f = swarm(), task = f.written(), reviewer = f.member('team-reviewer', 'mac-team')
+ const step = f.group({ reviewOf: task, step: 'Review' })
+ expect(refusal(() => f.run({ type: 'work.assign', conversationId: step, agentId: reviewer }))).toBeNull()
+ const clean = f.group(), cleanStep = f.group({ reviewOf: clean, step: 'Test' })
+ f.run({ type: 'work.assign', conversationId: cleanStep, agentId: f.member('team-tester', 'mac-team') })
+ expect(f.state.conversations.find(c => c.id === clean)!.teamWritten).toBeUndefined()
+ expect(refusal(() => f.run({ type: 'work.assign', conversationId: clean, agentId: f.member('main-builder', 'mac') }))).toBeNull()
+ })
+
+ it('moves a start on the Mac into its Team account, with project settings off', () => {
+ const f = swarm(), task = f.written()
+ f.start(f.group({ reviewOf: task, step: 'Review' }), 'mac')
+ const started = f.state.starts!.at(-1)!.request
+ expect(started.machineId).toBe('mac-team')
+ expect(started.projectSettings).toBe('off')
+ })
+
+ it('refuses a start where the Mac has no Team account', () => {
+ const f = swarm(), task = f.written(), step = f.group({ reviewOf: task, step: 'Review' })
+ f.state.machines = f.state.machines!.filter(m => m.machineId !== 'mac-team')
+ expect(refusal(() => f.start(step, 'mac'))).toBe(TEAM_WRITTEN_WORK)
+ })
+
+ it('leaves an owner\'s clean task as it was: a start in the main account, project settings on', () => {
+ const f = swarm()
+ f.start(f.group(), 'mac')
+ const started = f.state.starts!.at(-1)!.request
+ expect(started.machineId).toBe('mac')
+ expect(started.projectSettings).toBeUndefined()
+ })
+
+ it('takes GitHub\'s record of a bot\'s push: a clean task is marked for good and refuses the main account', () => {
+ const f = swarm(), task = f.group(), step = f.group({ reviewOf: task, step: 'Review' }), main = f.member('main-reviewer', 'mac')
+ expect(refusal(() => f.run({ type: 'work.assign', conversationId: step, agentId: main }, owner, { pushOrigin: 'team' }))).toBe(TEAM_WRITTEN_WORK)
+ // Refused, so nothing it did stays: the next reading decides again, and a clean reading never clears a mark.
+ f.state.conversations.find(c => c.id === task)!.teamWritten = true
+ expect(refusal(() => f.run({ type: 'work.assign', conversationId: step, agentId: main }, owner, { pushOrigin: 'clean' }))).toBe(TEAM_WRITTEN_WORK)
+ })
+
+ it('refuses the main account while GitHub cannot say who pushed, without marking the task, and takes it once GitHub answers', () => {
+ const f = swarm(), task = f.group(), step = f.group({ reviewOf: task, step: 'Review' }), main = f.member('main-reviewer', 'mac')
+ expect(refusal(() => f.run({ type: 'work.assign', conversationId: step, agentId: main }, owner, { pushOrigin: 'unknown' }))).toBe(TEAM_WRITTEN_WORK)
+ expect(f.state.conversations.find(c => c.id === task)!.teamWritten).toBeUndefined()
+ expect(refusal(() => f.run({ type: 'work.assign', conversationId: step, agentId: main }, owner, { pushOrigin: 'clean' }))).toBeNull()
+ })
+
+ it('still gives a Team agent the work while GitHub cannot say who pushed', () => {
+ const f = swarm(), step = f.group({ reviewOf: f.group(), step: 'Review' })
+ expect(refusal(() => f.run({ type: 'work.assign', conversationId: step, agentId: f.member('team-reviewer', 'mac-team') }, owner, { pushOrigin: 'unknown' }))).toBeNull()
+ })
+
+ it('tells a main-account agent on a step to stop when a Ready shows a bot\'s push on the owner\'s branch', () => {
+ const f = swarm(), task = f.group(), builder = f.member('main-builder', 'mac'), reviewer = f.member('main-reviewer', 'mac')
+ f.run({ type: 'work.assign', conversationId: task, agentId: builder })
+ const assignmentId = f.state.conversations.find(c => c.id === task)!.assignment!.id
+ f.run({ type: 'work.assign', conversationId: f.group({ reviewOf: task, step: 'Review' }), agentId: reviewer })
+ const effects = f.run({ type: 'work.status', conversationId: task, assignmentId, status: 'review', result: 'https://github.com/acme/app/pull/7' },
+ { kind: 'agent', agentId: builder, machineOwnerId: 'owner' }, { pushOrigin: 'team' })
+ expect(f.state.conversations.find(c => c.id === task)!.teamWritten).toBe(true)
+ expect(effects.messages.find(m => m.text === TEAM_WRITTEN_STOP)?.recipients).toEqual([reviewer])
+ })
+
+ it('tells every main-account member once when it is marked, finished steps included, and never the coordinator or a Team agent', () => {
+ const f = swarm(), task = f.group(), builder = f.member('main-builder', 'mac'), tester = f.member('main-tester', 'mac'), team = f.member('team-reviewer', 'mac-team')
+ f.run({ type: 'work.assign', conversationId: task, agentId: builder })
+ const assignmentId = f.state.conversations.find(c => c.id === task)!.assignment!.id
+ const testStep = f.group({ reviewOf: task, step: 'Test' }), reviewStep = f.group({ reviewOf: task, step: 'Review' })
+ f.run({ type: 'work.assign', conversationId: testStep, agentId: tester })
+ f.run({ type: 'work.assign', conversationId: reviewStep, agentId: team })
+ // The Tester's step ended: it is still a member, and the same-step re-ask would reach it.
+ f.state.conversations.find(c => c.id === testStep)!.assignment!.status = 'done'
+ const effects = f.run({ type: 'work.status', conversationId: task, assignmentId, status: 'review', result: 'https://github.com/acme/app/pull/7' }, owner, { pushOrigin: 'team' })
+ const told = effects.messages.filter(m => m.text === TEAM_WRITTEN_STOP).flatMap(m => m.recipients)
+ expect(told.sort()).toEqual([builder, tester].sort())
+ })
+
+ it('tells the main-account members when a Team agent is assigned to their clean task', () => {
+ const f = swarm(), task = f.group(), builder = f.member('main-builder', 'mac')
+ f.run({ type: 'conversation.agent', conversationId: task, agentId: builder, present: true, lead: false })
+ const effects = f.run({ type: 'work.assign', conversationId: task, agentId: f.member('team-builder', 'mac-team') })
+ expect(effects.messages.find(m => m.text === TEAM_WRITTEN_STOP)?.recipients).toEqual([builder])
+ })
+
+ it('refuses a post that names a main-account member of a marked task: the re-test the workflow asks for', () => {
+ const f = swarm(), task = f.group(), builder = f.member('main-builder', 'mac'), tester = f.member('main-tester', 'mac')
+ f.run({ type: 'work.assign', conversationId: task, agentId: builder })
+ const step = f.group({ reviewOf: task, step: 'Test' })
+ f.run({ type: 'work.assign', conversationId: step, agentId: tester })
+ f.state.conversations.find(c => c.id === task)!.teamWritten = true
+ const asBuilder: Actor = { kind: 'agent', agentId: builder, machineOwnerId: 'owner' }
+ const post = (conversationId: string, recipientIds: string[], actor: Actor) => f.run({ type: 'message.send', conversationId, text: 'Please test again.', replyTo: null, recipientIds }, actor)
+ expect(refusal(() => post(step, [tester], asBuilder))).toBe(TEAM_WRITTEN_WORK)
+ expect(refusal(() => post(task, [tester], asBuilder))).toBe(TEAM_WRITTEN_WORK)
+ // A Team agent may still be named, and a person speaks to whom they choose.
+ const team = f.member('team-tester', 'mac-team')
+ f.run({ type: 'conversation.agent', conversationId: task, agentId: team, present: true, lead: false })
+ expect(refusal(() => post(task, [team], asBuilder))).toBeNull()
+ expect(refusal(() => post(task, [tester], owner))).toBeNull()
+ })
+
+ it('reads who pushed before adding an agent: a bot\'s push or an unknown refuses the main account, and a Team agent still joins', () => {
+ const f = swarm(), task = f.group(), main = f.member('main-reviewer', 'mac')
+ const add = (agentId: string, pushOrigin: 'team' | 'unknown') => f.run({ type: 'conversation.agent', conversationId: task, agentId, present: true, lead: false }, owner, { pushOrigin })
+ expect(refusal(() => add(main, 'unknown'))).toBe(TEAM_WRITTEN_WORK)
+ expect(refusal(() => add(main, 'team'))).toBe(TEAM_WRITTEN_WORK)
+ expect(refusal(() => add(f.member('team-a', 'mac-team'), 'unknown'))).toBeNull()
+ })
+
+ it('refuses a PM start in the main account on a branch a bot pushed or GitHub cannot place, and takes a clean one', () => {
+ for (const [pushOrigin, code] of [['team', TEAM_WRITTEN_WORK], ['unknown', TEAM_WRITTEN_WORK], ['clean', null]] as const) {
+ const f = swarm()
+ const projectId = String(f.run({ type: 'project.create', name: 'New', visibility: 'public', brief: '' }).result.projectId)
+ f.state.machines!.find(m => m.machineId === 'mac')!.observation!.capabilities = [LEAD_CAPABILITY]
+ expect(refusal(() => f.run({ type: 'lead.start', projectId, machineId: 'mac', engine: 'claude', branchRef: 'refs/remotes/origin/fix', repositoryUrl: 'https://github.com/acme/app' }, owner, { pushOrigin, machineVersions: { mac: '99.0.0', 'mac-team': '99.0.0' } })), pushOrigin).toBe(code)
+ }
+ })
+
+ it('marks only on the server\'s own read: a client asking for the mark without one is refused', () => {
+ const f = swarm(), task = f.group()
+ expect(refusal(() => f.run({ type: 'work.teamWritten', conversationId: task }))).toBe('NOT_FOUND')
+ expect(f.state.conversations.find(c => c.id === task)!.teamWritten).toBeUndefined()
+ f.run({ type: 'work.teamWritten', conversationId: task }, owner, { pushOrigin: 'team' })
+ expect(f.state.conversations.find(c => c.id === task)!.teamWritten).toBe(true)
+ })
+
+ it('does not mark a clean task when a Team agent with a step on it joins its chat: it reads or tests, and a push of its own shows in GitHub', () => {
+ const f = swarm(), task = f.group(), builder = f.member('main-builder', 'mac'), tester = f.member('team-tester', 'mac-team')
+ f.run({ type: 'work.assign', conversationId: task, agentId: builder })
+ f.run({ type: 'work.assign', conversationId: f.group({ reviewOf: task, step: 'Test' }), agentId: tester })
+ const stored = f.state.conversations.find(c => c.id === task)!
+ // Named after leaving the task's chat, and posting there itself: each joins it again.
+ stored.agentIds = stored.agentIds.filter(id => id !== tester)
+ const named = f.run({ type: 'message.send', conversationId: task, text: 'Please test again.', replyTo: null, recipientIds: [tester] }, { kind: 'agent', agentId: builder, machineOwnerId: 'owner' })
+ expect(f.state.conversations.find(c => c.id === task)!.teamWritten).toBeUndefined()
+ expect(named.messages.some(m => m.text === TEAM_WRITTEN_STOP)).toBe(false)
+ const again = f.state.conversations.find(c => c.id === task)!
+ again.agentIds = again.agentIds.filter(id => id !== tester)
+ f.run({ type: 'message.send', conversationId: task, text: 'Testing now.', replyTo: null, recipientIds: [] }, { kind: 'agent', agentId: tester, machineOwnerId: 'owner' })
+ expect(f.state.conversations.find(c => c.id === task)!.teamWritten).toBeUndefined()
+ })
+
+ it('still marks a task when a Team agent with a step on it is assigned the task itself', () => {
+ const f = swarm(), task = f.group(), tester = f.member('team-tester', 'mac-team')
+ f.run({ type: 'work.assign', conversationId: f.group({ reviewOf: task, step: 'Test' }), agentId: tester })
+ f.state.conversations.find(c => c.id === task)!.assignment = null
+ const free = f.state.conversations.find(c => c.reviewOf === task)!
+ free.assignment!.status = 'done'
+ f.run({ type: 'work.assign', conversationId: task, agentId: tester })
+ expect(f.state.conversations.find(c => c.id === task)!.teamWritten).toBe(true)
+ })
+
+ it('marks a clean task when another agent names a Team agent into it', () => {
+ const f = swarm(), task = f.group(), builder = f.member('main-builder', 'mac')
+ f.run({ type: 'work.assign', conversationId: task, agentId: builder })
+ f.run({ type: 'message.send', conversationId: task, text: 'Please look.', replyTo: null, recipientIds: [f.member('team-a', 'mac-team')] }, { kind: 'agent', agentId: builder, machineOwnerId: 'owner' })
+ expect(f.state.conversations.find(c => c.id === task)!.teamWritten).toBe(true)
+ })
+
+ it('reads who pushed the branch a start names: a bot\'s push moves it to the Team account, an unknown branch stays out of the main account', () => {
+ const f = swarm(), task = f.group()
+ const request = (conversationId: string) => ({ type: 'agent.start' as const, request: { conversationId, machineId: 'mac', engine: 'claude', name: 'Tester', cwd: '/swarm/lead', worktree: true, branchRef: 'refs/remotes/origin/fix', requirements } })
+ expect(refusal(() => f.run(request(task), owner, { pushOrigin: 'unknown' }))).toBe(TEAM_WRITTEN_WORK)
+ f.run(request(task), owner, { pushOrigin: 'team' })
+ expect(f.state.starts!.at(-1)!.request).toMatchObject({ machineId: 'mac-team', projectSettings: 'off' })
+ expect(f.state.conversations.find(c => c.id === task)!.teamWritten).toBe(true)
+ })
+
+ it('refuses an agent of another project as it refuses one on any task, so the answer says nothing of the mark', () => {
+ const f = swarm(), task = f.written()
+ const other = String(f.run({ type: 'project.create', name: 'Other', visibility: 'public', brief: '' }).result.projectId)
+ const outsider = f.member('outsider', 'mac')
+ f.state.agents.find(a => a.id === outsider)!.projectId = other
+ const code = (conversationId: string) => { try { f.run({ type: 'work.assign', conversationId, agentId: outsider }); return null } catch (error) { return (error as SuperTabError).code } }
+ f.state.conversations.find(c => c.id === task)!.assignment = null
+ const clean = f.group()
+ expect(code(task)).toBe(code(clean))
+ expect(code(task)).not.toBe(TEAM_WRITTEN_WORK)
+ })
+
+ it('marks the task and not the agent: the same Team agent\'s next task elsewhere starts clean until it is assigned there', () => {
+ const f = swarm(), task = f.written(), clean = f.group()
+ expect(f.state.conversations.find(c => c.id === task)!.teamWritten).toBe(true)
+ expect(f.state.conversations.find(c => c.id === clean)!.teamWritten).toBeUndefined()
+ expect(refusal(() => f.run({ type: 'work.assign', conversationId: clean, agentId: f.member('main-builder', 'mac') }))).toBeNull()
+ })
+
+ it('keeps the coordinator on a marked task, and it marks nothing when it runs in a Team account', () => {
+ const f = swarm(), task = f.written(), lead = f.member('lead-on-team', 'mac-team'), clean = f.group()
+ f.state.projects!.find(p => p.id === 'lead')!.leadConversationId = 'lead'
+ f.state.conversations.find(c => c.id === 'lead')!.leadId = lead
+ f.run({ type: 'conversation.agent', conversationId: clean, agentId: lead, present: true, lead: false })
+ expect(f.state.conversations.find(c => c.id === clean)!.teamWritten).toBeUndefined()
+ expect(f.state.conversations.find(c => c.id === task)!.teamWritten).toBe(true)
+ })
+
+ it('reads a mark set before its assignee existed in the Swarm\'s record, on an open task, by its current assignee', () => {
+ const f = swarm(), task = f.written(), stored = f.state.conversations.find(c => c.id === task)!
+ delete stored.teamWritten
+ expect(teamWrittenTask(f.state, stored)).toBe(true)
+ })
+})
diff --git a/backend/src/superTabs/teamWritten.ts b/backend/src/superTabs/teamWritten.ts
new file mode 100644
index 000000000..09a021a0e
--- /dev/null
+++ b/backend/src/superTabs/teamWritten.ts
@@ -0,0 +1,92 @@
+/**
+ * A task a Harness Team agent worked on (audit H2, docs/security/2026-11-02-team-account-boundary.md): its branch runs
+ * only in a Team account, never with the main account's rights, as install scripts, tests and project settings would
+ * run there with no race and no bug. docs/plans/2026-11-02-team-written-branch-plan.md.
+ *
+ * The mark comes from the Swarm's own record of who worked on the task, or from GitHub's record of who pushed. It never
+ * clears, and it is never read from a commit's author, which anyone can write. A step reads its task's mark. A Team agent
+ * given only a step does not mark the task: it reads or tests, and a push of its own shows in GitHub's record.
+ */
+import type { PushOrigin } from '../github/pushOrigin.js'
+import { fail, type Agent, type Conversation, type SuperTabState } from './model.js'
+import { groupProject, ledProject, onTeamAccount, teamAccountPool } from './projects.js'
+
+export const TEAM_WRITTEN_WORK = 'TEAM_WRITTEN_WORK'
+export const TEAM_WRITTEN_REASON = 'A Harness Team agent wrote this task\'s code, so it runs only in a Team account, never in the main account. Choose an agent or machine in a Team account.'
+
+const coordinates = (state: SuperTabState, group: Conversation, worker: Agent): boolean =>
+ ledProject(state, worker.id)?.id === groupProject(state, group).id
+
+/** Told to an agent in the main account when a task it works on turns out to be Team-written. */
+export const TEAM_WRITTEN_STOP = 'Stop: GitHub shows a Harness Team agent pushed to this task\'s branch. Do not install, build, test or run it in the main account. Set this step blocked and hand it to an agent in a Team account.'
+
+/** The task a group's code belongs to: its own, or for a step, the task the step belongs to. */
+const taskOf = (state: SuperTabState, group: Conversation): Conversation | undefined =>
+ group.reviewOf ? state.conversations.find(c => c.id === group.reviewOf) : group
+
+/** Whether [group]'s code is Team-written. An open task from before the mark reads its current assignee too. A step whose
+ * task this command did not load counts as Team-written: an unknown never reads as clean. */
+export function teamWrittenTask(state: SuperTabState, group: Conversation): boolean {
+ const task = taskOf(state, group)
+ if (!task || group.teamWritten || task.teamWritten) return true
+ const assignee = state.agents.find(a => a.id === task.assignment?.agentId)
+ return !!assignee && onTeamAccount(state, assignee)
+}
+
+/** Marks [group] when [worker], assigned to it or added to it, runs in a Team account. A step or the project's coordinator marks nothing. */
+export function markTeamWritten(state: SuperTabState, group: Conversation, worker: Agent): void {
+ if (group.reviewOf || coordinates(state, group, worker) || !onTeamAccount(state, worker)) return
+ group.teamWritten = true
+}
+
+/** Refuses an agent outside a Team account for Team-written code. The project's coordinator stays: it never builds or runs it. */
+export function requireTeamWrittenAccount(state: SuperTabState, group: Conversation, worker: Agent): void {
+ if (!coordinates(state, group, worker) && teamWrittenTask(state, group) && !onTeamAccount(state, worker)) failTeamWritten()
+}
+
+/** Refuses a start for Team-written code on a machine outside a Team account. */
+export function requireTeamWrittenMachine(state: SuperTabState, group: Conversation, machineId: string): void {
+ if (teamWrittenTask(state, group) && !teamAccountPool(state.machines?.find(m => m.machineId === machineId))) failTeamWritten()
+}
+
+export function failTeamWritten(details?: Record<string, unknown>): never {
+ return fail(TEAM_WRITTEN_WORK, TEAM_WRITTEN_REASON, 403, details)
+}
+
+/** Whether [worker] has a step of [group], assigned now or before: it reads or tests that task, and a push of its own shows in GitHub. */
+export const hasStep = (state: SuperTabState, group: Conversation, worker: Agent): boolean =>
+ state.conversations.some(c => c.reviewOf === group.id && (c.assignment?.agentId === worker.id || c.agentIds.includes(worker.id)))
+
+/** Refuses an agent naming a main-account member of Team-written work in a post: how a re-test or re-check is asked for. */
+export function requireNameable(state: SuperTabState, group: Conversation, sender: Agent, named: Agent): void {
+ if (coordinates(state, group, sender) || named.id === sender.id) return
+ requireTeamWrittenAccount(state, group, named)
+}
+
+/** Everyone to tell when [group]'s task has just been marked, by the conversation that reaches them, each once: the main-account
+ * members of the task and of every step, finished steps included, as the workflow asks them again. Not the coordinator. */
+export function mainAccountMembers(state: SuperTabState, group: Conversation, except?: string): Array<{ conversationId: string; agentIds: string[] }> {
+ const task = taskOf(state, group) ?? group
+ const seen = new Set<string>(except ? [except] : [])
+ return [task, ...state.conversations.filter(c => c.reviewOf === task.id)].flatMap(c => {
+ const agentIds = c.agentIds.filter(id => {
+ const member = state.agents.find(a => a.id === id)
+ if (!member || seen.has(id) || onTeamAccount(state, member) || coordinates(state, group, member)) return false
+ seen.add(id)
+ return true
+ })
+ return agentIds.length ? [{ conversationId: c.id, agentIds }] : []
+ })
+}
+
+/** GitHub's record of who pushed: a bot among [group]'s pushes marks its task for good. A clean reading clears nothing. */
+export function applyPushOrigin(state: SuperTabState, group: Conversation, origin: PushOrigin | undefined): void {
+ if (origin !== 'team') return
+ const task = taskOf(state, group)
+ if (task) task.teamWritten = true
+ group.teamWritten = true
+}
+
+export function failPushUnknown(): never {
+ return fail(TEAM_WRITTEN_WORK, 'GitHub could not show who pushed this task\'s code, so it runs only in a Team account for now. Choose an agent in a Team account, or try again in a minute.', 403)
+}
diff --git a/backend/src/superTabs/tidy.test.ts b/backend/src/superTabs/tidy.test.ts
index 7bea43290..80124f0cb 100644
--- a/backend/src/superTabs/tidy.test.ts
+++ b/backend/src/superTabs/tidy.test.ts
@@ -153,7 +153,8 @@ describe('which finished groups archive', () => {
review({ checks: [{ ...verdict, evidence: null, passedBy: null }] }),
review({ id: 'r2', checks: [{ ...verdict, evidence: 'Ready: yes — revision abc', passedBy: 'agent:w' }] }),
review({ id: 'r3', checks: [{ ...verdict, evidence: null, passedBy: null }], assignment: done({ status: 'cancelled' }) })] })
- expect(state.conversations.slice(2).map(g => archivable(state, g, quiet))).toEqual([false, true, true])
+ // A step, with its task open: none, whatever its own verdict says (task steps design).
+ expect(state.conversations.slice(2).map(g => archivable(state, g, quiet))).toEqual([false, false, false])
expect(state.conversations.slice(2).map(g => linkPending(state, g))).toEqual([true, false, false])
// Once the reviewed work is done, its review is moot.
state.conversations[1]!.assignment = done()
@@ -174,9 +175,9 @@ describe('which finished groups archive', () => {
describe('which reviews nobody reviews may close', () => {
const quiet = START + ARCHIVE_QUIET_MS
const PR = 'https://github.com/acme/app/pull/2288', SECOND = 'https://github.com/acme/app/pull/2290'
- /** Work still waiting for its review, linking [built], and its review with no Reviewer, linking [own]. */
- const reviewState = (patch: Partial<Conversation> = {}, built: string[] = [PR], own: string[] = []) => swarm({ groups: [
- group({ assignment: done({ status: 'review' }), pullRequestUrls: built }),
+ /** Work ended, linking [built], and its review with no Reviewer, linking [own]. */
+ const reviewState = (patch: Partial<Conversation> = {}, built: string[] = [PR], own: string[] = [], work: 'done' | 'cancelled' | 'review' | 'working' | 'stopped' | 'lost' = 'done') => swarm({ groups: [
+ group({ assignment: done({ status: work }), pullRequestUrls: built }),
group({ id: 'r1', title: 'Review: Task', reviewOf: 'g1', assignment: null, pullRequestUrls: own, ...patch })] })
const review = (state: SuperTabState) => state.conversations[2]!
@@ -188,6 +189,23 @@ describe('which reviews nobody reviews may close', () => {
}
})
+ it('is never one whose task is open or was lost: it stays with its task, and is not archived while the task may need it', () => {
+ for (const work of ['review', 'working', 'stopped', 'lost'] as const) {
+ const state = reviewState({}, [PR], [], work)
+ expect(reviewClosable(state, review(state), quiet)).toBe(false)
+ }
+ for (const work of ['done', 'cancelled'] as const) {
+ const state = reviewState({}, [PR], [], work)
+ expect(reviewClosable(state, review(state), quiet)).toBe(true)
+ }
+ })
+
+ it('is never one whose task this write did not load', () => {
+ const state = reviewState()
+ state.conversations.splice(1, 1)
+ expect(reviewClosable(state, state.conversations[1]!, quiet)).toBe(false)
+ })
+
it('is never one a Reviewer works on', () => {
for (const status of ['working', 'review', 'needs_human', 'blocked'] as const) {
const state = reviewState({ assignment: done({ status }) })
diff --git a/backend/src/superTabs/tidy.ts b/backend/src/superTabs/tidy.ts
index c866a96b7..5aed2fb1c 100644
--- a/backend/src/superTabs/tidy.ts
+++ b/backend/src/superTabs/tidy.ts
@@ -1,4 +1,4 @@
-import { onlyStepsHeld } from './steps.js'
+import { isStep, onlyStepsHeld, taskEnded } from './steps.js'
import { isBuddy } from './buddies.js'
import { agentDisplayName } from './agentNames.js'
import { activeWork, stableId, type Agent, type Conversation, type MessageDraft, type SuperTabState } from './model.js'
@@ -110,12 +110,13 @@ export const linkPending = (state: SuperTabState, linked: Conversation): boolean
export const ARCHIVE_QUIET_MS = 30 * 60_000
/** Whether a group may archive by itself, as far as the Swarm alone can tell: its task done or cancelled, quiet for
- * ARCHIVE_QUIET_MS, not a linked task still owing its verdict (linkPending), and not a Lead conversation, a
- * private chat with people or the Leads conversation. Its pull requests and decisions are checked by the caller (archive.ts). */
+ * ARCHIVE_QUIET_MS, not a linked task still owing its verdict (linkPending), not a step whose task is still open
+ * (steps.ts taskEnded), and not a Lead conversation, a private chat with people or the Leads conversation. Its pull requests and decisions are checked by the caller (archive.ts). */
export function archivable(state: SuperTabState, group: Conversation, now: number): boolean {
if (state.tidy === false || group.archived || group.kind || group.audience) return false
if (projectsOf(state).some(p => p.leadConversationId === group.id)) return false
if (!['done', 'cancelled'].includes(group.assignment?.status ?? '') || linkPending(state, group)) return false
+ if (isStep(group) && !taskEnded(state, group)) return false
const last = time(group.lastActivityAt)
return last !== undefined && now - last >= ARCHIVE_QUIET_MS
}
@@ -149,11 +150,12 @@ export function reviewPullRequests(state: SuperTabState, review: Conversation):
return [...new Set([...review.pullRequestUrls ?? [], ...reviewed?.pullRequestUrls ?? []])]
}
-/** Whether an unattended review may close by itself, as far as the Swarm alone can tell: it links, or the work it reviews
- * links, a pull request, and it has been quiet for ARCHIVE_QUIET_MS. That each of those pull requests is merged or
+/** Whether an unattended review may close by itself, as far as the Swarm alone can tell: the work it reviews is done or
+ * cancelled, it links, or that work links, a pull request, and it has been quiet for ARCHIVE_QUIET_MS. That each of those pull requests is merged or
* closed, and that no decision waits there, the caller checks (archive.ts, store.ts archiveFinished). */
export function reviewClosable(state: SuperTabState, review: Conversation, now: number): boolean {
if (state.tidy === false || review.archived || review.kind || review.audience || !unattendedReview(review)) return false
+ if (!taskEnded(state, review)) return false
if (projectsOf(state).some(p => p.leadConversationId === review.id)) return false
if (!reviewPullRequests(state, review).length) return false
const last = time(review.lastActivityAt)
diff --git a/cli/src/cloud/bridge.socket.spec.ts b/cli/src/cloud/bridge.socket.spec.ts
new file mode 100644
index 000000000..9cc223274
--- /dev/null
+++ b/cli/src/cloud/bridge.socket.spec.ts
@@ -0,0 +1,180 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { chmodSync, mkdtempSync, writeFileSync } from 'node:fs'
+import { createServer, type Server } from 'node:http'
+import type { AddressInfo } from 'node:net'
+import { join } from 'node:path'
+import { bridgeKey, bridgeSocketPath, harnessKey, retireBridgeKey, rotateHarnessKey, KEY_GRACE_MS } from '../lib/connectors/agents.js'
+import { serveBridgeSocket } from '../lib/connectors/bridge.js'
+import type { LocalSocketServer } from '../lib/localSocket.js'
+import { Store } from '../lib/connectors/store.js'
+import { fakeCore } from '../testing/fakeCore.js'
+import { startConnectors } from '../services/connectors.js'
+import { fetchOverSocket, socketIsPrivate } from '../lib/localTransport.js'
+import { bridgeRoute, connectionsBridge } from './bridge.js'
+import { McpClient } from './mcp.js'
+
+const closers: Array<() => unknown> = []
+afterEach(async () => { vi.useRealTimers(); for (const close of closers.splice(0)) await close() })
+
+let vault: Store, env: NodeJS.ProcessEnv, home: string
+beforeEach(() => {
+ // Short: a socket has to fit.
+ home = mkdtempSync(join('/tmp', 'cs-'))
+ env = { HOME: home, PATH: '', XDG_CONFIG_HOME: join(home, '.config') }
+ vault = new Store(join(home, 'c'), env)
+})
+
+/** Another account on the bridge's port, recording what it hears. */
+async function holder(): Promise<{ heard: string[]; port: number }> {
+ const heard: string[] = []
+ const server = createServer((request, response) => { heard.push(`${request.method} ${request.url}`); response.writeHead(404).end() })
+ await new Promise<void>(ready => server.listen(0, '127.0.0.1', ready))
+ closers.push(() => new Promise(done => { server.closeAllConnections(); server.close(done) }))
+ return { heard, port: (server.address() as AddressInfo).port }
+}
+
+async function service(respond: (url: string, body: string) => { status?: number; body: string; type?: string }): Promise<string> {
+ const server: Server = createServer((request, response) => {
+ let raw = ''
+ request.on('data', part => { raw += part })
+ request.on('end', () => {
+ const answer = respond(request.url ?? '', raw)
+ response.writeHead(answer.status ?? 200, { 'content-type': answer.type ?? 'application/json' }).end(answer.body)
+ })
+ })
+ await new Promise<void>(ready => server.listen(0, '127.0.0.1', ready))
+ closers.push(() => new Promise(done => { server.closeAllConnections(); server.close(done) }))
+ return `http://127.0.0.1:${(server.address() as AddressInfo).port}`
+}
+
+const bridgeRoute2 = (): { fetch: typeof fetch } => ({ fetch: fetchOverSocket(bridgeSocketPath(vault)!) })
+
+const onSocket = async (): Promise<LocalSocketServer> => {
+ const listening = await serveBridgeSocket(vault, bridgeSocketPath(vault)!)
+ closers.push(() => listening.close())
+ return listening
+}
+
+describe('cloud agents and the bridge', () => {
+ it('list, API and MCP calls all go over the socket; a holder of the port hears nothing, Harness\'s key least of all', async () => {
+ const hold = await holder()
+ vi.stubEnv('HARNESS_CONNECTIONS_PORT', String(hold.port))
+ closers.push(() => vi.unstubAllEnvs())
+ const api = await service((url) => ({ body: JSON.stringify({ url }) }))
+ const mcp = await service((_url, body) => {
+ const message = JSON.parse(body) as { id?: number; method: string }
+ return { body: JSON.stringify({ jsonrpc: '2.0', id: message.id, result: message.method === 'tools/list' ? { tools: [{ name: 'a' }] } : { protocolVersion: '2025-06-18' } }) }
+ })
+ vault.save('devin', { access_token: 't', source: 'custom', transport: 'none', api_entry: { origin: api } } as never)
+ vault.save('fo', { access_token: 't', source: 'dcr', mcp_entry: { url: `${mcp}/mcp`, headers: {} } })
+ await onSocket()
+ const bridge = connectionsBridge(() => bridgeRoute(vault))
+ expect((await bridge.connections()).map(c => c.code).sort()).toEqual(['devin', 'fo'])
+ expect((await bridge.api('devin', 'GET', '/v3/self')).status).toBe(200)
+ const client = new McpClient(bridge.mcpUrl('fo'), 'Fo', bridge.fetch)
+ expect((await client.tools()).map(t => t.name)).toEqual(['a'])
+ expect(hold.heard).toEqual([])
+ })
+
+ it('with the socket gone says Connections is not running, and sends nothing to the port', async () => {
+ const hold = await holder()
+ vi.stubEnv('HARNESS_CONNECTIONS_PORT', String(hold.port))
+ closers.push(() => vi.unstubAllEnvs())
+ await expect(connectionsBridge(() => bridgeRoute(vault)).connections()).rejects.toThrow()
+ expect(hold.heard).toEqual([])
+ })
+
+ it('the socket answers Harness\'s key, and an agent\'s route on it still reaches MCP servers only', async () => {
+ const key = harnessKey(vault)
+ await onSocket()
+ const { fetch: over } = bridgeRoute(vault)
+ expect((await over(`http://bridge/${key}/connections`)).status).toBe(200)
+ expect((await over('http://bridge/local/connections')).status).toBe(404)
+ expect((await over('http://bridge/wrong-key/connections')).status).toBe(404)
+ })
+
+ it('a socket that is not private is not used: Harness\'s key reaches nothing, and the port is not tried', async () => {
+ const hold = await holder()
+ vi.stubEnv('HARNESS_CONNECTIONS_PORT', String(hold.port))
+ closers.push(() => vi.unstubAllEnvs())
+ const listening = await onSocket()
+ const bridge = connectionsBridge(() => bridgeRoute(vault))
+ expect(await bridge.connections()).toEqual([])
+ chmodSync(listening.path, 0o666)
+ await expect(bridge.connections()).rejects.toThrow()
+ chmodSync(listening.path, 0o600)
+ // Reading Harness's key tightens the vault's folder, so the route heals this one by itself; the check still says so while it is open.
+ chmodSync(vault.root, 0o777)
+ expect(socketIsPrivate(listening.path)).toBe(false)
+ chmodSync(vault.root, 0o700)
+ expect(socketIsPrivate(listening.path)).toBe(true)
+ expect(hold.heard).toEqual([])
+ })
+
+ it('names a host that resolves nowhere, so the key cannot leave if the address ever reached plain fetch', () => {
+ expect(new URL(bridgeRoute(vault).base).hostname).toMatch(/\.invalid$/)
+ })
+
+ it('an unreadable Harness key refuses Harness\'s calls, and agents\' MCP calls still work', async () => {
+ const fake = await service((_url, body) => ({ body: JSON.stringify({ jsonrpc: '2.0', id: (JSON.parse(body) as { id?: number }).id, result: {} }) }))
+ vault.save('linear', { access_token: 't', source: 'dcr', mcp_entry: { url: `${fake}/mcp`, headers: {} } })
+ harnessKey(vault)
+ await onSocket()
+ writeFileSync(join(vault.root, 'harness-key.json'), 'not json', { mode: 0o600 })
+ const { fetch: over } = bridgeRoute2()
+ const answer = await over('http://bridge/local/linear/mcp', { method: 'POST', body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }) })
+ expect(answer.status).toBe(200)
+ })
+
+ it('where no socket can be, the route is the port, as before', () => {
+ const long = new Store(join(home, 'x'.repeat(120)), env)
+ expect(bridgeSocketPath(long)).toBeNull()
+ expect(bridgeRoute(long).base).toMatch(/^http:\/\/127\.0\.0\.1:\d+\//)
+ })
+})
+
+describe('the keys that crossed the port', () => {
+ it('the service takes Harness\'s key on its socket and not on its port, and the agents\' old key on its port for now', async () => {
+ const agents = bridgeKey(vault), stale = harnessKey(vault)
+ const free = createServer()
+ await new Promise<void>(ready => free.listen(0, '127.0.0.1', ready))
+ const port = (free.address() as AddressInfo).port
+ await new Promise(done => free.close(done))
+ startConnectors(fakeCore(), { vault, env, port, offered: async () => ({}), retryMs: 60_000 })
+ const socket = bridgeRoute(vault)
+ await vi.waitFor(async () => expect((await socket.fetch(`${socket.base}/connections`)).status).toBe(200))
+ await vi.waitFor(async () => expect((await fetch(`http://127.0.0.1:${port}/nope/connections`)).status).toBe(404))
+ expect(harnessKey(vault)).not.toBe(stale)
+ expect((await fetch(`http://127.0.0.1:${port}/${harnessKey(vault)}/connections`)).status).toBe(404)
+ expect((await fetch(`http://127.0.0.1:${port}/${stale}/connections`)).status).toBe(404)
+ // Reached by the key, and nothing is connected under this name.
+ const answer = await fetch(`http://127.0.0.1:${port}/${agents}/nothing/mcp`, { method: 'POST', body: '{}' })
+ expect(await answer.text()).toMatch(/not connected/)
+ expect(typeof vault.file('bridge.json').keyRetiresAt).toBe('number')
+ })
+
+ it('Harness\'s key is replaced once, on the first start that has a socket', () => {
+ const before = harnessKey(vault)
+ rotateHarnessKey(vault)
+ const after = harnessKey(vault)
+ expect(after).not.toBe(before)
+ rotateHarnessKey(vault)
+ expect(harnessKey(vault)).toBe(after)
+ })
+
+ it('the agents\' old key lasts a day from the first start that has a socket, then goes for good', () => {
+ const key = bridgeKey(vault)
+ const start = 1_000_000
+ expect(retireBridgeKey(vault, start)).toBe(key)
+ expect(retireBridgeKey(vault, start + KEY_GRACE_MS - 1)).toBe(key)
+ expect(retireBridgeKey(vault, start + KEY_GRACE_MS)).toBe('')
+ expect(vault.file('bridge.json').key).toBeUndefined()
+ expect(retireBridgeKey(vault, start + 2 * KEY_GRACE_MS)).toBe('')
+ })
+
+ it('a machine with no key has nothing to retire, and its saved port is kept', () => {
+ vault.file('bridge.json')
+ expect(retireBridgeKey(vault, 5)).toBe('')
+ expect(vault.file('bridge.json').keyRetiresAt).toBeUndefined()
+ })
+})
diff --git a/cli/src/cloud/bridge.ts b/cli/src/cloud/bridge.ts
index 13613ffc3..4bbb0f0d1 100644
--- a/cli/src/cloud/bridge.ts
+++ b/cli/src/cloud/bridge.ts
@@ -3,7 +3,8 @@
* connection's credential, so this service holds none (services/AGENTS.md, "Do not hold credentials").
* A connection is found by where it points (Fo's MCP server, Devin's API), not by what the person named it.
*/
-import { bridgePort, harnessKey } from '../lib/connectors/agents.js'
+import { bridgePort, bridgeSocketPath, harnessKey } from '../lib/connectors/agents.js'
+import { fetchOverSocket } from '../lib/localTransport.js'
import { Store } from '../lib/connectors/store.js'
import { CLOUD_AGENTS, type CloudAgentId } from '../lib/cloudAgents.js'
import { CloudError } from './types.js'
@@ -14,25 +15,46 @@ export interface Bridge {
connections(): Promise<Connection[]>
/** The bridge's MCP address for a connection. */
mcpUrl(code: string): string
+ /** How to reach [mcpUrl]: over the bridge's socket where it has one. */
+ fetch?: typeof fetch
/** One call to a key-only connection's API, as JSON. A non-2xx status is the answer, not a throw. */
api(code: string, method: string, path: string, body?: unknown, timeoutMs?: number): Promise<{ status: number; json: Record<string, unknown> }>
}
-/** Through Harness's own key (agents.ts `harnessKey`), never the one in the agents' configurations. */
-export function connectionsBridge(base: () => string = () => {
- const vault = new Store()
- return `http://127.0.0.1:${bridgePort(process.env, vault)}/${harnessKey(vault)}`
-}): Bridge {
+/** Where the bridge is, and how to reach it. */
+export interface BridgeRoute { base: string; fetch: typeof fetch }
+
+/**
+ * Through Harness's own key (agents.ts `harnessKey`), never the one in the agents' configurations, and over the bridge's 0600 socket
+ * where it can have one: whoever holds a port hears what is sent to it (audit H1). With the socket gone Connections is down, and
+ * nothing goes to the port. The address's host is then only a name, one that resolves nowhere (RFC 6761), so the key cannot leave if the
+ * address ever reached plain `fetch`.
+ */
+export function bridgeRoute(vault: Store = new Store()): BridgeRoute {
+ const socket = bridgeSocketPath(vault)
+ return socket
+ ? { base: `http://connections.invalid/${harnessKey(vault)}`, fetch: fetchOverSocket(socket) }
+ : { base: `http://127.0.0.1:${bridgePort(process.env, vault)}/${harnessKey(vault)}`, fetch: (input, init) => fetch(input, init) }
+}
+
+export function connectionsBridge(target: () => string | BridgeRoute = () => bridgeRoute()): Bridge {
+ const route = (): BridgeRoute => {
+ const got = target()
+ return typeof got === 'string' ? { base: got, fetch: (input, init) => fetch(input, init) } : got
+ }
return {
async connections() {
- const answer = await fetch(`${base()}/connections`, { signal: AbortSignal.timeout(10_000) })
+ const { base, fetch: send } = route()
+ const answer = await send(`${base}/connections`, { signal: AbortSignal.timeout(10_000) })
if (!answer.ok) throw new CloudError('CONNECTIONS_UNAVAILABLE', 'Connections is not running here.')
const body = await answer.json() as { connections?: unknown }
return Array.isArray(body.connections) ? body.connections as Connection[] : []
},
- mcpUrl: (code) => `${base()}/${code}/mcp`,
+ mcpUrl: (code) => `${route().base}/${code}/mcp`,
+ fetch: (input, init) => route().fetch(input, init),
async api(code, method, path, body, timeoutMs = 30_000) {
- const answer = await fetch(`${base()}/${code}/api${path}`, {
+ const { base, fetch: send } = route()
+ const answer = await send(`${base}/${code}/api${path}`, {
method,
headers: { accept: 'application/json', ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
body: body === undefined ? undefined : JSON.stringify(body),
diff --git a/cli/src/cloud/mcp.ts b/cli/src/cloud/mcp.ts
index 57019e8df..33b23abfe 100644
--- a/cli/src/cloud/mcp.ts
+++ b/cli/src/cloud/mcp.ts
@@ -28,11 +28,11 @@ export class McpClient {
private ready: Promise<void> | null = null
private next = 1
- constructor(private readonly url: string, private readonly name: string) {}
+ constructor(private readonly url: string, private readonly name: string, private readonly send: typeof fetch = (input, init) => fetch(input, init)) {}
private async post(message: Record<string, unknown>, timeoutMs: number, signal?: AbortSignal): Promise<{ status: number; type: string; body: string; session: string | null }> {
const timeout = AbortSignal.timeout(timeoutMs)
- const answer = await fetch(this.url, {
+ const answer = await this.send(this.url, {
method: 'POST',
headers: {
accept: 'application/json, text/event-stream', 'content-type': 'application/json', 'mcp-protocol-version': PROTOCOL,
diff --git a/cli/src/cloud/service.ts b/cli/src/cloud/service.ts
index 62027672a..50a2753c3 100644
--- a/cli/src/cloud/service.ts
+++ b/cli/src/cloud/service.ts
@@ -97,7 +97,7 @@ export function startCloudService(options: CloudServiceOptions) {
fo: options.adapters?.fo ?? foAdapter(async () => {
const url = bridge.mcpUrl(await codeFor('fo')())
let client = mcpClients.get(url)
- if (!client) { client = new McpClient(url, CLOUD_AGENTS.fo.name); mcpClients.set(url, client) }
+ if (!client) { client = new McpClient(url, CLOUD_AGENTS.fo.name, bridge.fetch); mcpClients.set(url, client) }
return client
}),
'devin-cloud': options.adapters?.['devin-cloud'] ?? devinAdapter(bridge, codeFor('devin-cloud')),
diff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.ts
index 212148530..9ae3a1cd9 100644
--- a/cli/src/core/agents/create.spec.ts
+++ b/cli/src/core/agents/create.spec.ts
@@ -78,6 +78,9 @@ const { preTrustClaudeProject, preTrustCodexProject, acceptFullMode } = trust
vi.mock('../../engines/launchPrep.js', () => ({ acceptFullMode: trust.acceptFullMode, folderTrust: (engine: string, profile?: string | null) => engine === 'claude'
? { trusts: (path: string) => trust.claudeTrusts(path), record: (path: string) => trust.preTrustClaudeProject(path) }
: engine === 'codex' ? { trusts: (path: string) => trust.codexTrusts(path, profile), record: (path: string) => trust.preTrustCodexProject(path, profile) } : null }))
+// The connections an agent on a profile home is given (lib/connectors/agents.ts): never written into a real folder here.
+const syncProfileHome = vi.hoisted(() => vi.fn((_vault: unknown, _engine: string, _home: string): string[] => []))
+vi.mock('../../lib/connectors/agents.js', () => ({ syncProfileHome }))
vi.mock('../../lib/createAgentPane.js', () => ({ createAndRegisterPane: vi.fn() }))
// The Harness GitHub App's launch writes files in the daemon's folder (lib/swarmGitHub.ts): never this machine's here.
vi.mock('../../lib/swarmGitHub.js', () => ({ swarmGitHubLaunch: vi.fn(() => null) }))
@@ -569,6 +572,23 @@ describe('creating an agent', () => {
expect(createAndRegisterPane).toHaveBeenCalledTimes(1)
})
+ it('gives an agent on a Claude or Codex profile home the connections there, and one on the default home none', async () => {
+ const { create } = setup()
+ expect(await create(request({ engine: 'claude', claudeHome: '/profiles/claude-work' }))).toMatchObject({ ok: true })
+ expect(await create(request({ engine: 'codex', codexHome: '/profiles/codex-work' }))).toMatchObject({ ok: true })
+ expect(syncProfileHome.mock.calls.map(([, engine, home]) => [engine, home])).toEqual([['claude', '/profiles/claude-work'], ['codex', '/profiles/codex-work']])
+ syncProfileHome.mockClear()
+ expect(await create(request({ engine: 'claude' }))).toMatchObject({ ok: true })
+ expect(await create(request({ engine: 'codex' }))).toMatchObject({ ok: true })
+ expect(await create(request({ engine: 'opencode', claudeHome: '/profiles/claude-work' }))).toMatchObject({ ok: true })
+ expect(syncProfileHome).not.toHaveBeenCalled()
+ })
+
+ it('still launches when the connections cannot be written into a profile home', async () => {
+ syncProfileHome.mockImplementationOnce(() => { throw new Error('read-only') })
+ expect(await setup().create(request({ engine: 'claude', claudeHome: '/profiles/claude-work' }))).toMatchObject({ ok: true })
+ })
+
it('reaches the existing first-install pane route when OpenCode is absent', async () => {
vi.mocked(opencodeMajorVersion).mockResolvedValueOnce(null)
const { create } = setup({ installOpencodePlugin })
diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.ts
index f0e014249..f0a2969c0 100644
--- a/cli/src/core/agents/create.ts
+++ b/cli/src/core/agents/create.ts
@@ -34,6 +34,8 @@ import { agentLaunchArgs, joinedInstructions } from '../../lib/agentAttribution.
import { machineMcpLaunchArgs } from '../../lib/machineMcp.js'
import { writeGridConfigDir } from '../../lib/gridConfigDir.js'
import { describeGridLaunch, gridConfigHandOff, gridConflictingEnvToClear, type GridLaunchAnswer, type GridLaunchMachine, type GridLaunchRequest, type GridWebSearchStatus } from '../../lib/gridLaunchWire.js'
+import { syncProfileHome } from '../../lib/connectors/agents.js'
+import { Store as ConnectionsVault } from '../../lib/connectors/store.js'
import { profileEnvironment } from '../../lib/engineHomes.js'
import { DEFAULT_HARNESS_PERMISSION, freshHarnessEnvironment } from '../../lib/harnessDefaults.js'
import { buildHarnessSessionLabel } from '../../lib/harnessSessionLabel.js'
@@ -151,7 +153,7 @@ export function createAgentCreator({
// Never from a relayed request, which could name any repository here. Codex's trust also sets defaults for the
// person's own sessions in that folder, so it stays theirs to give.
const trustSwarmFolder = !trustEmptyProject && context?.local === true && !dsh && engine === 'claude' && !!input.swarmRole
- && permissionMode === 'full' && await swarmFolder(cwd)
+ && (permissionMode === 'full' || permissionMode === 'teamWritten') && await swarmFolder(cwd)
if (!authority.current()) return stale()
// A harness can pin its permission mode (`dshPinnedPermissionMode`): the Grid harness starts model
// servers, which Codex's sandbox would start without a GPU. Pinned before anything reads the mode,
@@ -319,7 +321,7 @@ export function createAgentCreator({
// The Swarm starts its agents in full mode, so a machine that never accepted full mode's warning stops each one there
// before its first turn (Claude Code's "Yes, I accept", the Mac Studio, 2026-10-26). The Swarm's owner chose that mode
// for it; recorded the way the engine records the person's own yes, in the home this launch reads.
- if (input.swarmRole && permissionMode === 'full') {
+ if (input.swarmRole && (permissionMode === 'full' || permissionMode === 'teamWritten')) {
try { acceptFullMode(engine, native ? { ...native.environment, ...gridLaunch?.env, ...dshEnv } : undefined) }
catch (error) { console.warn(`[agent] full mode acceptance · ${error instanceof Error ? error.message : error}`) }
}
@@ -352,6 +354,12 @@ export function createAgentCreator({
if (!native && codexHome && !hooksDisabled && !await engineHooks.codex.installIn(hookPort, codexHome)) return {
ok: false, error: 'NATIVE_LAUNCH_HELD', detail: 'Waiting to confirm Codex’s hooks in the selected profile.', unavailable: 'native',
}
+ // An agent on a profile home reads that home's MCP config, not the default's: it gets the connections there too.
+ const profileHome = engine === 'claude' ? claudeHome : engine === 'codex' ? codexHome : null
+ if (profileHome && (engine === 'claude' || engine === 'codex')) {
+ try { syncProfileHome(new ConnectionsVault(), engine, profileHome) }
+ catch (error) { console.warn(`[agent] connections for ${profileHome} · ${error instanceof Error ? error.message : error}`) }
+ }
// OpenCode may have upgraded from 1.x to 2.x while this daemon was running. Its new TUI must
// not discover our old server plugin; the cached version probe changes with the executable.
// Native installation is eager. A plugin is how this engine tells the daemon its session.
diff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.ts
index dfc1e4e72..5568c88fb 100644
--- a/cli/src/core/agents/launches.spec.ts
+++ b/cli/src/core/agents/launches.spec.ts
@@ -1127,6 +1127,11 @@ describe('agent_resume and agent_restart', () => {
expect(vi.mocked(resume!).mock.calls).toEqual([['a1'], ['a1', 'plan']])
})
+ it('refuse a resume that would trade Team-written work\'s mode for another: its project settings stay off (audit H2)', async () => {
+ const run = setup({ byAgent: (id: string) => id === 'written' ? { ...session('written'), permissionMode: 'teamWritten' } : undefined })
+ expect(await run.relaunch('agent_resume', { agentId: 'written', permissionMode: 'full' })).toStrictEqual({ error: 'INVALID_PERMISSION_MODE' })
+ })
+
it('refuse a request with no agent, on a machine that cannot relaunch, and a permission mode a restart has no use for', async () => {
const { relaunch, restart } = setup()
expect(await relaunch('agent_restart', {})).toStrictEqual({ error: 'MISSING_AGENT_ID' })
diff --git a/cli/src/core/agents/launches.ts b/cli/src/core/agents/launches.ts
index 86043a42d..682208ea8 100644
--- a/cli/src/core/agents/launches.ts
+++ b/cli/src/core/agents/launches.ts
@@ -146,7 +146,7 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
// 2026-10-30, a new Swarm made with Cmd+S on a local openharness checkout started its PM in a worktree of it, and
// the PM sat at Claude Code's trust question, which no Swarm view shows; it read Idle and every message to it was
// withheld. Only from a local frame: a relayed request could name any repository on this machine.
- const swarmAgent = input.engine === 'claude' && !!input.swarmRole && input.permissionMode === 'full'
+ const swarmAgent = input.engine === 'claude' && !!input.swarmRole && (input.permissionMode === 'full' || input.permissionMode === 'teamWritten')
const swarmCheckout = swarmAgent && (projectFolder.source === 'remote' || (projectFolder.source === 'worktree' && local))
try {
// A Codex agent on its own profile reads its trust from that profile's config.toml, not ~/.codex.
@@ -608,6 +608,10 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
|| !['ask', 'auto', 'plan', 'full'].includes(permissionMode))) {
reply({ error: 'INVALID_PERMISSION_MODE' }); return
}
+ // Team-written work keeps its project settings off: no resume trades that mode for another (audit H2).
+ if (permissionMode !== undefined && byAgent(target)?.permissionMode === 'teamWritten') {
+ reply({ error: 'INVALID_PERMISSION_MODE' }); return
+ }
const invoke = () => permissionMode === undefined ? restart(target) : resumeAgent()!(target, permissionMode)
const creationId = payload.creationId
if (creationId !== undefined) {
diff --git a/cli/src/core/experimentQueries.spec.ts b/cli/src/core/experimentQueries.spec.ts
index 9a6511d54..bcc5eea4a 100644
--- a/cli/src/core/experimentQueries.spec.ts
+++ b/cli/src/core/experimentQueries.spec.ts
@@ -297,6 +297,25 @@ it('exposes identity-bound close only to the Swarm service and validates its nat
expect(await answerExperimentQuery(fakeCore(), allowed, 'superTabs', 'close_swarm', payload)).toEqual({ error: 'UNSUPPORTED' })
})
+it('asks the core about the agents it is given, keeping only the first 64 ids that are strings, to the Swarm service alone', async () => {
+ const activity = vi.fn(async (ids: string[]) => Object.fromEntries(ids.map(id => [id, 'working' as const])))
+ const core = fakeCore({ agents: { activity } } as never)
+ const allowed = new Set(['superTabs', 'orchestrator'])
+ expect(await answerExperimentQuery(core, allowed, 'superTabs', 'activity', { agentIds: ['a', 4, null, 'b'] })).toEqual({ activity: { a: 'working', b: 'working' } })
+ expect(activity).toHaveBeenLastCalledWith(['a', 'b'])
+ const many = Array.from({ length: 70 }, (_, i) => `agent-${i}`)
+ await answerExperimentQuery(core, allowed, 'superTabs', 'activity', { agentIds: many })
+ expect(activity).toHaveBeenLastCalledWith(many.slice(0, 64))
+ // Without a list of ids, the core is asked about none rather than failing.
+ for (const payload of [{}, { agentIds: 'a' }, { agentIds: { 0: 'a' } }]) {
+ expect(await answerExperimentQuery(core, allowed, 'superTabs', 'activity', payload)).toEqual({ activity: {} })
+ expect(activity).toHaveBeenLastCalledWith([])
+ }
+ activity.mockClear()
+ expect(await answerExperimentQuery(core, allowed, 'orchestrator', 'activity', { agentIds: ['a'] })).toEqual({ error: 'NOT_SUPER_TABS' })
+ expect(activity).not.toHaveBeenCalled()
+})
+
it('lets only the Swarm service reopen a Lead or close a member, by a valid agent id', async () => {
const keepLeadAlive = vi.fn(async () => ({ ok: true as const })), closeMember = vi.fn(async () => ({ closed: true as const }))
const core = fakeCore({ agents: { keepLeadAlive, closeMember } })
diff --git a/cli/src/engines/__fixtures__/launch-argv.golden.json b/cli/src/engines/__fixtures__/launch-argv.golden.json
index c73a62ba0..c4385ac0f 100644
--- a/cli/src/engines/__fixtures__/launch-argv.golden.json
+++ b/cli/src/engines/__fixtures__/launch-argv.golden.json
@@ -733,6 +733,7 @@
"claude · new, mode ask · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","--permission-mode","default"],"script":"7b9a7551f122ab5c","command":3},
"claude · new, mode buddy · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","--permission-mode","dontAsk","--setting-sources","local","--strict-mcp-config"],"script":"7b9a7551f122ab5c","command":6},
"claude · new, mode full · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","--dangerously-skip-permissions"],"script":"7b9a7551f122ab5c","command":2},
+ "claude · new, mode teamWritten · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","--dangerously-skip-permissions","--setting-sources","user","--strict-mcp-config"],"script":"7b9a7551f122ab5c","command":5},
"claude · first prompt · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","Fix the \"parser\" — it's broken; $HOME stays literal, as does `date` and a 'quote' ✓"],"script":"7b9a7551f122ab5c","command":2},
"claude · resume · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","--resume","sess-0001"],"script":"7b9a7551f122ab5c","command":3},
"claude · resume, approving · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","--permission-mode","auto","--resume","sess-0001"],"script":"7b9a7551f122ab5c","command":5},
@@ -761,6 +762,7 @@
"codex · new, mode readOnly · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","--sandbox","read-only","-c","tui.fullscreen_transcript=false"],"script":"533ec1354e8b74a3","command":5},
"codex · new, mode ask · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","-c","tui.fullscreen_transcript=false"],"script":"533ec1354e8b74a3","command":3},
"codex · new, mode full · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","--dangerously-bypass-approvals-and-sandbox","-c","tui.fullscreen_transcript=false"],"script":"533ec1354e8b74a3","command":4},
+ "codex · new, mode teamWritten · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","--dangerously-bypass-approvals-and-sandbox","-c","tui.fullscreen_transcript=false"],"script":"533ec1354e8b74a3","command":4},
"codex · first prompt · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","-c","tui.fullscreen_transcript=false","Fix the \"parser\" — it's broken; $HOME stays literal, as does `date` and a 'quote' ✓"],"script":"533ec1354e8b74a3","command":4},
"codex · resume · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","resume","sess-0001","-c","tui.fullscreen_transcript=false"],"script":"533ec1354e8b74a3","command":5},
"codex · resume, approving · zsh · tmux": {"argv":["/usr/bin/env","DISABLE_AUTO_UPDATE=true","/bin/zsh","-lic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","resume","sess-0001","--approve-for-me","-c","tui.fullscreen_transcript=false"],"script":"533ec1354e8b74a3","command":6},
@@ -966,6 +968,7 @@
"claude · new, mode ask · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","--permission-mode","default"],"script":"6d299a48b039bf1e","command":3},
"claude · new, mode buddy · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","--permission-mode","dontAsk","--setting-sources","local","--strict-mcp-config"],"script":"6d299a48b039bf1e","command":6},
"claude · new, mode full · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","--dangerously-skip-permissions"],"script":"6d299a48b039bf1e","command":2},
+ "claude · new, mode teamWritten · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","--dangerously-skip-permissions","--setting-sources","user","--strict-mcp-config"],"script":"6d299a48b039bf1e","command":5},
"claude · first prompt · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","Fix the \"parser\" — it's broken; $HOME stays literal, as does `date` and a 'quote' ✓"],"script":"6d299a48b039bf1e","command":2},
"claude · resume · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","--resume","sess-0001"],"script":"6d299a48b039bf1e","command":3},
"claude · resume, approving · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","claude","--permission-mode","auto","--resume","sess-0001"],"script":"6d299a48b039bf1e","command":5},
@@ -1073,6 +1076,7 @@
"codex · new, mode readOnly · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","--sandbox","read-only","-c","tui.fullscreen_transcript=false"],"script":"585ef6d2032354bb","command":5},
"codex · new, mode ask · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","-c","tui.fullscreen_transcript=false"],"script":"585ef6d2032354bb","command":3},
"codex · new, mode full · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","--dangerously-bypass-approvals-and-sandbox","-c","tui.fullscreen_transcript=false"],"script":"585ef6d2032354bb","command":4},
+ "codex · new, mode teamWritten · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","--dangerously-bypass-approvals-and-sandbox","-c","tui.fullscreen_transcript=false"],"script":"585ef6d2032354bb","command":4},
"codex · first prompt · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","-c","tui.fullscreen_transcript=false","Fix the \"parser\" — it's broken; $HOME stays literal, as does `date` and a 'quote' ✓"],"script":"585ef6d2032354bb","command":4},
"codex · resume · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","resume","sess-0001","-c","tui.fullscreen_transcript=false"],"script":"585ef6d2032354bb","command":5},
"codex · resume, approving · bash · no tmux": {"argv":["/bin/bash","-ic",". '<data>/launch/<one-time>.sh'","harness-engine","codex","resume","sess-0001","--approve-for-me","-c","tui.fullscreen_transcript=false"],"script":"585ef6d2032354bb","command":6},
diff --git a/cli/src/engines/claude/launch.ts b/cli/src/engines/claude/launch.ts
index ce077ffd2..a9126508f 100644
--- a/cli/src/engines/claude/launch.ts
+++ b/cli/src/engines/claude/launch.ts
@@ -15,6 +15,12 @@ const permissionModes = {
// Harness's own hooks are copied into those settings (lib/swarmSkills.ts).
buddy: ['--permission-mode', 'dontAsk', '--setting-sources', 'local', '--strict-mcp-config'],
full: ['--dangerously-skip-permissions'],
+ // Code a Harness Team agent wrote, in a Team account (backend superTabs/teamWritten.ts, audit H2): full mode, and nothing the
+ // branch carries. `user` and not `local`: a branch can commit `.claude/settings.local.json`. Harness's hooks are in the user
+ // settings. Claude Code 2.1.316, tried: planted settings.json, settings.local.json and .mcp.json each ran in a trusted
+ // folder without these flags, and none with them. With no trust record the session stops at the trust question, so the record
+ // stays and the flags are the barrier; a Yes on the main repository answers for its worktrees anyway.
+ teamWritten: ['--dangerously-skip-permissions', '--setting-sources', 'user', '--strict-mcp-config'],
}
export const launch: EngineLaunch = {
permissionModes, bypassPermission: permissionModes.auto,
diff --git a/cli/src/engines/codex/launch.ts b/cli/src/engines/codex/launch.ts
index 8d301e013..593d3ca6f 100644
--- a/cli/src/engines/codex/launch.ts
+++ b/cli/src/engines/codex/launch.ts
@@ -12,6 +12,10 @@ const permissionModes = {
readOnly: ['--sandbox', 'read-only'],
ask: [],
full: ['--dangerously-bypass-approvals-and-sandbox'],
+ // Code a Harness Team agent wrote, in a Team account (backend superTabs/teamWritten.ts, audit H2). Codex has no flag for it: a
+ // worktree takes its main repository's trust, and `-c projects...` does not turn it off (0.165.0, tried). The start gives
+ // this mode an engine home of its own, which trusts no project (superTabs/start.ts).
+ teamWritten: ['--dangerously-bypass-approvals-and-sandbox'],
}
/**
diff --git a/cli/src/lib/commander.ts b/cli/src/lib/commander.ts
index 0c71c6de0..f770122af 100644
--- a/cli/src/lib/commander.ts
+++ b/cli/src/lib/commander.ts
@@ -837,7 +837,7 @@ export class CommanderMirror {
if (!decide) tell(null)
// Not news (a sub-agent's, a replay, a turn waiting on an answer): silent, and nobody is asked.
else if (!notification) tell('silent')
- // The recap first, as the dial's decision always read it (services/devices.ts): Jev keeps 600 characters.
+ // The recap first, as the dial's decision always read it (services/devices.ts).
else this.tellOnceDecided(decide, ac, { sessionId, recap: recap || body, durationS, stats }, tell)
} else {
this.opts.changed?.(sessionId)
diff --git a/cli/src/lib/connectors/README.md b/cli/src/lib/connectors/README.md
index 4c4085157..ce2c19ecb 100644
--- a/cli/src/lib/connectors/README.md
+++ b/cli/src/lib/connectors/README.md
@@ -89,7 +89,8 @@ falls back to a port, so whoever holds a port hears no tool call:
Where no socket can be (Windows, or a folder too long for one), the entry is still the address
`http://127.0.0.1:51793/<capability>/<code>/mcp`. The port also stays for clients already running on it until they
-restart, and for Harness's own cloud agents.
+restart: its old key lasts a day from the first start with a socket, then goes (`retireBridgeKey`). Harness's own cloud agents use
+the socket too, with Harness's key, which that listener alone accepts where a socket can be.
Only names recorded in `projections.json` are changed or removed; a server the person added keeps its
name and contents, a config that is not plain JSON is left alone, and a symlinked config is written
@@ -97,6 +98,12 @@ through its link. The daemon writes the entries again as it starts, so an agent
service was connected gets it too. An agent reads its MCP servers when it starts: one already running
sees a new connection after it is restarted.
+An agent started under a Claude profile (`CLAUDE_CONFIG_DIR`) or a Codex profile (`CODEX_HOME`), such as a switched PM, reads that
+folder's `.claude.json` or `config.toml`, not the default's. Launching it writes the same entries there (`syncProfileHome`) and
+records the folder in `projections.json` as `claude:<folder>` / `codex:<folder>`; every later sync keeps it current, and a folder
+that is gone is forgotten. Only a Codex folder this machine lists as a profile is written, never through a link that leaves the folder,
+and a home that cannot be written is logged without stopping the others.
+
The bridge (`bridge.ts`) checks the capability, refuses browser requests (any `Origin`), renews a token
within five minutes of expiry, forwards the MCP request with the stored headers and streams the answer,
event streams included. A token the service rejects is renewed once; a revoked grant marks the
diff --git a/cli/src/lib/connectors/agents.ts b/cli/src/lib/connectors/agents.ts
index b5d789cd4..dedd44722 100644
--- a/cli/src/lib/connectors/agents.ts
+++ b/cli/src/lib/connectors/agents.ts
@@ -11,7 +11,8 @@
import { randomBytes } from 'node:crypto'
import { existsSync, readFileSync, realpathSync, renameSync, writeFileSync, mkdirSync, statSync } from 'node:fs'
import { homedir } from 'node:os'
-import { delimiter, dirname, join } from 'node:path'
+import { delimiter, dirname, isAbsolute, join, resolve, sep } from 'node:path'
+import { defaultCodexHome, listCodexProfiles } from '../codexProfiles.js'
import { managedNodePath } from '../nodeRuntime.js'
import { MCP_SHIM_SOURCE } from './mcpShimSource.js'
import { CODE, locked, writePrivate, type Store } from './store.js'
@@ -62,11 +63,43 @@ export function harnessKey(vault: Store): string {
const key = vault.file('harness-key.json').key
if (typeof key === 'string' && key.length >= 32) return key
const fresh = randomBytes(32).toString('base64url')
- writePrivate(join(vault.root, 'harness-key.json'), { key: fresh })
+ writePrivate(join(vault.root, 'harness-key.json'), { ...vault.file('harness-key.json'), key: fresh })
return fresh
})
}
+/** How long the agents' key still opens the port once its entries have moved to the shim: running agents keep the address they read. */
+export const KEY_GRACE_MS = 24 * 60 * 60_000
+
+/**
+ * The agents' key where a socket can be, for the port's listener to compare against, or '' once it is retired. It has crossed the
+ * port, so a holder may have heard it (audit H1). It lasts [KEY_GRACE_MS] from the first time this is asked, then goes for good.
+ * Agents' entries no longer hold it; one still running from an old address answers "unknown" until it restarts.
+ */
+export function retireBridgeKey(vault: Store, now: number = Date.now()): string {
+ const seen = vault.file('bridge.json')
+ if (typeof seen.key !== 'string') return ''
+ if (typeof seen.keyRetiresAt === 'number' && now < seen.keyRetiresAt) return seen.key
+ return locked(vault.root, () => {
+ const { key, keyRetiresAt, ...rest } = vault.file('bridge.json')
+ if (typeof key !== 'string') return ''
+ if (typeof keyRetiresAt === 'number' && now >= keyRetiresAt) {
+ writePrivate(join(vault.root, 'bridge.json'), rest)
+ return ''
+ }
+ if (typeof keyRetiresAt !== 'number') writePrivate(join(vault.root, 'bridge.json'), { ...rest, key, keyRetiresAt: now + KEY_GRACE_MS })
+ return key
+ })
+}
+
+/** Replaces Harness's own key once where a socket can be: it crossed the port until now, and from here on it never does. */
+export function rotateHarnessKey(vault: Store): void {
+ locked(vault.root, () => {
+ if (vault.file('harness-key.json').socketOnly === true) return
+ writePrivate(join(vault.root, 'harness-key.json'), { key: randomBytes(32).toString('base64url'), socketOnly: true })
+ })
+}
+
export function bridgeUrl(key: string, code: string, port = bridgePort()): string {
return `http://127.0.0.1:${port}/${key}/${code}/mcp`
}
@@ -117,6 +150,21 @@ function replace(file: string, text: string): void {
renameSync(tmp, target)
}
+/** The real path of [path], or its absolute form where it does not exist yet. */
+function real(path: string): string {
+ try { return realpathSync(path) } catch { return resolve(path) }
+}
+
+/**
+ * Whether the config [file] is inside the profile [folder] once symlinks are followed. A person's dotfiles in the default home
+ * may be links elsewhere; a profile home is only that profile's own, and a link out of it is not written through.
+ */
+function within(folder: string, file: string): boolean {
+ const root = real(folder)
+ const target = existsSync(file) ? real(file) : join(real(dirname(file)), file.slice(dirname(file).length + 1))
+ return target.startsWith(root + sep)
+}
+
export interface Agent {
name: string
installed(): boolean
@@ -126,11 +174,13 @@ export interface Agent {
class JsonAgent implements Agent {
constructor(readonly name: string, private readonly binary: string, private readonly path: string,
- private readonly env: NodeJS.ProcessEnv, private readonly key: string, private readonly entry: (reach: McpEntry) => Record<string, unknown>) {}
+ private readonly env: NodeJS.ProcessEnv, private readonly key: string, private readonly entry: (reach: McpEntry) => Record<string, unknown>,
+ private readonly profile: string | null = null) {}
- installed(): boolean { return existsSync(this.path) || onPath(this.binary, this.env) }
+ installed(): boolean { return !!this.profile || existsSync(this.path) || onPath(this.binary, this.env) }
apply(wanted: Record<string, McpEntry>, owned: string[]): string[] {
+ if (this.profile && !within(this.profile, this.path)) return owned
let data: Record<string, unknown> = {}
if (existsSync(this.path)) {
try { data = JSON.parse(readFileSync(this.path, 'utf8')) } catch { return owned }
@@ -155,10 +205,9 @@ class JsonAgent implements Agent {
/** Codex's config.toml, edited as text: Harness's tables are removed whole and written again at the end. */
class CodexAgent implements Agent {
- readonly name = 'codex'
- constructor(private readonly path: string, private readonly env: NodeJS.ProcessEnv) {}
+ constructor(private readonly path: string, private readonly env: NodeJS.ProcessEnv, readonly name = 'codex', private readonly profile: string | null = null) {}
- installed(): boolean { return existsSync(this.path) || onPath('codex', this.env) }
+ installed(): boolean { return !!this.profile || existsSync(this.path) || onPath('codex', this.env) }
private static header(name: string): RegExp {
const escaped = name.replace(/[.*+?^${}()|[\]\\-]/g, '\\$&')
@@ -166,6 +215,7 @@ class CodexAgent implements Agent {
}
apply(wanted: Record<string, McpEntry>, owned: string[]): string[] {
+ if (this.profile && !within(this.profile, this.path)) return owned
let lines: string[] = []
if (existsSync(this.path)) {
try { lines = readFileSync(this.path, 'utf8').split('\n') } catch { return owned }
@@ -192,19 +242,80 @@ class CodexAgent implements Agent {
}
}
+const claudeEntry = (reach: McpEntry): Record<string, unknown> =>
+ 'url' in reach ? { type: 'http', url: reach.url } : { type: 'stdio', command: reach.command, args: reach.args }
+
+const claudeFile = (env: NodeJS.ProcessEnv): string => join(env.CLAUDE_CONFIG_DIR || home(env), '.claude.json')
+const codexFile = (env: NodeJS.ProcessEnv): string => join(env.CODEX_HOME || join(home(env), '.codex'), 'config.toml')
+
export function agents(env: NodeJS.ProcessEnv = process.env): Agent[] {
const config = env.XDG_CONFIG_HOME || join(home(env), '.config')
return [
- new JsonAgent('claude', 'claude', join(env.CLAUDE_CONFIG_DIR || home(env), '.claude.json'), env, 'mcpServers',
- reach => 'url' in reach ? { type: 'http', url: reach.url } : { type: 'stdio', command: reach.command, args: reach.args }),
- new CodexAgent(join(env.CODEX_HOME || join(home(env), '.codex'), 'config.toml'), env),
+ new JsonAgent('claude', 'claude', claudeFile(env), env, 'mcpServers', claudeEntry),
+ new CodexAgent(codexFile(env), env),
new JsonAgent('opencode', 'opencode', join(config, 'opencode', 'opencode.json'), env, 'mcp',
reach => 'url' in reach ? { type: 'remote', url: reach.url, enabled: true } : { type: 'local', command: [reach.command, ...reach.args], enabled: true }),
]
}
-/** Give every installed agent exactly the connections that have MCP tools (their own, or REST served as MCP). */
-export function sync(vault: Store, env: NodeJS.ProcessEnv = process.env, list: Agent[] = agents(env)): Record<string, string[]> {
+let listedCodex: { key: string; at: number; folders: Set<string> } | null = null
+
+/** The Codex profiles this machine lists (the real paths), read at most every 30 s: discovery reads shell startup files. */
+function codexProfileFolders(env: NodeJS.ProcessEnv): Set<string> {
+ const key = `${home(env)}\0${env.CODEX_HOME ?? ''}`
+ if (!listedCodex || listedCodex.key !== key || Date.now() - listedCodex.at > 30_000) {
+ const environment = Object.fromEntries(Object.entries(env).filter((entry): entry is [string, string] => typeof entry[1] === 'string'))
+ listedCodex = { key, at: Date.now(), folders: new Set(listCodexProfiles([], { home: home(env), environment }).map(profile => profile.path)) }
+ }
+ return listedCodex.folders
+}
+
+/** Test seam: forget the Codex profiles read so far. */
+export function resetProfileCache(): void { listedCodex = null }
+
+/**
+ * The agent for a Claude profile (CLAUDE_CONFIG_DIR) or Codex profile (CODEX_HOME) folder: the default homes' entries, in the
+ * profile's own files. Its name carries the folder, so projections.json records what Harness wrote there apart from the default
+ * home; an agent runs under the folder, so the engine counts as installed. It never writes through a link that leaves the folder.
+ * Null for the default home (the default agent has it, wherever a link leads), for a folder that is not an absolute path and, with
+ * [listed], for a Codex folder this machine does not list as a profile (a Claude folder is checked where the launch is asked for,
+ * core/agents/launches.ts).
+ */
+function profileAgent(engine: 'claude' | 'codex', folder: string, env: NodeJS.ProcessEnv, listed = true): Agent | null {
+ if (!isAbsolute(folder)) return null
+ const name = `${engine}:${folder}`
+ if (engine === 'claude') {
+ if (real(folder) === real(dirname(claudeFile(env)))) return null
+ return new JsonAgent(name, 'claude', join(folder, '.claude.json'), env, 'mcpServers', claudeEntry, folder)
+ }
+ if (real(folder) === defaultCodexHome(home(env), env)) return null
+ if (listed && !codexProfileFolders(env).has(real(folder))) return null
+ return new CodexAgent(join(folder, 'config.toml'), env, name, folder)
+}
+
+/**
+ * The profile homes Harness has written entries into, from projections.json. A folder that is gone took its entries with it; one
+ * that is no longer a profile of this machine has them taken out (`release`). Both are forgotten.
+ */
+function recordedProfiles(record: Record<string, unknown>, env: NodeJS.ProcessEnv): { gone: string[]; agents: Agent[]; release: Agent[] } {
+ const found: { gone: string[]; agents: Agent[]; release: Agent[] } = { gone: [], agents: [], release: [] }
+ for (const key of Object.keys(record)) {
+ const match = /^(claude|codex):(.+)$/.exec(key)
+ if (!match) continue
+ const engine = match[1] as 'claude' | 'codex'
+ const agent = existsSync(match[2]) ? profileAgent(engine, match[2], env) : null
+ if (agent) { found.agents.push(agent); continue }
+ const unlisted = existsSync(match[2]) ? profileAgent(engine, match[2], env, false) : null
+ if (unlisted) found.release.push(unlisted)
+ found.gone.push(key)
+ }
+ return found
+}
+
+type Targets = { agents: Agent[]; gone?: string[]; release?: Agent[]; remember?: string[] }
+
+/** Give the agents in [list] exactly the connections that have MCP tools (their own, or REST served as MCP). */
+function project(vault: Store, env: NodeJS.ProcessEnv, list: (record: Record<string, unknown>) => Targets, waitMs?: number): Record<string, string[]> {
const codes = Object.entries(vault.tokens()).filter(([code, token]) => transport(token) !== 'none' && CODE.test(code)).map(([code]) => code)
const socket = bridgeSocketPath(vault)
const shim = codes.length && socket ? writeShim(vault) : ''
@@ -214,14 +325,51 @@ export function sync(vault: Store, env: NodeJS.ProcessEnv = process.env, list: A
: { url: bridgeUrl(key, code, bridgePort(env, vault)) }]))
return locked(vault.root, () => {
const record = vault.file('projections.json') as Record<string, unknown>
- const changed: Record<string, string[]> = {}
- for (const agent of list) {
+ const { agents: targets, gone = [], release = [], remember = [] } = list(record)
+ const ownedBy = (agent: Agent): string[] => {
const raw = record[agent.name]
- const owned = Array.isArray(raw) ? raw.filter((name): name is string => typeof name === 'string' && CODE.test(name)) : []
+ return Array.isArray(raw) ? raw.filter((name): name is string => typeof name === 'string' && CODE.test(name)) : []
+ }
+ // One agent whose config cannot be written (a read-only home) leaves the others, and what was recorded, as they are.
+ const attempt = (agent: Agent, work: () => void): void => {
+ try { work() } catch (error) { console.warn(`[connections] could not update ${agent.name}: ${error instanceof Error ? error.message : String(error)}`) }
+ }
+ const changed: Record<string, string[]> = {}
+ for (const agent of targets) {
+ const owned = ownedBy(agent)
if ((!owned.length && !codes.length) || !agent.installed()) continue
- changed[agent.name] = agent.apply(wanted, owned)
+ attempt(agent, () => { changed[agent.name] = agent.apply(wanted, owned) })
}
- writePrivate(join(vault.root, 'projections.json'), { ...record, ...changed })
+ for (const agent of release) if (ownedBy(agent).length) attempt(agent, () => { agent.apply({}, ownedBy(agent)) })
+ const kept = Object.fromEntries(Object.entries(record).filter(([name]) => !gone.includes(name)))
+ // A profile home with nothing to write yet is still recorded, so a connection made later reaches it.
+ for (const name of remember) if (!(name in changed) && !(name in kept)) kept[name] = []
+ writePrivate(join(vault.root, 'projections.json'), { ...kept, ...changed })
return changed
+ }, waitMs)
+}
+
+/**
+ * Give every installed agent exactly the connections that have MCP tools, in its default home and in each profile home an agent
+ * was launched under (syncProfileHome), so a connection made or removed later reaches a running profile's config too.
+ */
+export function sync(vault: Store, env: NodeJS.ProcessEnv = process.env, list?: Agent[]): Record<string, string[]> {
+ return project(vault, env, record => {
+ if (list) return { agents: list }
+ const profiles = recordedProfiles(record, env)
+ return { agents: [...agents(env), ...profiles.agents], gone: profiles.gone, release: profiles.release }
})
}
+
+/**
+ * Give the agent about to run under [folder] (its Claude profile or Codex profile) the same entries the default home has. The
+ * default home, a Codex folder this machine does not list as a profile and a link out of the folder change nothing. Called as an
+ * agent launches, so it waits for the vault's lock for seconds, not the half minute a connection change may.
+ */
+export function syncProfileHome(vault: Store, engine: 'claude' | 'codex', folder: string, env: NodeJS.ProcessEnv = process.env): string[] {
+ const agent = profileAgent(engine, folder, env)
+ if (!agent) return []
+ // Desktop's "Add Claude account" names the folder before Claude Code makes it.
+ if (engine === 'claude') mkdirSync(folder, { recursive: true, mode: 0o700 })
+ return project(vault, env, () => ({ agents: [agent], remember: [agent.name] }), 3_000)[agent.name] ?? []
+}
diff --git a/cli/src/lib/connectors/bridge.ts b/cli/src/lib/connectors/bridge.ts
index 99b344aba..a38c4eda4 100644
--- a/cli/src/lib/connectors/bridge.ts
+++ b/cli/src/lib/connectors/bridge.ts
@@ -8,7 +8,7 @@
* goes to a port another account can hold. The port stays for clients still running on it, Windows, and a folder too long for
* a socket.
*
- * Two more addresses serve Harness's own cloud agents (services/cloud.ts), which hold no credential either:
+ * Two more addresses serve Harness's own cloud agents (services/cloud.ts), over the socket where one can be, which hold no credential either:
* - `/<key>/connections`: what is connected, by address and with no secret, so the service finds the
* connection that signs in Fo or Devin by where it points rather than by what the person named it;
* - `/<key>/<code>/api/<path>`: one request to a key-only connection's own API (`api_entry`), with its key.
@@ -73,12 +73,15 @@ export function createBridge(vault: Store, options: BridgeOptions): Server {
return createServer(bridgeHandler(vault, options))
}
-/** The bridge for MCP clients on its 0600 socket: their MCP servers only, as an agent's key reaches (no Harness key here). */
+/** The bridge on its 0600 socket: for MCP clients, their MCP servers only, as an agent's key reaches; for Harness's own key, what it reaches. */
export async function serveBridgeSocket(vault: Store, path: string): Promise<LocalSocketServer> {
// The socket's privacy rests on this folder too, which may be older than this code.
mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
chmodSync(dirname(path), 0o700)
- const listening = await listenLocalSocket(bridgeHandler(vault, { key: () => SOCKET_KEY, socket: true }), path)
+ const listening = await listenLocalSocket(bridgeHandler(vault, { key: () => SOCKET_KEY,
+ // Harness's own calls (cloud/bridge.ts) come here too: its key never crosses the port where this socket can be.
+ // An unreadable key refuses Harness's calls only: agents' MCP calls never needed this file.
+ harnessKey: () => { try { return String(vault.file('harness-key.json').key ?? '') } catch { return '' } }, socket: true }), path)
listening.server.unref()
return listening
}
@@ -184,7 +187,7 @@ function bridgeHandler(vault: Store, options: BridgeOptions): RequestListener {
// as an unknown key is, so the answer does not say the key was right.
// On the 0600 socket the filesystem has already said who the caller is, and a socket's peer has no port to look up.
if (!address || (!options.socket && !await (options.peerAccount ?? peerIsThisAccount)(request.socket))) {
- fail(response, 404, 'Unknown connection address. Run harness connections sync.'); return
+ fail(response, 404, 'Unknown connection address. Restart this agent, or run harness connections sync.'); return
}
if (address.kind === 'list') { list(response); return }
const code = address.code
diff --git a/cli/src/lib/connectors/connectors.spec.ts b/cli/src/lib/connectors/connectors.spec.ts
index 2716c7569..e1cacb6ec 100644
--- a/cli/src/lib/connectors/connectors.spec.ts
+++ b/cli/src/lib/connectors/connectors.spec.ts
@@ -3,14 +3,14 @@
* real provider, ~/.claude or ~/.codex.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync, chmodSync } from 'node:fs'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync, chmodSync } from 'node:fs'
import { createServer, request as httpRequest } from 'node:http'
import type { AddressInfo } from 'node:net'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { managedNodePath } from '../nodeRuntime.js'
import { FakeGateway, FakeService } from '../../testing/connectorServers.js'
-import { bridgeKey, harnessKey, sync } from './agents.js'
+import { bridgeKey, harnessKey, resetProfileCache, sync, syncProfileHome } from './agents.js'
import { createBridge } from './bridge.js'
import { CATALOG, services } from './catalog.js'
import { addApiKey, addCustom, cards, customCode, disconnect, finish, Flows, signInFor } from './connect.js'
@@ -302,6 +302,129 @@ describe('agent configs', () => {
expect(JSON.parse(readFileSync(opencode, 'utf8'))).toEqual({ model: 'opencode/muse' })
})
+ describe('under a profile home', () => {
+ const shim = (code: string) => [join(vault.root, 'mcp-shim.mjs'), '--socket', join(vault.root, 'bridge.sock'), code]
+ beforeEach(() => resetProfileCache())
+ const connect = (...codes: string[]) => { for (const code of codes) vault.save(code, { access_token: 'secret-' + code, source: 'dcr', mcp_entry: { url: `https://mcp.${code}.example/mcp`, headers: {} } }) }
+
+ it('gives an agent on a Claude profile the shim in the profile\'s .claude.json, and the default home as it was', () => {
+ const profile = join(home, '.claude-work')
+ mkdirSync(profile)
+ writeFileSync(join(profile, '.claude.json'), JSON.stringify({ oauthAccount: { emailAddress: '[email protected]' }, mcpServers: { mine: { command: 'mine' } } }))
+ connect('linear')
+ expect(syncProfileHome(vault, 'claude', profile, env)).toEqual(['linear'])
+ const data = JSON.parse(readFileSync(join(profile, '.claude.json'), 'utf8'))
+ expect(data.oauthAccount).toEqual({ emailAddress: '[email protected]' })
+ expect(data.mcpServers).toEqual({ mine: { command: 'mine' }, linear: { type: 'stdio', command: managedNodePath(), args: shim('linear') } })
+ expect(existsSync(join(home, '.claude.json'))).toBe(false)
+ })
+
+ it('gives an agent on a Codex profile the shim in the profile\'s config.toml, and the default home as it was', () => {
+ const profile = join(home, 'codex-work')
+ mkdirSync(profile)
+ writeFileSync(join(profile, 'config.toml'), 'model = "gpt-5"\n')
+ connect('linear')
+ expect(syncProfileHome(vault, 'codex', profile, env)).toEqual(['linear'])
+ expect(readFileSync(join(profile, 'config.toml'), 'utf8'))
+ .toBe(`model = "gpt-5"\n\n[mcp_servers.linear]\ncommand = ${JSON.stringify(managedNodePath())}\nargs = ${JSON.stringify(shim('linear'))}\n`)
+ expect(existsSync(join(home, '.codex', 'config.toml'))).toBe(false)
+ })
+
+ it('keeps the profile current: a later connection arrives, a disconnected one leaves, and a gone folder is forgotten', () => {
+ const claude = join(home, '.claude-work'), codex = join(home, 'codex-work'), gone = join(home, '.claude-gone')
+ for (const folder of [claude, codex, gone]) mkdirSync(folder)
+ for (const folder of [claude, gone]) writeFileSync(join(folder, '.claude.json'), '{}')
+ writeFileSync(join(codex, 'config.toml'), '')
+ expect(syncProfileHome(vault, 'claude', claude, env)).toEqual([]) // Nothing connected yet: the home is only recorded.
+ syncProfileHome(vault, 'codex', codex, env)
+ syncProfileHome(vault, 'claude', gone, env)
+ connect('linear', 'notion')
+ expect(sync(vault, env)).toMatchObject({ [`claude:${claude}`]: ['linear', 'notion'], [`codex:${codex}`]: ['linear', 'notion'] })
+ expect(Object.keys(JSON.parse(readFileSync(join(claude, '.claude.json'), 'utf8')).mcpServers)).toEqual(['linear', 'notion'])
+ vault.disconnect('notion')
+ rmSync(gone, { recursive: true })
+ sync(vault, env)
+ expect(Object.keys(JSON.parse(readFileSync(join(claude, '.claude.json'), 'utf8')).mcpServers)).toEqual(['linear'])
+ expect(readFileSync(join(codex, 'config.toml'), 'utf8')).not.toContain('notion')
+ expect(Object.keys(vault.file('projections.json'))).not.toContain(`claude:${gone}`)
+ vault.disconnect('linear')
+ sync(vault, env)
+ expect(JSON.parse(readFileSync(join(claude, '.claude.json'), 'utf8')).mcpServers).toBeUndefined()
+ expect(readFileSync(join(codex, 'config.toml'), 'utf8')).toBe('')
+ })
+
+ it('writes into a Codex folder only when this machine lists it as a profile', () => {
+ const unlisted = join(home, 'elsewhere')
+ mkdirSync(unlisted)
+ connect('linear')
+ expect(syncProfileHome(vault, 'codex', unlisted, env)).toEqual([])
+ expect(existsSync(join(unlisted, 'config.toml'))).toBe(false)
+ expect(Object.keys(vault.file('projections.json'))).toEqual([])
+ // The folder a native launch picked is not a profile either.
+ expect(syncProfileHome(vault, 'codex', join(home, 'not-yet-made'), env)).toEqual([])
+ expect(existsSync(join(home, 'not-yet-made'))).toBe(false)
+ })
+
+ it('never writes through a link that leaves the profile, nor treats a link to the default home as a profile', () => {
+ const profile = join(home, '.claude-work'), outside = join(home, 'dotfiles', 'claude.json')
+ mkdirSync(profile)
+ mkdirSync(join(home, 'dotfiles'))
+ writeFileSync(outside, '{"mine":true}')
+ symlinkSync(outside, join(profile, '.claude.json'))
+ connect('linear')
+ expect(syncProfileHome(vault, 'claude', profile, env)).toEqual([])
+ expect(readFileSync(outside, 'utf8')).toBe('{"mine":true}')
+ const codex = join(home, 'codex-work')
+ mkdirSync(codex)
+ writeFileSync(join(home, 'dotfiles', 'config.toml'), 'model = "x"\n')
+ symlinkSync(join(home, 'dotfiles', 'config.toml'), join(codex, 'config.toml'))
+ expect(syncProfileHome(vault, 'codex', codex, env)).toEqual([])
+ expect(readFileSync(join(home, 'dotfiles', 'config.toml'), 'utf8')).toBe('model = "x"\n')
+ const alias = join(home, 'alias')
+ symlinkSync(home, alias)
+ expect(syncProfileHome(vault, 'claude', alias, env)).toEqual([])
+ expect(existsSync(join(home, '.claude.json'))).toBe(false)
+ })
+
+ it('keeps one home that cannot be written from stopping the others, and records what was written', () => {
+ if (process.getuid?.() === 0) return // root writes anywhere
+ const locked = join(home, '.claude-locked'), open = join(home, '.claude-open')
+ for (const folder of [locked, open]) { mkdirSync(folder); writeFileSync(join(folder, '.claude.json'), '{}') }
+ syncProfileHome(vault, 'claude', locked, env)
+ syncProfileHome(vault, 'claude', open, env)
+ chmodSync(locked, 0o500)
+ closers.push(() => chmodSync(locked, 0o700))
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ connect('linear')
+ const changed = sync(vault, env)
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining(`claude:${locked}`))
+ warn.mockRestore()
+ expect(changed[`claude:${open}`]).toEqual(['linear'])
+ expect(vault.file('projections.json')[`claude:${open}`]).toEqual(['linear'])
+ expect(JSON.parse(readFileSync(join(open, '.claude.json'), 'utf8')).mcpServers.linear).toBeDefined()
+ chmodSync(locked, 0o700)
+ })
+
+ it('takes its entries out of a Codex folder this machine no longer lists, and forgets it', () => {
+ const folder = join(home, 'once-a-profile')
+ mkdirSync(folder)
+ writeFileSync(join(folder, 'config.toml'), 'model = "x"\n\n[mcp_servers.linear]\ncommand = "node"\nargs = []\n')
+ writePrivate(join(vault.root, 'projections.json'), { [`codex:${folder}`]: ['linear'] })
+ sync(vault, env)
+ expect(readFileSync(join(folder, 'config.toml'), 'utf8')).toBe('model = "x"\n')
+ expect(Object.keys(vault.file('projections.json'))).not.toContain(`codex:${folder}`)
+ })
+
+ it('leaves the default home\'s own file and a path that is not absolute to the default agent', () => {
+ connect('linear')
+ expect(syncProfileHome(vault, 'claude', home, env)).toEqual([])
+ expect(syncProfileHome(vault, 'codex', join(home, '.codex'), env)).toEqual([])
+ expect(syncProfileHome(vault, 'claude', 'relative/profile', env)).toEqual([])
+ expect(existsSync(join(home, '.claude.json'))).toBe(false)
+ expect(Object.keys(vault.file('projections.json'))).toEqual([])
+ })
+ })
+
it('leaves a config it cannot read safely as it is', () => {
const opencode = join(home, '.config', 'opencode', 'opencode.json')
mkdirSync(join(home, '.config', 'opencode'), { recursive: true })
diff --git a/cli/src/lib/connectors/store.ts b/cli/src/lib/connectors/store.ts
index 931cce8fc..7e72dd8d7 100644
--- a/cli/src/lib/connectors/store.ts
+++ b/cli/src/lib/connectors/store.ts
@@ -121,11 +121,11 @@ export function writePrivate(path: string, data: unknown): void {
}
}
-/** One writer at a time across agents, the bridge and the page: an exclusive lock file, waited for. */
-export function locked<T>(dir: string, work: () => T): T {
+/** One writer at a time across agents, the bridge and the page: an exclusive lock file, waited for (`waitMs`, then it throws). */
+export function locked<T>(dir: string, work: () => T, waitMs = 35_000): T {
privateDirectory(dir)
const lock = join(dir, '.lock')
- const deadline = Date.now() + 35_000
+ const deadline = Date.now() + waitMs
for (;;) {
try { closeSync(openSync(lock, 'wx', 0o600)); break } catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw new ConnectorError('Invalid connection lock.')
diff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.ts
index 0337e0907..9c4839ca5 100644
--- a/cli/src/lib/engineLaunch.spec.ts
+++ b/cli/src/lib/engineLaunch.spec.ts
@@ -829,6 +829,9 @@ printf '%s %s' "$harness_status" "$resumed"`], { encoding: 'utf8', stdio: ['igno
// with its person's credentials (Lead, 10-29).
expect(buildEngineCommandArgv('claude', { permissionMode: 'buddy', bypassPermission: true }))
.toEqual([engineBin('claude'), '--permission-mode', 'dontAsk', '--setting-sources', 'local', '--strict-mcp-config'])
+ // Team-written work reads none of the branch's own settings, `settings.local.json` included (audit H2).
+ expect(buildEngineCommandArgv('claude', { permissionMode: 'teamWritten', bypassPermission: true }))
+ .toEqual([engineBin('claude'), '--dangerously-skip-permissions', '--setting-sources', 'user', '--strict-mcp-config'])
// A Codex Buddy: reads in the sandbox, and asks the person at the terminal before anything outside it (Lead, 10-29).
expect(buildEngineCommandArgv('codex', { permissionMode: 'readOnlyAsk', bypassPermission: true }))
.toEqual([engineBin('codex'), '--ask-for-approval', 'on-request', '--sandbox', 'read-only', '-c', 'approvals_reviewer="user"', ...CODEX_SCREEN])
diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.ts
index 0872cec87..0e8f8aced 100644
--- a/cli/src/lib/engineLaunch.ts
+++ b/cli/src/lib/engineLaunch.ts
@@ -77,7 +77,7 @@ export const PERMISSION_MODES: Readonly<Partial<Record<AgentEngine, Readonly<Rec
/** Modes a relaunch never trades for the engine's own default when the engine on disk lacks their flag: a Buddy's, whose
* default would let it act with its person's own credentials (security review 1 of #2087). The relaunch is held. */
-const KEPT_PERMISSION_MODES: ReadonlySet<string> = new Set(['readOnlyAsk', 'buddy'])
+const KEPT_PERMISSION_MODES: ReadonlySet<string> = new Set(['readOnlyAsk', 'buddy', 'teamWritten'])
/** The argv of [mode] for [engine], or null when the engine has no such mode. */
export function permissionModeFlags(engine: AgentEngine, mode: string): readonly string[] | null {
@@ -87,7 +87,7 @@ export function permissionModeFlags(engine: AgentEngine, mode: string): readonly
/** Whether [mode] lets the agent act without stopping to ask — what `bypassPermission` records. */
export function permissionModeApproves(mode: string): boolean {
- return mode === 'auto' || mode === 'full'
+ return mode === 'auto' || mode === 'full' || mode === 'teamWritten'
}
/**
diff --git a/cli/src/lib/localTransport.ts b/cli/src/lib/localTransport.ts
index 585788088..dcbbfafb8 100644
--- a/cli/src/lib/localTransport.ts
+++ b/cli/src/lib/localTransport.ts
@@ -8,9 +8,9 @@
* The folder's mode is the guarantee here, as for every client of this socket (lib/localSocket.ts): nobody else can
* have put a socket in it.
*/
-import { existsSync, readdirSync } from 'node:fs'
+import { existsSync, lstatSync, readdirSync } from 'node:fs'
import { request } from 'node:http'
-import { join } from 'node:path'
+import { dirname, join } from 'node:path'
import { Readable } from 'node:stream'
import type { ReadableStream as NodeReadableStream } from 'node:stream/web'
import { readDaemonRecord } from './daemonRecord.js'
@@ -68,6 +68,25 @@ async function overSocket(socketPath: string, input: Request): Promise<Response>
})
}
+/** Whether [path] is what the daemon makes: a socket of this account's, owner only, in a real folder nobody else can write to. */
+export function socketIsPrivate(path: string): boolean {
+ const uid = process.getuid?.()
+ try {
+ const folder = lstatSync(dirname(path)), file = lstatSync(path)
+ return folder.isDirectory() && (folder.mode & 0o022) === 0 && file.isSocket() && (file.mode & 0o077) === 0
+ && (uid === undefined || (folder.uid === uid && file.uid === uid))
+ } catch { return false }
+}
+
+/** `fetch` that sends every request over the private Unix socket at [socketPath], whatever host its address names, and fails as `fetch` does
+ * when the socket is missing or not private: what is sent can carry a key. */
+export function fetchOverSocket(socketPath: string): typeof fetch {
+ return async (input, init) => {
+ if (!socketIsPrivate(socketPath)) throw new TypeError('fetch failed', { cause: new Error('The socket is missing or not private.') })
+ return overSocket(socketPath, new Request(input, init))
+ }
+}
+
/**
* `fetch` for the daemon on [port] of [dataDir]: a request to its loopback address goes over its socket where it can
* have one. Any other address, such as a storage link, is the ordinary [base].
diff --git a/cli/src/lib/notifyTier.spec.ts b/cli/src/lib/notifyTier.spec.ts
index c9cf4ca3c..119946b9c 100644
--- a/cli/src/lib/notifyTier.spec.ts
+++ b/cli/src/lib/notifyTier.spec.ts
@@ -1,15 +1,13 @@
import { describe, expect, it, vi } from 'vitest'
-import { JevUnavailable } from './jev/jevClient.js'
-import { createTierDecider, fallbackTier, isTier, tierState, type TierInput } from './notifyTier.js'
+import { createTierDecider, fallbackTier, isTier, type TierInput } from './notifyTier.js'
const base: TierInput = {
agent: 'lamp', engine: 'codex', recap: 'Shipped the thing.', durationS: 300,
- stats: { testsPassed: 640, testsFailed: 0, commits: 1 }, subagent: false, onScreen: false, failed: false,
+ stats: { testsPassed: 640, testsFailed: 0, commits: 1 }, subagent: false, onScreen: false, failed: false, swarm: false,
}
-const answer = (choice: string) => ({ tier: { choice, probabilities: { alert: 0.1, list: 0.2, silent: 0.7, [choice]: 0.9 } } })
-const make = (jev: any, extra: object = {}) => {
+const make = (extra: object = {}) => {
const log = vi.fn()
- return { log, decide: createTierDecider({ jev, log, ...extra }) }
+ return { log, decide: createTierDecider({ log, ...extra }) }
}
describe('notifyTier', () => {
@@ -24,104 +22,37 @@ describe('notifyTier', () => {
expect(fallbackTier(null)).toBe('silent')
})
- it('failed → alert by rule, Jev never asked', async () => {
- const jev = vi.fn()
- const { decide } = make(jev)
- const d = await decide({ ...base, failed: true })
- expect(d).toMatchObject({ tier: 'alert', by: 'rule:failed' })
- expect(jev).not.toHaveBeenCalled()
+ it("a harness agent's finished turn alerts", async () => {
+ const { decide } = make()
+ expect(await decide(base)).toMatchObject({ tier: 'alert', by: 'rule:turn' })
})
- it('subagent → silent; onScreen → silent; empty recap → silent', async () => {
- const jev = vi.fn()
- const { decide } = make(jev)
+ it("a Swarm agent's finished turn is silent", async () => {
+ const { decide } = make()
+ expect(await decide({ ...base, swarm: true })).toMatchObject({ tier: 'silent', by: 'rule:swarm' })
+ })
+
+ it('the fixed rules come first', async () => {
+ const { decide } = make()
+ expect(await decide({ ...base, failed: true, swarm: true })).toMatchObject({ tier: 'alert', by: 'rule:failed' })
expect(await decide({ ...base, subagent: true })).toMatchObject({ tier: 'silent', by: 'rule:subagent' })
expect(await decide({ ...base, onScreen: true })).toMatchObject({ tier: 'silent', by: 'rule:onScreen' })
expect(await decide({ ...base, recap: ' ' })).toMatchObject({ tier: 'silent', by: 'rule:empty' })
- expect(jev).not.toHaveBeenCalled()
- })
-
- it('otherwise asks Jev once with recap ≤ 600 chars and recent counts; returns its choice', async () => {
- const jev = vi.fn(async () => answer('list'))
- const { decide } = make(jev)
- const d = await decide({ ...base, recap: 'x'.repeat(2000) })
- expect(d).toMatchObject({ tier: 'list', by: 'jev' })
- expect(jev).toHaveBeenCalledTimes(1)
- const [state, questions] = jev.mock.calls[0] as any[]
- expect(state.recap.length).toBeLessThanOrEqual(600)
- expect(state).toEqual({
- agent: 'lamp (codex)', recap: 'x'.repeat(600), turn: 'ran 300 s; tests 640 passed, 0 failed; 1 commit',
- recent: '0 alerts and 0 list entries in the last 30 minutes',
- })
- expect(Object.keys(questions)).toEqual(['tier'])
- expect(Object.keys(questions.tier.criteria)).toEqual(['alert', 'list', 'silent'])
- })
-
- it('shows Jev four fields of text, as the hosted route takes them (a record of strings, four keys at most)', () => {
- const shapes = [
- tierState(base, { alerts: 2, lists: 5 }),
- tierState({ ...base, agent: '', engine: '', durationS: null, stats: {} }, { alerts: 0, lists: 0 }),
- tierState({ ...base, engine: '', stats: { testsFailed: 2, commits: 3 } }, { alerts: 0, lists: 1 }),
- tierState({ ...base, agent: '', stats: { testsPassed: 4 } }, { alerts: 0, lists: 0 }),
- ]
- for (const state of shapes) {
- expect(Object.keys(state)).toHaveLength(4)
- expect(Object.values(state).every((value) => typeof value === 'string')).toBe(true)
- }
- expect(shapes[0]).toEqual({ agent: 'lamp (codex)', recap: 'Shipped the thing.', turn: 'ran 300 s; tests 640 passed, 0 failed; 1 commit',
- recent: '2 alerts and 5 list entries in the last 30 minutes' })
- expect(shapes[1]).toMatchObject({ agent: 'an agent', turn: 'duration unknown' })
- expect(shapes[2]).toMatchObject({ agent: 'lamp', turn: 'ran 300 s; tests 0 passed, 2 failed; 3 commits' })
- expect(shapes[3]).toMatchObject({ agent: 'an agent (codex)', turn: 'ran 300 s; tests 4 passed, 0 failed' })
- })
-
- it('Jev unavailable / too slow / null answer → fallback by duration', async () => {
- const down = make(vi.fn(async () => { throw new JevUnavailable('NO_KEY', 'no key') }))
- expect(await down.decide(base)).toMatchObject({ tier: 'list', by: 'fallback:NO_KEY' })
- expect(await down.decide({ ...base, durationS: 119 })).toMatchObject({ tier: 'silent' })
- expect(await down.decide({ ...base, durationS: null })).toMatchObject({ tier: 'silent' })
- const slow = make(() => new Promise(() => {}), { budgetMs: 20 })
- expect(await slow.decide(base)).toMatchObject({ tier: 'list', by: 'fallback:timeout' })
- const bad = make(vi.fn(async () => ({})))
- expect(await bad.decide({ ...base, durationS: 10 })).toMatchObject({ tier: 'silent', by: 'fallback:no-answer' })
- // Anything else it throws is not Jev saying why: the rule all the same, said as an error.
- const broken = make(vi.fn(async () => { throw new Error('socket hang up') }))
- expect(await broken.decide(base)).toMatchObject({ tier: 'list', by: 'fallback:error' })
})
- it('jev null → fallback without calling anything', async () => {
- const { decide } = make(null)
- expect(await decide(base)).toMatchObject({ tier: 'list', by: 'fallback:off' })
+ it('takes no Jev', async () => {
+ const log = vi.fn()
+ expect(await createTierDecider({ log })(base)).toMatchObject({ tier: 'alert' })
+ expect('tierState' in (await import('./notifyTier.js'))).toBe(false)
})
- it('logs exactly one line per decision', async () => {
- const { decide, log } = make(vi.fn(async () => answer('alert')))
+ it('logs each decision, then the day\'s count', async () => {
+ const { decide, log } = make()
await decide(base)
await decide({ ...base, failed: true })
- expect(log).toHaveBeenCalledTimes(4) // each decision, then the day's count
+ expect(log).toHaveBeenCalledTimes(4)
expect(log.mock.calls[1][0]).toMatch(/^notify · day \d{4}-\d\d-\d\d · alert 1 · list 0 · silent 0$/)
- expect(log.mock.calls[0][0]).toMatch(/^notify · lamp · alert · jev · .+ · \d+ms$/)
+ expect(log.mock.calls[0][0]).toMatch(/^notify · lamp · alert · rule:turn · turn · \d+ms$/)
expect(log.mock.calls[2][0]).toMatch(/^notify · lamp · alert · rule:failed · .+ · \d+ms$/)
})
-
- it('recent counts: alerts in a 30 min window, older ones drop out', async () => {
- let t = 0
- const jev = vi.fn(async () => answer('alert'))
- const { decide } = make(jev, { now: () => t })
- for (let i = 0; i < 3; i++) { t = i * 60_000; await decide(base) }
- t = 4 * 60_000
- await decide(base)
- expect((jev.mock.calls[3] as any[])[0].recent).toBe('3 alerts and 0 list entries in the last 30 minutes')
- t = 31 * 60_000
- await decide(base)
- expect((jev.mock.calls[4] as any[])[0].recent).toBe('2 alerts and 0 list entries in the last 30 minutes')
- })
-
- it('5 concurrent decisions resolve independently within the budget', async () => {
- const { decide } = make(() => new Promise(() => {}), { budgetMs: 50 })
- const start = Date.now()
- const all = await Promise.all([1, 2, 3, 4, 5].map(() => decide(base)))
- expect(all.every((d) => d.by === 'fallback:timeout')).toBe(true)
- expect(Date.now() - start).toBeLessThan(250)
- })
})
diff --git a/cli/src/lib/notifyTier.ts b/cli/src/lib/notifyTier.ts
index 552caf241..12410504a 100644
--- a/cli/src/lib/notifyTier.ts
+++ b/cli/src/lib/notifyTier.ts
@@ -1,9 +1,8 @@
/**
- * How loudly a finished turn tells the devices: rules first, Jev for the grey zone, a fallback when Jev
- * cannot answer in time (docs/superpowers/specs/2026-10-19-device-notify-tiers-design.md).
+ * How loudly a finished turn tells the devices, by fixed rules and no model: a harness agent's turn alerts, a Swarm
+ * agent's is silent because the Swarm tells its news through chat cards
+ * (docs/superpowers/specs/2026-11-02-device-notify-no-jev-design.md).
*/
-import type { JevChoice, JevDecide } from './jev/jevClient.js'
-import { JevUnavailable } from './jev/jevClient.js'
export type Tier = 'alert' | 'list' | 'silent'
export interface TierInput {
@@ -11,52 +10,18 @@ export interface TierInput {
durationS: number | null // null: unknown start
stats: { testsPassed?: number; testsFailed?: number; commits?: number }
subagent: boolean; onScreen: boolean; failed: boolean
+ swarm: boolean // a Swarm agent (registry row with swarmSkill, or a Team machine)
}
export interface TierDecision { tier: Tier; by: string; detail: string; ms: number }
-const WINDOW_MS = 30 * 60_000
-const RECAP_MAX = 600
const LONG_TURN_S = 120
/** Whether a frame's `tier` is one: anything else is read as no tier at all. */
export const isTier = (value: unknown): value is Tier => value === 'alert' || value === 'list' || value === 'silent'
-/** The rule when Jev cannot say: a turn that ran 120 s or more is worth a glance later, a shorter one is not. */
+/** The rule for a decision superseded before it lands (lib/commander.ts): a turn that ran 120 s or more is worth a glance later, a shorter one is not. */
export const fallbackTier = (durationS: number | null): Tier => (durationS !== null && durationS >= LONG_TURN_S ? 'list' : 'silent')
-const QUESTIONS: Record<string, JevChoice> = {
- tier: {
- type: 'choice',
- instructions: 'An AI coding agent just finished a turn while its owner was looking at something else. Choose how loudly to tell them.',
- criteria: {
- alert: 'A substantial result the person would want to know about now, such as a long task finished, a build or deploy done, or a requested deliverable ready. Less likely when recent already shows several alerts.',
- list: 'Real progress worth a glance later, such as a small feature or a fix with edits.',
- silent: 'Chatter, such as an acknowledgement, a short answer, a no-op, or a step inside a longer job.',
- },
- },
-}
-
-/**
- * What Jev is shown of a turn: four fields of text. Harness's hosted Jev takes nothing else (backend
- * routes/jevRoute.ts: `state` is a record of strings, four keys at most), and on 2026-10-21 every decision
- * there was refused with a 400 — the state carried numbers and nested objects — so every turn fell back
- * to the duration rule and none was ever an alert.
- */
-export function tierState(input: TierInput, recent: { alerts: number; lists: number }): Record<string, string> {
- const { testsPassed, testsFailed, commits } = input.stats
- const turn = [
- input.durationS === null ? 'duration unknown' : `ran ${input.durationS} s`,
- ...(testsPassed !== undefined || testsFailed !== undefined ? [`tests ${testsPassed ?? 0} passed, ${testsFailed ?? 0} failed`] : []),
- ...(commits ? [`${commits} ${commits === 1 ? 'commit' : 'commits'}`] : []),
- ]
- return {
- agent: input.engine ? `${input.agent || 'an agent'} (${input.engine})` : input.agent || 'an agent',
- recap: input.recap.slice(0, RECAP_MAX),
- turn: turn.join('; '),
- recent: `${recent.alerts} alerts and ${recent.lists} list entries in the last 30 minutes`,
- }
-}
-
/** Logs one decision line and the day's running count per tier, so the volume can be read from the log (no storage). */
export function createTally(log: (line: string) => void, now: () => number = Date.now): (agent: string, tier: Tier, by: string, detail: string, ms: number) => void {
let day = ''
@@ -71,53 +36,22 @@ export function createTally(log: (line: string) => void, now: () => number = Dat
}
export function createTierDecider(opts: {
- jev: JevDecide | null; now?: () => number; log: (line: string) => void; budgetMs?: number
- tally?: ReturnType<typeof createTally>
+ now?: () => number; log: (line: string) => void; tally?: ReturnType<typeof createTally>
}): (input: TierInput) => Promise<TierDecision> {
const tally = opts.tally ?? createTally(opts.log, opts.now)
const now = opts.now ?? Date.now
- const budgetMs = opts.budgetMs ?? 1000
- const recent: { at: number; tier: Tier }[] = []
-
- const count = (tier: Tier) => {
- const from = now() - WINDOW_MS
- while (recent.length && recent[0].at <= from) recent.shift()
- return recent.filter((r) => r.tier === tier).length
- }
return async (input) => {
const start = now()
- const finish = (tier: Tier, by: string, detail: string): TierDecision => {
+ const rule = (tier: Tier, name: string): TierDecision => {
const ms = Math.max(0, now() - start)
- if (tier !== 'silent') recent.push({ at: now(), tier })
- tally(input.agent, tier, by, detail, ms)
- return { tier, by, detail, ms }
+ tally(input.agent, tier, `rule:${name}`, name, ms)
+ return { tier, by: `rule:${name}`, detail: name, ms }
}
- const rule = (tier: Tier, name: string) => finish(tier, `rule:${name}`, name)
if (input.failed) return rule('alert', 'failed')
if (input.subagent) return rule('silent', 'subagent')
if (input.onScreen) return rule('silent', 'onScreen')
if (!input.recap.trim()) return rule('silent', 'empty')
-
- const fallback = (reason: string) =>
- finish(fallbackTier(input.durationS), `fallback:${reason}`, input.durationS === null ? 'duration unknown' : `${input.durationS}s`)
- if (!opts.jev) return fallback('off')
-
- const state = tierState(input, { alerts: count('alert'), lists: count('list') })
- const abort = new AbortController()
- let timer: ReturnType<typeof setTimeout> | undefined
- const late = new Promise<'timeout'>((resolve) => { timer = setTimeout(() => { abort.abort(); resolve('timeout') }, budgetMs) })
- try {
- const answers = await Promise.race([opts.jev(state, QUESTIONS, abort.signal), late])
- if (answers === 'timeout') return fallback('timeout')
- const answer = answers.tier
- if (!answer || !(answer.choice in QUESTIONS.tier.criteria)) return fallback('no-answer')
- const p = Object.entries(answer.probabilities).map(([k, v]) => `${k}=${Number(v).toFixed(2)}`).join(',')
- return finish(answer.choice as Tier, 'jev', `p=${p}`)
- } catch (error) {
- return fallback(error instanceof JevUnavailable ? error.code : 'error')
- } finally {
- clearTimeout(timer)
- }
+ return input.swarm ? rule('silent', 'swarm') : rule('alert', 'turn')
}
}
diff --git a/cli/src/services/connectors.ts b/cli/src/services/connectors.ts
index aa2daafe0..2fd2117bd 100644
--- a/cli/src/services/connectors.ts
+++ b/cli/src/services/connectors.ts
@@ -16,7 +16,7 @@
import type { Server } from 'node:http'
import type { AddressInfo } from 'node:net'
import type { CoreApi, ServiceRequests } from '../core/api.js'
-import { bridgePort, bridgeSocketPath, saveBridgePort, sync } from '../lib/connectors/agents.js'
+import { bridgePort, bridgeSocketPath, retireBridgeKey, rotateHarnessKey, saveBridgePort, sync } from '../lib/connectors/agents.js'
import { portHolderIsThisAccount } from '../lib/peerAccount.js'
import { createBridge, serveBridgeSocket } from '../lib/connectors/bridge.js'
import { services, type GatewayRow } from '../lib/connectors/catalog.js'
@@ -103,7 +103,12 @@ export function startConnectors(core: CoreApi, overrides: Partial<ConnectorsDeps
}
const { vault } = deps
const flows = new Flows(vault, env)
- const bridgeKeys = { key: () => String(vault.file('bridge.json').key ?? ''), harnessKey: () => String(vault.file('harness-key.json').key ?? '') }
+ const socket = bridgeSocketPath(vault)
+ // Where a socket can be, the port takes neither key for long: Harness's own goes over the socket, and the agents' retires (agents.ts).
+ if (socket) { try { rotateHarnessKey(vault) } catch (error) { console.warn(`[connections] could not replace Harness's key: ${(error as Error).message}`) } }
+ const bridgeKeys = socket
+ ? { key: () => { try { return retireBridgeKey(vault) } catch { return '' } } }
+ : { key: () => String(vault.file('bridge.json').key ?? ''), harnessKey: () => String(vault.file('harness-key.json').key ?? '') }
const bridge = createBridge(vault, bridgeKeys)
bridge.unref()
// A port a test or HARNESS_CONNECTIONS_PORT names stays that port.
@@ -119,8 +124,9 @@ export function startConnectors(core: CoreApi, overrides: Partial<ConnectorsDeps
listen(old, from, deps.retryMs)
},
} : undefined)
- const socket = bridgeSocketPath(vault)
if (socket) listenSocket(vault, socket, deps.retryMs)
+ // Stamped now, not at a client's first call: the day counts from this start.
+ if (socket) { try { retireBridgeKey(vault) } catch { /* The next request tries again. */ } }
try { sync(vault, env) } catch { /* A config that cannot be written now is written at the next connect. */ }
// Connections the same on every computer of the account: read now, at each `connectors_changed`, and
diff --git a/cli/src/services/devices.spec.ts b/cli/src/services/devices.spec.ts
index 9751981ab..d360e434b 100644
--- a/cli/src/services/devices.spec.ts
+++ b/cli/src/services/devices.spec.ts
@@ -122,19 +122,6 @@ vi.mock('../lib/voiceRouter.js', () => ({
routeVoiceTask: vi.fn(),
}))
-const jevMade = vi.hoisted(() => vi.fn())
-vi.mock('../lib/jev/jevClient.js', async (orig) => {
- const actual = await orig<typeof import('../lib/jev/jevClient.js')>()
- return {
- ...actual,
- createJevDecide: (options: Parameters<typeof actual.createJevDecide>[0]) => {
- jevMade(options)
- // Keep the real hosted request and answer parsing, without discovering a key or calling OpenRouter.
- return actual.createJevDecide({ ...options, key: async () => null })
- },
- }
-})
-
const { startDevices } = await import('./devices.js')
let dataDir: string
@@ -151,6 +138,15 @@ afterEach(() => {
vi.restoreAllMocks()
})
+/** The account's machines: a Harness Team one (`team-mac`) and a computer of the person's own (`mac-mini`). */
+const teamAccount = (core: CoreApi) => {
+ vi.mocked(core.account.machines).mockResolvedValue({ status: 200, body: { success: true, data: { machines: [
+ { machineId: 'team-mac', name: 'Diego’s Mac', sessionKind: 'team' },
+ { machineId: 'mac-mini', name: 'Mac mini', sessionKind: 'computer' },
+ ] } } })
+ return seen.fleet!.deps.machines.refresh()
+}
+
function start(over: { core?: CoreApi; faults?: string[]; cableDisabled?: boolean; testDialPort?: string; readUsage?: DevicesDeps['readUsage']; now?: () => number; decideTier?: DevicesDeps['decideTier'] | null } = {}) {
const core = over.core ?? fakeCore({ dataDir })
const ports: CorePorts = emptyPorts()
@@ -401,41 +397,44 @@ describe('what the windows say, reaching the dial', () => {
})
describe('a summary\'s tier', () => {
- afterEach(() => { delete process.env.HARNESS_NOTIFY_SMART })
- it('builds the default decider without Jev when HARNESS_NOTIFY_SMART is 0, and with it otherwise', () => {
- process.env.HARNESS_NOTIFY_SMART = '0'
- start({ decideTier: null })
- expect(jevMade).not.toHaveBeenCalled()
- delete process.env.HARNESS_NOTIFY_SMART
- start({ decideTier: null })
- expect(jevMade).toHaveBeenCalledTimes(1)
- })
-
- it('asks the signed-in backend for a default tier, sends its answer to the dial, and tallies it', async () => {
- delete process.env.HARNESS_NOTIFY_SMART
- const backend = vi.fn(async () => ({ status: 200, body: { data: { answers: {
- tier: { choice: 'alert', probabilities: { alert: 0.8, list: 0.15, silent: 0.05 } },
- } } } }))
- const core = fakeCore({ dataDir, account: { backend } })
- const { port } = start({ core, decideTier: null })
+ it('decides a card without a tier by the fixed rules: a harness agent alerts, with no Jev call, and it is tallied', async () => {
+ const backend = vi.fn()
+ const { port } = start({ core: fakeCore({ dataDir, account: { backend } }), decideTier: null })
port.card({ type: 'commander_event', agentId: 'a1', payload: { kind: 'summary', text: 'done', recap: 'The requested build is ready.' } })
await vi.waitFor(() => expect(calls('summary')).toEqual([
['a1', 'The requested build is ready.', 'done', 'alert', undefined, false],
]))
- expect(backend).toHaveBeenCalledExactlyOnceWith('POST', '/api/route/jev', {
- state: {
- agent: 'an agent', recap: 'The requested build is ready.', turn: 'duration unknown',
- recent: '0 alerts and 0 list entries in the last 30 minutes',
- },
- questions: { tier: {
- type: 'choice', instructions: expect.any(String),
- criteria: { alert: expect.any(String), list: expect.any(String), silent: expect.any(String) },
- } },
- })
- expect(logs).toContainEqual(expect.stringMatching(/^\[cable\] notify · .* · alert · jev · p=alert=0\.80,list=0\.15,silent=0\.05 · \d+ms$/))
+ expect(backend).not.toHaveBeenCalled()
+ expect(logs).toContainEqual(expect.stringMatching(/^\[cable\] notify · .* · alert · rule:turn · turn · \d+ms$/))
expect(logs).toContainEqual(expect.stringMatching(/^\[cable\] notify · day \d{4}-\d\d-\d\d · alert 1 · list 0 · silent 0$/))
})
+ it.each(['lead', 'buddy', 'agent', 'coordinator'])('decides a local Swarm agent\'s card silent, whatever its role (%s)', async (role) => {
+ const { port } = start({ core: fakeCore({ dataDir, agents: { byAgent: vi.fn(() => ({ agentId: 'a1', swarmSkill: { role, key: 'k' } }) as never) } }), decideTier: null })
+ port.card({ type: 'commander_event', agentId: 'a1', payload: { kind: 'summary', text: 'done', recap: 'Built.' } })
+ await vi.waitFor(() => expect(calls('summary')).toEqual([['a1', 'Built.', 'done', 'silent', undefined, false]]))
+ expect(logs).toContainEqual(expect.stringMatching(/silent · rule:swarm · swarm/))
+ })
+
+ it('decides an agent on a Harness Team machine silent, and one on another computer of the person alert', async () => {
+ const core = fakeCore({ dataDir })
+ const { port } = start({ core, decideTier: null })
+ await teamAccount(core)
+ seen.fleet!.events!({ machineId: 'team-mac', kind: 'summary', agentId: 'reviewer', text: 'done', recap: 'Reviewed.' })
+ seen.fleet!.events!({ machineId: 'mac-mini', kind: 'summary', agentId: 'far', text: 'done', recap: 'Done far.' })
+ await vi.waitFor(() => expect(calls('summary')).toHaveLength(2))
+ expect(calls('summary').map((c) => [c[0], c[3]])).toEqual([['reviewer', 'silent'], ['far', 'alert']])
+ void port
+ })
+
+ it('still decides a remote card that came without a tier, and never throws', async () => {
+ const { port } = start({ decideTier: null })
+ expect(() => seen.fleet!.events!({ machineId: 'mac-mini', kind: 'summary', agentId: 'far', text: 'done', recap: '' })).not.toThrow()
+ await vi.waitFor(() => expect(calls('summary')).toHaveLength(1))
+ expect(calls('summary')[0][3]).toBe('alert') // a harness agent's, whatever machine it ran on
+ void port
+ })
+
it('keeps a recap in the list when the decider rejects', async () => {
const { port } = start({ decideTier: async () => { throw new Error('decision unavailable') } })
port.card({ type: 'commander_event', agentId: 'a1', payload: { kind: 'summary', text: 'done', recap: 'The requested build is ready.', fullText: 'The full build report.' } })
@@ -1151,13 +1150,6 @@ describe('a failed turn of a Swarm worker', () => {
const swarmAgents = (sessions: Array<Partial<RegisteredSession>>) => fakeCore({ dataDir, agents: {
byAgent: vi.fn((id: string) => sessions.find((s) => s.agentId === id) as RegisteredSession | undefined),
} })
- const teamAccount = (core: CoreApi) => {
- vi.mocked(core.account.machines).mockResolvedValue({ status: 200, body: { success: true, data: { machines: [
- { machineId: 'team-mac', name: 'Diego’s Mac', sessionKind: 'team' },
- { machineId: 'mac-mini', name: 'Mac mini', sessionKind: 'computer' },
- ] } } })
- return seen.fleet!.deps.machines.refresh()
- }
it('on a Harness Team account never reaches the dial as an error, and ends its tile quietly', async () => {
const { core } = start()
diff --git a/cli/src/services/devices.ts b/cli/src/services/devices.ts
index 6c8239d0d..53e0a3c36 100644
--- a/cli/src/services/devices.ts
+++ b/cli/src/services/devices.ts
@@ -37,7 +37,6 @@ import { harnessDevicesRequest } from '../lib/harnessDevices.js'
import { machineKindsOf } from '../lib/e2ee/machineKinds.js'
import { truncateUtf8 } from '../lib/deviceRecentTrim.js'
import { setVoiceRouterDeviceConnected, setVoiceRouterSessions, shutdownVoiceRouter } from '../lib/voiceRouter.js'
-import { createJevDecide } from '../lib/jev/jevClient.js'
import { createTally, createTierDecider, type Tier, type TierDecision, type TierInput } from '../lib/notifyTier.js'
import { createPartGuard } from './devicesGuard.js'
import { FLEET_FALLBACKS, startFleet, type Fleet } from './fleet.js'
@@ -59,7 +58,7 @@ export interface DevicesDeps {
/** `HARNESSD_TEST_FAULTS`: parts to fail, for the end-to-end suite. */
faults?: ReadonlySet<string>
log?: (line: string) => void
- /** How loudly a finished turn tells the devices. Defaults to rules plus Jev (off with `HARNESS_NOTIFY_SMART=0`). */
+ /** How loudly a finished turn tells the devices. Defaults to the fixed rules (lib/notifyTier.ts). */
decideTier?: (input: TierInput) => Promise<TierDecision>
/** A monotonic clock in ms (default `performance.now`), for the reply throttle: a wall-clock step must not stall or burst it. */
now?: () => number
@@ -97,7 +96,6 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)
const tally = createTally((line) => log(`[cable] ${line}`))
const tierOf = deps.decideTier ?? createTierDecider({
tally,
- jev: process.env.HARNESS_NOTIFY_SMART === '0' ? null : createJevDecide({ backend: (method, path, body) => core.account.backend(method, path, body) }),
log,
})
const part = createPartGuard({ log, faults: deps.faults })
@@ -368,7 +366,7 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)
if (!start || !cable.wantsStats()) return finish({})
return turnTokens(event.agentId, start).then(finish)
}
- // On screen or a sub-agent's: silent, Jev is not asked. Otherwise the tier decides how loudly the dial tells. The
+ // On screen or a sub-agent's: silent, nobody is asked. Otherwise the tier decides how loudly the dial tells. The
// tile still updates either way — the recap is what it draws.
else if (event.kind === 'summary') {
const { agentId } = event
@@ -390,7 +388,7 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)
}
// Returned, so the agent's next card waits behind this one (inOrder): a late recap must not follow turn.started.
return tierOf({ agent: who?.name ?? '', engine: who?.engine ?? '', recap, durationS: turn?.durationS ?? null,
- stats: turn?.stats ?? {}, subagent: false, onScreen: false, failed: event.failed === true })
+ stats: turn?.stats ?? {}, subagent: false, onScreen: false, failed: event.failed === true, swarm: swarmAgent(event) })
.then((d) => d.tier, () => 'list' as const)
.then((tier) => { void cable.summary(agentId, recap, event.text, tier, event.fullText, false) })
}
@@ -425,6 +423,10 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)
const role = session?.startedBy === 'agent' ? session.swarmSkill?.role : undefined
return role === 'agent' || (!!event.machineId && teamMachines.has(event.machineId))
}
+ /** Any Swarm agent, whatever its role (PM, Buddy, Builder, Reviewer, Tester): its registry row carries `swarmSkill`, or it runs
+ * on a Harness Team account. Its news reaches the dial through the Swarm's cards, so its finished turn is silent. */
+ const swarmAgent = (event: DialEvent): boolean =>
+ (!event.machineId && !!core.agents.byAgent(event.agentId)?.swarmSkill) || (!!event.machineId && teamMachines.has(event.machineId))
/** Whether an agent on another machine is a Swarm's Builder or Reviewer, as the Swarm service read it last
* (superTabs/cards.ts `worker`). Asked once a minute at most per agent: a failing worker fails every 1-2 s. */
const WORKER_ANSWER_MS = 60_000
diff --git a/cli/src/services/recaps.spec.ts b/cli/src/services/recaps.spec.ts
index 4daacea6e..be1de2e89 100644
--- a/cli/src/services/recaps.spec.ts
+++ b/cli/src/services/recaps.spec.ts
@@ -9,19 +9,6 @@ import type { LiveEvent } from '../lib/normalize.js'
import type { TierDecision, TierInput } from '../lib/notifyTier.js'
import { fakeCore } from '../testing/fakeCore.js'
-const jevMade = vi.hoisted(() => vi.fn())
-vi.mock('../lib/jev/jevClient.js', async (orig) => {
- const actual = await orig<typeof import('../lib/jev/jevClient.js')>()
- return {
- ...actual,
- createJevDecide: (options: Parameters<typeof actual.createJevDecide>[0]) => {
- jevMade(options)
- // The real hosted request and answer parsing, without discovering a key on this computer or calling OpenRouter.
- return actual.createJevDecide({ ...options, key: async () => null })
- },
- }
-})
-
const { createRecaps, startRecaps } = await import('./recaps.js')
const dirs: string[] = []
@@ -258,7 +245,6 @@ describe('the recaps', () => {
})
describe('a finished turn\'s tier', () => {
- afterEach(() => { delete process.env.HARNESS_NOTIFY_SMART })
const turn = async (tell: (event: TurnLifecycle, seen?: typeof watching) => void, seen: typeof watching & { remote?: boolean }) => {
// The core says the engine with every event (core/turns/recaps.ts `session`).
tell({ kind: 'events', session: { ...s1, engine: 'codex' }, events: [started()], replay: false }, seen)
@@ -272,7 +258,7 @@ describe('the recaps', () => {
await turn(tell, watching)
await vi.waitFor(() => expect(core.clients.turnSummary).toHaveBeenCalled())
expect(decideTier).toHaveBeenCalledExactlyOnceWith({ agent: 'app', engine: 'codex', recap: expect.any(String),
- durationS: 0, stats: {}, subagent: false, onScreen: false, failed: false })
+ durationS: 0, stats: {}, subagent: false, onScreen: false, failed: false, swarm: false })
expect(vi.mocked(core.clients.turnSummary).mock.calls[0][0]).toMatchObject({ payload: { tier: 'alert' } })
expect(vi.mocked(core.clients.turnCard).mock.calls.at(-1)?.[0].payload).toMatchObject({ kind: 'summary', tier: 'alert' })
})
@@ -292,33 +278,31 @@ describe('the recaps', () => {
expect(vi.mocked(alone.core.clients.turnSummary).mock.calls[0][0].payload).not.toHaveProperty('tier')
})
- it('builds the default decider without Jev when HARNESS_NOTIFY_SMART is 0, and with it otherwise', async () => {
+ const decidedWith = async (row: object | undefined) => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
- jevMade.mockClear()
- process.env.HARNESS_NOTIFY_SMART = '0'
- const off = setup({ decideTier: undefined })
- expect(jevMade).not.toHaveBeenCalled()
- await turn(off.tell, watching)
- await vi.waitFor(() => expect(off.core.clients.turnSummary).toHaveBeenCalled())
- // A turn under two minutes, with nobody to ask: the rule's silence.
- expect(vi.mocked(off.core.clients.turnSummary).mock.calls[0][0]).toMatchObject({ payload: { tier: 'silent' } })
- expect(log).toHaveBeenCalledWith(expect.stringMatching(/^\[recap\] notify · app · silent · fallback:off · 0s · \d+ms$/))
- delete process.env.HARNESS_NOTIFY_SMART
- setup({ decideTier: undefined })
- expect(jevMade).toHaveBeenCalledTimes(1)
- })
-
- it('asks Harness\'s Jev through the core\'s signed-in backend, and sends what it chose', async () => {
- vi.spyOn(console, 'log').mockImplementation(() => {})
- const backend = vi.fn(async () => ({ status: 200, body: { data: { answers: {
- tier: { choice: 'alert', probabilities: { alert: 0.7, list: 0.2, silent: 0.1 } },
- } } } }))
- const { core, tell } = setup({ decideTier: undefined }, fakeCore({ dataDir: temp(), account: { backend } }))
+ const backend = vi.fn()
+ const core = fakeCore({ dataDir: temp(), account: { backend }, agents: { byAgent: vi.fn(() => row as never) } })
+ const { tell } = setup({ decideTier: undefined }, core)
await turn(tell, watching)
await vi.waitFor(() => expect(core.clients.turnSummary).toHaveBeenCalled())
- expect(backend).toHaveBeenCalledExactlyOnceWith('POST', '/api/route/jev', expect.objectContaining({
- state: { agent: 'app (codex)', recap: expect.any(String), turn: 'ran 0 s', recent: '0 alerts and 0 list entries in the last 30 minutes' } }))
- expect(vi.mocked(core.clients.turnSummary).mock.calls[0][0]).toMatchObject({ payload: { tier: 'alert' } })
+ expect(backend).not.toHaveBeenCalled()
+ return { tier: (vi.mocked(core.clients.turnSummary).mock.calls[0][0].payload as { tier?: string }).tier, log }
+ }
+
+ it('decides a harness agent\'s turn alert, with no Jev call', async () => {
+ const { tier, log } = await decidedWith({ agentId: 'a1' })
+ expect(tier).toBe('alert')
+ expect(log).toHaveBeenCalledWith(expect.stringMatching(/^\[recap\] notify · app · alert · rule:turn · turn · \d+ms$/))
+ })
+
+ it.each(['lead', 'buddy', 'agent'])('decides a Swarm agent\'s turn silent, whatever its role (%s)', async (role) => {
+ const { tier, log } = await decidedWith({ agentId: 'a1', swarmSkill: { role, key: 'k' } })
+ expect(tier).toBe('silent')
+ expect(log).toHaveBeenCalledWith(expect.stringMatching(/rule:swarm/))
+ })
+
+ it('decides a turn alert when the agent has no row', async () => {
+ expect((await decidedWith(undefined)).tier).toBe('alert')
})
})
})
diff --git a/cli/src/services/recaps.ts b/cli/src/services/recaps.ts
index 85853285c..5e9a8ed41 100644
--- a/cli/src/services/recaps.ts
+++ b/cli/src/services/recaps.ts
@@ -21,7 +21,6 @@ import type { CoreApi, CorePorts, RecapSession, RecapsPort, RecapWatchers, TurnC
import { AgentNotifications } from '../lib/agentNotifications.js'
import { CommanderMirror, SUBAGENT_IDLE_MS } from '../lib/commander.js'
import { deriveTurnSummary } from '../lib/deviceRecap.js'
-import { createJevDecide } from '../lib/jev/jevClient.js'
import { createTierDecider, type TierDecision, type TierInput } from '../lib/notifyTier.js'
export interface RecapsOptions {
@@ -32,7 +31,7 @@ export interface RecapsOptions {
recapForce?: boolean
/** Whether a recap is cut for every turn, a device watching or not (`RECAP_WITHOUT_DEVICE`). */
recapWithoutDevice?: () => boolean
- /** How loudly a finished turn tells. Defaults to rules plus Jev (off with `HARNESS_NOTIFY_SMART=0`). */
+ /** How loudly a finished turn tells. Defaults to the fixed rules (lib/notifyTier.ts). */
decideTier?: (input: TierInput) => Promise<TierDecision>
}
@@ -59,7 +58,6 @@ export function createRecaps(core: CoreApi, options: RecapsOptions = {}): Recaps
// How loudly each finished turn tells (lib/notifyTier.ts), decided here once for the dial, the phone and the
// window: the `summary` card and the apps' `turn_summary` both carry it, so the devices ask nobody again.
const tierOf = options.decideTier ?? createTierDecider({
- jev: process.env.HARNESS_NOTIFY_SMART === '0' ? null : createJevDecide({ backend: (method, path, body) => core.account.backend(method, path, body) }),
log: (line) => console.log(`[recap] ${line}`),
})
const mirror = new CommanderMirror({
@@ -101,12 +99,14 @@ export function createRecaps(core: CoreApi, options: RecapsOptions = {}): Recaps
alwaysGenerate: () => options.recapWithoutDevice?.() ?? env.RECAP_WITHOUT_DEVICE,
changed: options.changed,
// Asked only while someone away from this desk can hear it — a device, or an app over the relay. The window
- // here does not read a tier, so with neither there is nothing to decide and no Jev decision to pay for.
+ // here does not read a tier, so with neither there is nothing to decide.
decideTier: async (turn) => {
if (!watchers.device && !watchers.remote) return null
const session = sessions.get(turn.sessionId)
+ // A Swarm agent tells its news through the Swarm's chat cards, so its turn is silent on the devices.
+ const swarm = !!(session && core.agents.byAgent(session.agentId)?.swarmSkill)
const decision = await tierOf({ agent: session?.name ?? '', engine: session?.engine ?? '', recap: turn.recap,
- durationS: turn.durationS, stats: turn.stats, subagent: false, onScreen: false, failed: false })
+ durationS: turn.durationS, stats: turn.stats, subagent: false, onScreen: false, failed: false, swarm })
return decision.tier
},
})
diff --git a/cli/src/superTabs/cloneTrust.spec.ts b/cli/src/superTabs/cloneTrust.spec.ts
index bfcd6a387..02a52b352 100644
--- a/cli/src/superTabs/cloneTrust.spec.ts
+++ b/cli/src/superTabs/cloneTrust.spec.ts
@@ -130,6 +130,21 @@ describe('consented Swarm clones', () => {
expect(folderTrust('codex', profile)!.trusts(tree)).toBe(true)
machine.stop()
})
+ it('leaves Team-written work\'s own Codex home trusting no project, whatever the sweep repairs (audit H2)', async () => {
+ const f = fixture(true), source = clone(join(f.oldRoot, 'project'))
+ const tree = join(home, 'harnesses', 'worktrees', 'project', 'worker')
+ git(source, 'worktree', 'add', '-q', '-b', 'super-tab/written', tree)
+ const profile = join(home, 'written-profile')
+ mkdirSync(profile); writeFileSync(join(profile, 'config.toml'), '')
+ Object.assign(f.row, { harnessIds: ['written'] })
+ vi.mocked(f.core.agents.all).mockReturnValue([{ agentId: 'written', engine: 'codex', cwd: tree, codexHome: profile, permissionMode: 'teamWritten' }] as never)
+ const machine = new ContributedMachines(f.core, f.core.daemon.machineId(), { backend: takesAll(f.row),
+ open: async () => ({ request: async () => ({}), close: vi.fn() }), capabilities: f.deps.capacity, start: vi.fn(), now: () => 1 } as never)
+ await machine.tick()
+ expect(folderTrust('codex', profile)!.trusts(source)).toBe(false)
+ expect(folderTrust('codex', profile)!.trusts(tree)).toBe(false)
+ machine.stop()
+ })
it('does not follow a Swarm root symlink into the owner repository', async () => {
const f = fixture(true), personal = clone(join(home, 'personal'))
mkdirSync(join(home, 'harnesses', 'swarms'), { recursive: true })
@@ -213,6 +228,13 @@ describe('consented Swarm clones', () => {
expect(claudeWrites()).toBe(before)
machine.stop()
})
+ it('does not write a Team-written agent\'s own Codex home when a start names it (audit H2)', async () => {
+ const f = fixture(true), source = clone(join(f.oldRoot, 'project')), profile = join(home, 'written-selected')
+ mkdirSync(profile); writeFileSync(join(profile, 'config.toml'), '')
+ vi.mocked(f.core.agents.all).mockReturnValue([{ agentId: 'written', engine: 'codex', codexHome: profile, permissionMode: 'teamWritten' }] as never)
+ await prepareSwarmProject(f.core, f.row, { request: { conversationId: 'work', cwd: source, codexHome: profile }, dispatched: false }, async () => source)
+ expect(folderTrust('codex', profile)!.trusts(source)).toBe(false)
+ })
it('does not write a backend-selected Codex home that no local agent uses', async () => {
const f = fixture(true), source = clone(join(f.oldRoot, 'project')), home = join(process.env.HOME!, '.cargo')
mkdirSync(home)
diff --git a/cli/src/superTabs/cloneTrust.ts b/cli/src/superTabs/cloneTrust.ts
index e5f6156e8..9d780c5b4 100644
--- a/cli/src/superTabs/cloneTrust.ts
+++ b/cli/src/superTabs/cloneTrust.ts
@@ -206,7 +206,8 @@ export async function repairSwarmCloneTrust(core: CoreApi, row: Json, profile?:
const agents = local.filter(agent => ids.has(agent.agentId))
// A backend-selected path is not authority to edit a local config file. Only a Codex profile a
// locally registered Codex agent already uses can select another config.toml for this consent.
- const known = profile && isAbsolute(profile) ? local.find(agent => agent.engine === 'codex'
+ // Never a Team-written agent's own home, which stays one that trusts no project (engines/codex/launch.ts, audit H2).
+ const known = profile && isAbsolute(profile) ? local.find(agent => agent.engine === 'codex' && agent.permissionMode !== 'teamWritten'
&& agent.codexHome && resolve(agent.codexHome) === resolve(profile)) : undefined
let complete = discovered
// The service has a separate shell cache from core. Use the same captured locations as native launch.
@@ -244,6 +245,8 @@ export async function repairSwarmCloneTrust(core: CoreApi, row: Json, profile?:
const profiles = new Set(known?.codexHome ? [known.codexHome] : [])
for (const agent of agents) {
if (agent.engine !== 'codex' || !agent.codexHome || !agent.cwd) continue
+ // Team-written work's own home stays one that trusts no project (engines/codex/launch.ts, audit H2).
+ if (agent.permissionMode === 'teamWritten') continue
const cwd = await realpath(agent.cwd).catch(() => null)
if (cwd && paths.some(path => within(path, cwd))) profiles.add(agent.codexHome)
}
diff --git a/cli/src/superTabs/inCore/teamPurge.spec.ts b/cli/src/superTabs/inCore/teamPurge.spec.ts
index 300d98a55..10a84a118 100644
--- a/cli/src/superTabs/inCore/teamPurge.spec.ts
+++ b/cli/src/superTabs/inCore/teamPurge.spec.ts
@@ -1,10 +1,11 @@
import { buddyTmpFolder, buddyTmpParent } from '../../lib/agentTmp.js'
import { appendFileSync, chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync, realpathSync } from 'node:fs'
import { tmpdir } from 'node:os'
-import { join } from 'node:path'
+import { dirname, join } from 'node:path'
+import { PM_HOMES } from '../teamDaemon.js'
import { describe, expect, it, vi } from 'vitest'
import { createSwarmAgents } from './agents.js'
-import { OWN_LEFT, SHARED_LEFT, SWEEP_LEFT, UNREADABLE_DETAIL, createConfidentialPurge, purgeRecord, recordsOtherFolder, rewriteIfUnchanged, scrubClaudeSession, sweepForSession, type PurgeTarget } from './teamPurge.js'
+import { OWN_LEFT, SHARED_LEFT, SWEEP_LEFT, UNREADABLE_DETAIL, createConfidentialPurge, ownHomeFolder, purgeRecord, recordsOtherFolder, rewriteIfUnchanged, scrubClaudeSession, sweepForSession, type PurgeTarget } from './teamPurge.js'
/** A folder that goes between the sweep's listing of its parent and its own read: removed just before that read. */
const vanish = vi.hoisted(() => ({ path: '' }))
@@ -512,6 +513,30 @@ describe('the purge of a confidential session the Swarm ended', () => {
return { purge, session, record, calls }
}
+ it('finds an agent\'s own engine home on either separator, and nothing outside it (audit H2, Windows pass)', () => {
+ expect(ownHomeFolder('/Users/team/.harness-pm-homes', '/Users/team/.harness-pm-homes/super-start/codex')).toBe('/Users/team/.harness-pm-homes/super-start')
+ expect(ownHomeFolder('C:\\Users\\team\\.harness-pm-homes', 'C:\\Users\\team\\.harness-pm-homes\\super-start\\codex')).toBe('C:\\Users\\team\\.harness-pm-homes\\super-start')
+ for (const [homes, path] of [
+ ['/Users/team/.harness-pm-homes', '/Users/team/.harness-pm-homes-other/x/codex'],
+ ['/Users/team/.harness-pm-homes', '/Users/team/.harness-pm-homes/codex'],
+ ['/Users/team/.harness-pm-homes', '/Users/team/.harness-pm-homes/../x/codex'],
+ ['C:\\Users\\team\\.harness-pm-homes', 'C:\\Users\\team\\.harness-pm-homes\\..\\x\\codex'],
+ ['/Users/team/.harness-pm-homes', '/Users/team/.codex'],
+ ] as const) expect(ownHomeFolder(homes, path), path).toBeNull()
+ expect(ownHomeFolder('/Users/team/.harness-pm-homes', null)).toBeNull()
+ })
+
+ it('removes Team-written work\'s own Codex home when the agent ends, confidential or not, and nothing else (audit H2)', async () => {
+ const { home } = teamHome()
+ const s = service(home), own = join(home, PM_HOMES, 'super-start', 'codex'), other = join(home, 'elsewhere', 'codex')
+ mkdirSync(own, { recursive: true }); mkdirSync(other, { recursive: true })
+ const session = (codexHome: string) => () => ({ agentId: 'r', sessionId: 's', registeredAt: 1, engine: 'codex', cwd: CWD, codexHome })
+ expect(await createConfidentialPurge({ confidential: () => false, home, session: session(other), purge: s.purge, record: s.record })('r')).toEqual({ skipped: true })
+ expect(existsSync(other)).toBe(true)
+ expect(await createConfidentialPurge({ confidential: () => false, home, session: session(own), purge: s.purge, record: s.record })('r')).toEqual({ skipped: true })
+ expect(existsSync(dirname(own))).toBe(false)
+ })
+
it('deletes through the reviewed purge, scrubs, sweeps, and keeps the session in its record until the sweep passes', async () => {
const { home, claude } = teamHome()
const s = service(home)
diff --git a/cli/src/superTabs/inCore/teamPurge.ts b/cli/src/superTabs/inCore/teamPurge.ts
index 64025fa8d..d85f4c501 100644
--- a/cli/src/superTabs/inCore/teamPurge.ts
+++ b/cli/src/superTabs/inCore/teamPurge.ts
@@ -400,6 +400,15 @@ export const PURGE_RECORD_UNREADABLE = 'PURGE_RECORD_UNREADABLE'
export const UNREADABLE_DETAIL = "This machine's record of purges still to finish could not be read and was kept aside, as the daemon's log says at "
+ "each start. The account stays held until its owner clears it as #2142's risk note says, by file names only."
+/** The folder of an agent's own engine home `<homes>/<creation>/codex`, to delete whole; null for any other path. Either separator,
+ * as a Windows path has `\\` (Windows pass, task #2022), and never a path that climbs out. */
+export function ownHomeFolder(homes: string, codexHome: string | null | undefined): string | null {
+ if (!codexHome || !codexHome.startsWith(homes)) return null
+ const [first, creation, name, ...rest] = codexHome.slice(homes.length).split(/[\\/]/)
+ if (first !== '' || !creation || creation === '.' || creation === '..' || name !== 'codex' || rest.length) return null
+ return codexHome.slice(0, homes.length + 1 + creation.length)
+}
+
/**
* The purge of [agentId]'s data, once the Swarm ended it for good, when it was confidential: kept in [record] before the
* first deletion and dropped once the sweep finds nothing. A retry finishes from the record, the session gone or not.
@@ -420,7 +429,13 @@ export function createConfidentialPurge(deps: {
const session = deps.session(agentId)
let target = deps.record.get(agentId)
if (!target) {
- if (!session || !deps.confidential(agentId)) return { skipped: true }
+ // Team-written Codex work has an engine home of its own too (superTabs/start.ts): it goes with the agent, confidential or not.
+ if (session && !deps.confidential(agentId)) {
+ const own = ownHomeFolder(join(deps.home, PM_HOMES), session.codexHome)
+ if (own) await rm(own, { recursive: true, force: true })
+ return { skipped: true }
+ }
+ if (!session) return { skipped: true }
target = { agentId: session.agentId, sessionId: session.sessionId ?? null, cwd: session.cwd, engine: session.engine, codexHome: session.codexHome ?? null }
deps.record.put(target)
}
diff --git a/cli/src/superTabs/start.spec.ts b/cli/src/superTabs/start.spec.ts
index 99d8c9f4e..fc74203da 100644
--- a/cli/src/superTabs/start.spec.ts
+++ b/cli/src/superTabs/start.spec.ts
@@ -1,11 +1,12 @@
import { describe, expect, it, vi } from 'vitest'
-import { join } from 'node:path'
+import { dirname, join } from 'node:path'
import { existsSync, mkdtempSync, rmSync } from 'node:fs'
import { homedir, tmpdir } from 'node:os'
import { BUDDY_SESSION_ENGINE, HEAVY_NOT_RECORDED, HEAVY_REFUSED, inspectCapacity, MODEL_REPORT_WAIT_MS, startAgent } from './start.js'
import { buildEngineCommandArgv } from '../lib/engineLaunch.js'
import { readCapacityDisk } from './disk.js'
import { SuperTabHostError } from './wire.js'
+import { PM_HOMES } from './teamDaemon.js'
const teamDaemon = vi.hoisted(() => ({ value: false, relayed: true, offered: null as null | { slugs: string[]; listed: string[] } }))
vi.mock('./teamDaemon.js', async (original) => ({ ...await original<object>(), isTeamDaemon: () => teamDaemon.value }))
vi.mock('../team/relay.js', async (original) => ({ ...await original<object>(), teamRelayed: () => teamDaemon.relayed, offeredCodexModels: async () => teamDaemon.offered }))
@@ -93,6 +94,42 @@ describe('Swarm permission mode', () => {
}
})
+ // Audit H2: the launch line that keeps a branch's own settings out. Tried with the real binaries, planted settings.json,
+ // settings.local.json and .mcp.json ran without these flags and not with them (Claude Code 2.1.316, 2026-11-02).
+ it('starts Team-written Claude Code work with project settings off, in a Team account', async () => {
+ teamDaemon.value = true
+ try {
+ const f = fixture()
+ Object.assign(f.start.request, { engine: 'claude', projectSettings: 'off' })
+ expect(await startAgent({ action: 'resume', tabId: 'tab', startId: 'start' }, f.scoped, where, f.open)).toMatchObject({ ok: true })
+ const payload = f.request.mock.calls.find(c => c[0] === 'agent_create')![1]!
+ expect(payload).toMatchObject({ permissionMode: 'teamWritten', bypassPermission: true })
+ expect(buildEngineCommandArgv('claude', { permissionMode: 'teamWritten' })).toEqual(expect.arrayContaining(['--dangerously-skip-permissions', '--setting-sources', 'user', '--strict-mcp-config']))
+ } finally { teamDaemon.value = false }
+ })
+
+ // A Codex worktree takes its main repository's trust, and `-c` does not turn it off. An engine home of its own does (0.165.0, tried).
+ it('starts Team-written Codex work in an engine home of its own, which trusts no project', async () => {
+ teamDaemon.value = true
+ try {
+ const f = fixture()
+ Object.assign(f.start.request, { engine: 'codex', projectSettings: 'off' })
+ expect(await startAgent({ action: 'resume', tabId: 'tab', startId: 'start' }, f.scoped, where, f.open)).toMatchObject({ ok: true })
+ const payload = f.request.mock.calls.find(c => c[0] === 'agent_create')![1]!
+ expect(payload).toMatchObject({ permissionMode: 'teamWritten', bypassPermission: true })
+ expect(String(payload.codexHome)).toContain(`/${PM_HOMES}/`)
+ rmSync(dirname(String(payload.codexHome)), { recursive: true, force: true })
+ } finally { teamDaemon.value = false }
+ })
+
+ it.each(['claude', 'codex'] as const)('refuses Team-written %s work in the main account, before anything is created', async engine => {
+ const f = fixture()
+ Object.assign(f.start.request, { engine, projectSettings: 'off' })
+ expect(await startAgent({ action: 'resume', tabId: 'tab', startId: 'start' }, f.scoped, where, f.open)).toMatchObject({ error: 'START_FAILED' })
+ expect(f.request.mock.calls.some(c => c[0] === 'agent_create')).toBe(false)
+ expect(f.start.error).toContain('Team account')
+ })
+
it.each(['opencode', 'kilo'])('fails a pending legacy %s Swarm start before native creation', async engine => {
const f = fixture()
Object.assign(f.start.request, { engine })
diff --git a/cli/src/superTabs/start.ts b/cli/src/superTabs/start.ts
index 2ef7312b2..f8be3f748 100644
--- a/cli/src/superTabs/start.ts
+++ b/cli/src/superTabs/start.ts
@@ -23,6 +23,7 @@ const text = (v: unknown) => typeof v === 'string' ? v : null
const number = (v: unknown) => typeof v === 'number' && Number.isFinite(v) ? v : null
// These native validations run before dispatch. Storage errors, conflicts and
// unknown failures deliberately stay uncertain: they cannot prove no launch.
+const TEAM_WRITTEN_MAIN_ACCOUNT = 'A Harness Team agent wrote this task\'s code, so it runs only in a Team account, never in this machine\'s main account. Choose an agent or machine in a Team account.'
const PRE_DISPATCH_REFUSALS = new Set([
'INVALID_ENGINE', 'INVALID_CWD', 'INVALID_PROJECT_SOURCE', 'INVALID_REPOSITORY',
'INVALID_GRID', 'INVALID_CODEX_HOME', 'INVALID_DSH', 'INVALID_PROMPT',
@@ -363,6 +364,13 @@ async function startOnce(input: Json, scoped: ScopedRequest, where: Where, open:
if (!refusedByBackend(error)) throw error
return await releaseRefused(error)
}
+ // Code a Team agent wrote never runs as this machine's owner (backend superTabs/teamWritten.ts, audit H2). The server sends it
+ // only to a Team account's machine, so this is the last check, for a row or a server that says otherwise.
+ const projectSettingsOff = request.projectSettings === 'off'
+ if (projectSettingsOff && !isTeamDaemon()) {
+ requireSuccess(await scoped({ action: 'command', operationId: `refused-${startId}`, command: { type: 'agent.startFailed', startId, error: TEAM_WRITTEN_MAIN_ACCOUNT } }))
+ return { error: 'START_FAILED', startId, detail: TEAM_WRITTEN_MAIN_ACCOUNT }
+ }
// Both direct and contributed-host starts reach this boundary. Existing
// native receipts are read above and never have their permissions changed.
// Engines without a full mode retain their existing approving launch flags.
@@ -406,7 +414,7 @@ async function startOnce(input: Json, scoped: ScopedRequest, where: Where, open:
// The role's name from the project's document, when the backend's start request has it; one line, bounded.
const roleName = typeof request.roleName === 'string' ? request.roleName.replace(/\s+/g, ' ').trim().slice(0, 80) : ''
const payload: Json = { engine: request.engine, name: request.name, creationId, startedBy: 'agent', bypassPermission: !asks,
- ...(asks ? { permissionMode: asks } : permissionModeFlags(request.engine as AgentEngine, 'full') ? { permissionMode: 'full' } : {}),
+ ...(asks ? { permissionMode: asks } : projectSettingsOff ? { permissionMode: 'teamWritten' } : permissionModeFlags(request.engine as AgentEngine, 'full') ? { permissionMode: 'full' } : {}),
...(mode ? { swarmRole: role, swarmSkillMode: mode } : {}),
...(github ? { swarmGitHub: true } : {}),
// A thread session (#2345) gets its own Buddy note; a coordinator's and an agent's notes name their role (phase 3).
@@ -422,7 +430,8 @@ async function startOnce(input: Json, scoped: ScopedRequest, where: Where, open:
for (const key of ['codexHome', 'gridModel', 'gridName']) if (request[key] !== undefined) payload[key] = request[key]
// A Codex Product Manager in a Harness Team account runs in an engine home of its own, deleted whole when the Swarm
// ends it, so nothing of its chats stays where the account's next agent reads (teamDaemon.ts, security re-check 2 of #2089).
- const pmHome = lead ? pmEngineHome(String(request.engine), creationId, isTeamDaemon(), homedir()) : null
+ // Team-written Codex work too: a home that trusts no project keeps the branch's own settings out (engines/codex/launch.ts).
+ const pmHome = lead || projectSettingsOff ? pmEngineHome(String(request.engine), creationId, isTeamDaemon(), homedir()) : null
if (pmHome) {
// Codex refuses a CODEX_HOME that is not there; only the Team user reads it.
mkdirSync(pmHome, { recursive: true, mode: 0o700 })
diff --git a/desktop/lib/core/permission_modes.dart b/desktop/lib/core/permission_modes.dart
index 7a7b28456..e99ee6451 100644
--- a/desktop/lib/core/permission_modes.dart
+++ b/desktop/lib/core/permission_modes.dart
@@ -90,6 +90,11 @@ const Map<String, List<PermissionMode>> kLaunchOnlyPermissionModes = {
'Reads only, never asks',
'Runs its read tools and commands, refuses the rest without asking',
),
+ PermissionMode(
+ 'teamWritten',
+ 'Full, project settings off',
+ 'Runs in a Team account and reads none of the branch\'s own settings',
+ ),
],
'codex': [
PermissionMode(
@@ -97,6 +102,11 @@ const Map<String, List<PermissionMode>> kLaunchOnlyPermissionModes = {
'Read only, asks you',
'Reads in its sandbox, asks you before anything outside it',
),
+ PermissionMode(
+ 'teamWritten',
+ 'Full, project settings off',
+ 'Runs in a Team account and reads none of the branch\'s own settings',
+ ),
],
};
diff --git a/docs/plans/2026-11-02-archive-step-waits-for-task-plan.md b/docs/plans/2026-11-02-archive-step-waits-for-task-plan.md
new file mode 100644
index 000000000..b3e54da4a
--- /dev/null
+++ b/docs/plans/2026-11-02-archive-step-waits-for-task-plan.md
@@ -0,0 +1,36 @@
+# Archive pass: a step waits for its task Implementation Plan
+
+**Goal:** A review or test step is never archived on its own clock while its task is open, so a re-check never fails on an archived step.
+
+**Architecture:** The task steps design says a step archives with its task. Three places still let one go alone: the worker's startup mark, the archive pass, and the store's write. All three now read the task. The write stays the last word, inside its transaction.
+
+**Tech stack:** TypeScript, Prisma on MongoDB, Vitest integration tests with a real replica set.
+
+## Files
+
+- `backend/src/superTabs/archive.ts`: `markFinishedGroups`, `archiveFinishedGroups`.
+- `backend/src/superTabs/steps.ts`: `taskEnded`.
+- `backend/src/superTabs/tidy.ts`: `archivable` and `reviewClosable` use `taskEnded`.
+- `backend/src/superTabs/store.ts`: `archiveFinished` reads the task's pull requests and touches the task.
+- `backend/integration/superTabTidy.test.ts`, `backend/src/superTabs/tidy.test.ts`.
+
+## Task 1: A step follows its task
+
+- [x] Write failing tests: a finished step and a step nobody holds stay unarchived after a worker restart under an open task; an earlier mark is taken back; the write refuses a step of an open task or of a task it did not read.
+- [x] Run them and watch them fail on the unchanged source.
+- [x] Mark: no step in the legacy mark; clear every open step's mark; set it only where the task is done or cancelled.
+- [x] Pass: read the task; skip unless it ended; settle both the step's and the task's pull requests.
+- [x] Write: `archivable` and `reviewClosable` require `taskEnded`; a step's archive touches its task, so a hand-back since the load retries.
+- [x] Run `npx vitest run --config vitest.super-tabs.config.ts integration/superTabTidy.test.ts`, then `npm run test:super-tabs`.
+
+## Design
+
+- **Growth:** nothing new is stored. A step still goes with its task.
+- **Concurrency:** the write loads the task and touches it, so a task handed on during the archive retries and declines.
+- **Read cost:** the pass reads one task per marked step. The startup mark runs one aggregate over open groups, with one `tabId_key` read per open step, once per worker start.
+- **Scale:** at 10x, startup aggregate time warns first. It is not on any request path.
+- **Compatibility:** no wire or client change.
+- **Migration and rollback:** the first startup clears old marks on open steps. A rollback marks unattended steps again, as today.
+- **Audience, identity:** N/A because no read or write gains a reader, and no login is used.
+- **Failure:** a missing or unloaded task reads as not ended, so a step stays open. A failed write skips that group with the pass's existing warning.
+- **Platforms:** backend only.
diff --git a/docs/plans/2026-11-02-bridge-key-rotation-cloud-socket-plan.md b/docs/plans/2026-11-02-bridge-key-rotation-cloud-socket-plan.md
new file mode 100644
index 000000000..28eb37d13
--- /dev/null
+++ b/docs/plans/2026-11-02-bridge-key-rotation-cloud-socket-plan.md
@@ -0,0 +1,36 @@
+# Retire the bridge's old key, and move cloud agents' bridge calls to its socket: plan
+
+> Written by the writing-plans skill's rules. Task #2076, the two pieces #2558's review named. Part 1 is #2566.
+
+**Goal:** on macOS and Linux, no key the bridge accepts has ever crossed its TCP port, and Harness's own cloud calls no longer use it.
+
+**Architecture:** the bridge's 0600 socket also answers Harness's key (`/<harness key>/connections`, `/<harness key>/<code>/api/...`, and its MCP address), and the TCP listener stops accepting that key. `cloud/bridge.ts` routes through the socket, with no fallback. Harness's key is replaced once, as it did cross the port. The agents' old key keeps working for 24 hours after its entries moved to the shim, then it is deleted.
+
+## Design
+
+- Growth: N/A because the only stored additions are two small fields, one a time that goes with the key it describes.
+- Concurrency: the key files change under the vault's lock, at the service's start. A request reads the file as it does today.
+- Read cost: N/A because each request reads the same file it read before.
+- Scale: N/A because the cloud service's calls are the requests they were, on another listener.
+- Compatibility: an agent still running from a URL entry keeps working for 24 hours, then answers 404 until it restarts, and its next start uses the shim. An old cloud service is restarted with the daemon. A folder too long for a socket, and Windows, keep the key and the port as they are.
+- Migration + rollback: the first start after this stamps the time and replaces Harness's key. A rollback after the old key is gone makes a new one at the next `sync`, as a fresh install does.
+- Audience: the filesystem for the socket, the peer check on TCP. The agents' route on the socket still reaches MCP servers only.
+- Identity: the OS account; no login is read.
+- Failure: with the socket gone, cloud calls say Connections is not running. A retired key answers as any unknown key does, so the answer does not confirm it.
+- Platforms: macOS and Linux. Windows is unchanged.
+
+## Decisions
+
+- **24 hours, not at once.** A key heard already opens nothing for another account (#2550), so a day's grace costs little, while deleting it at once would cut every running agent's connections at the update.
+- **The port keeps listening.** With no key it answers nothing, and while it is held by this daemon nobody else can hold it for clients still on it.
+
+## Tasks
+
+1. Red tests: a holder of the port hears no cloud call or key; the socket answers Harness's key; TCP refuses it where a socket can be; the old key lives 24 hours then goes; Harness's key is replaced once; no socket, nothing changes.
+2. `serveBridgeSocket` takes Harness's key; `fetchOverSocket` in `lib/localTransport.ts`.
+3. `cloud/bridge.ts` and `cloud/mcp.ts` route through it.
+4. `retireBridgeKey` and `rotateHarnessKey` in `agents.ts`, called from `services/connectors.ts`.
+
+## Left open
+
+- Windows, and a data folder too long for a socket, still send keys over TCP: its own task, with a proof-checked pipe.
diff --git a/docs/plans/2026-11-02-connections-profile-homes-plan.md b/docs/plans/2026-11-02-connections-profile-homes-plan.md
new file mode 100644
index 000000000..4bda9c400
--- /dev/null
+++ b/docs/plans/2026-11-02-connections-profile-homes-plan.md
@@ -0,0 +1,42 @@
+# Connections reach an agent running under a profile home: plan
+
+**Goal:** An agent started under a Claude profile (`CLAUDE_CONFIG_DIR`) or a Codex profile (`CODEX_HOME`), such as a switched PM
+(#2527-#2529), gets the connection entries the default homes get. Today `sync` writes only `<HOME>/.claude.json` and
+`~/.codex/config.toml` (or the daemon's own moved homes), so such an agent has no connections. Task #2088.
+
+## Design
+
+- **Profile agents.** `agents.ts` gets a profile variant of the Claude (`<home>/.claude.json`, `mcpServers`) and Codex
+ (`<home>/config.toml`) agents, named `claude:<home>` / `codex:<home>`. Their entries are the default ones: same shim, same code.
+- **At launch.** `core/agents/create.ts` calls `syncProfileHome` for the agent's `claudeHome` / `codexHome` (already validated
+ by `claudeHomeOffered` / the Codex profile check in `launches.ts`), after the home is final and before the engine starts.
+ A failure is logged, never refuses the launch. The default homes are untouched; a profile that is the default's file is skipped.
+- **Kept current.** `projections.json` records the names Harness wrote per agent name, so the profile agents are recorded under
+ their own names. `sync` (daemon start, connect, disconnect, renewal, `harness connections sync`) also applies every recorded
+ profile home, so a later connection reaches and a disconnected one leaves a running profile's config.
+- **Only the profile's own home.** A Claude folder is validated by `claudeHomeOffered` where the launch is asked for; a Codex folder
+ must be one of this machine's Codex profiles (`listCodexProfiles`, read at most every 30 s), so the folder a native launch picks
+ for itself is not one. The default home is recognised by real path. A config that is a link leaving the folder is not written.
+- **One bad home.** Each agent is updated on its own: a failure is logged and the others, and the record of what was written, go on.
+ A launch waits 3 s for the vault's lock, not 35 s; a timeout is logged and the launch goes on.
+- **Removed with the profile.** A recorded home whose folder is gone, or is no longer a Codex profile (its entries are taken out first), is dropped from `projections.json`; a home with no wanted
+ connections has Harness's entries removed, like the default homes. Only recorded names are changed or removed.
+
+## Design rules
+
+- Growth: one record per profile home used; dropped when the folder is gone.
+- Concurrency: the vault lock already covers `projections.json`; the engine's own config is replaced atomically as before.
+- Read cost: `sync` reads each recorded home's config, once per change; the number of profile homes on a machine is small (<= 256 linked).
+- Scale: 10x profiles is 2,560 config reads per connection change; review if a machine records more than 100 homes.
+- Compatibility: an old daemon ignores `claude:/...` keys it does not know; a new one reads old files unchanged.
+- Migration and rollback: none; a rollback leaves the entries in the profile homes, still working.
+- Audience: the same user's files, in a home the daemon already validated and writes hooks into.
+- Identity: N/A because no login is read.
+- Failure: an unreadable config is left as it is; a failed write is logged and the launch goes on.
+- Platforms: macOS, Linux, Windows (paths via `node:path`).
+
+## Steps
+
+1. Specs: an agent started under a Claude profile and one under a Codex profile get the entries (fail on main); a later
+ connection reaches them, a disconnect and a gone folder remove them; the default homes are as before.
+2. `agents.ts`, then `create.ts`.
diff --git a/docs/plans/2026-11-02-team-written-branch-plan.md b/docs/plans/2026-11-02-team-written-branch-plan.md
new file mode 100644
index 000000000..7600a00cd
--- /dev/null
+++ b/docs/plans/2026-11-02-team-written-branch-plan.md
@@ -0,0 +1,165 @@
+# A branch a Team agent wrote never runs as the owner: implementation plan
+
+Task #2025, audit finding H2 (`docs/security/2026-11-02-team-account-boundary.md`). Requested by Scholes.
+
+**Goal:** code a Team agent wrote is built, run and read only in a Team account, with its project settings off. It never
+runs with the main account's rights.
+
+**Approach:** three layers. The server decides who may take the work. GitHub's record says who pushed. The launch turns
+project settings off.
+
+## What the code does today
+
+- A Team agent's GitHub token may write to the whole repository (`backend/src/github/app.ts:14`). GitHub has no per-branch
+ token, so it can push to any unprotected branch, including an owner's agent's pull request.
+- Commit authors and trailers can be forged. They can show a branch is Team-written, but never that it is safe.
+- GitHub's activity log can't be forged by the pusher. `GET /repos/R/activity` names each push's actor, its ref and its
+ before and after commits. Read on 2026-11-02: `harness-for-autonomous[bot]` made 8 of the last 100 pushes, and people's
+ own logins made the rest.
+- Most Reviewers start on the default branch and then run `gh pr checkout` themselves, so a check at start alone misses the
+ normal path.
+- A trust record is not the real barrier. Claude Code also accepts a Yes given to the main repository for its worktrees
+ (`engines/claude/launch.ts`). What keeps the settings out is the launch flags.
+- `--setting-sources local` is not enough here: a branch can commit `.claude/settings.local.json`. Harness's hooks are in the
+ person's user settings, so `user` keeps them and drops everything the branch carries.
+- All 8 Macs in this Swarm have a Team account beside them at this reading, so routing there is possible today.
+
+## The rule
+
+A branch is **Team-written** when any of these holds. It is trusted only when the check reads clean, and a failed read counts
+as Team-written:
+
+1. An agent on a Team account opened its task, was assigned to it or was added to it (a lasting mark on the task, kept by the
+ server). A Team agent given only a step does not count, and neither does the project's coordinator.
+2. GitHub shows a push by the app's bot of a commit in the pull request. This also catches a batch branch that the PM pushed with
+ Team commits inside.
+3. Its head has commits not on the default branch, and the activity log can't cover them (the log was too short, the read
+ failed, or the commit came from a fork).
+
+Code on the default branch has passed review and counts as clean.
+
+## Tasks
+
+### Task 1: the server's mark and refusal (backend)
+
+Files: `backend/src/superTabs/commands.ts`, `machines.ts`, `model.ts`, new `backend/src/superTabs/teamWritten.ts`, tests beside them.
+
+- `Conversation.teamWritten: true` is set when an agent on a Team account opens a task, is assigned to it, is added to it or is named
+ into it, and it never clears. Any new mark tells every main-account member of the task and its steps to stop, finished steps
+ included, and a post by another agent that names one of them is refused. A step reads its task's mark. A Team agent given only a step, or the project's coordinator, marks nothing.
+- `work.assign`, `conversation.agent`, `agent.start` and `route.record` refuse an agent outside a Team account for a marked
+ task or its step, with `TEAM_WRITTEN_WORK` and a reason that says where the work can go. Route candidates leave those
+ machines out and say why.
+- Tests, each failing on main: refused assign, join and start; a step of a marked task; the mark survives a re-route; an owner's
+ own unmarked task is unchanged; an id from another project or a private chat reads as missing, as today.
+
+### Task 2: who pushed it (backend, with a read for clients)
+
+Files: new `backend/src/github/pushOrigin.ts`, `backend/src/github/app.ts`, `backend/src/superTabs/store.ts`.
+
+- Given a project and a head commit, it reads the activity log with the app's token and answers `clean`, `team` or `unknown`.
+ Results are cached by head commit only, with a bounded retry. `unknown` is never cached as clean.
+- At a `work.assign`, an added agent, a Ready for review and a start that names a branch (a PM's too), the server reads the origin
+ first and marks the task on `team`, and the mark stays even when the command that read it is refused. `unknown` refuses the main
+ account without marking. A step that names no pull request reads `unknown`. This covers a Team push onto an owner's branch.
+- The whole log is too long to walk: 2,000 events reached 3.3 days on this repository. So the read asks two narrow questions: who
+ pushed the head, on its own branch (`ref=`), and which of these commits the app's bot ever pushed (`actor=`).
+- The answer says only the verdict: no names and no branch titles. A project the caller can't read gets the same refusal as a
+ missing one.
+- Tests with `fakeGitHub.ts`: a bot push; a batch branch; a person's push; a forged author on a bot push; a failed, partial or
+ too-short log (`unknown`); and a rate limit.
+
+### Task 3: the launch (CLI)
+
+Files: `cli/src/engines/claude/launch.ts`, `engines/codex/launch.ts`, `lib/engineLaunch.ts`, `core/agents/launches.ts`,
+`core/agents/create.ts`, `superTabs/cloneTrust.ts`, `superTabs/start.ts`, `superTabs/inCore/teamPurge.ts`,
+`desktop/lib/core/permission_modes.dart`.
+
+- The server stamps `projectSettings: 'off'` on a start for a marked task. The host turns it into the permission mode
+ `teamWritten`, which is kept on the agent's row, so a relaunch keeps it. A resume that asks for another mode is refused.
+- Claude Code gets `--setting-sources user --strict-mcp-config`. Codex gets an engine home of its own, which trusts no project.
+- A daemon that is not a Team daemon refuses a stamped start before anything is created.
+- The server also reads the branch a start names: a bot's push moves the start to the Team account, and a branch GitHub cannot
+ place stays out of the main account.
+
+### What the real engines showed (2026-11-02, throwaway config folders, this Mac)
+
+| Run | Result |
+|---|---|
+| Claude Code 2.1.316, trusted folder, no flags | Planted `settings.json`, `settings.local.json` and `.mcp.json` all ran. This is H2 happening. |
+| Same folder, with the flags | None ran. |
+| Same flags, no trust record | The session stops at the trust question. |
+| Codex 0.165.0, untrusted folder | Project MCP server not loaded. |
+| Codex, a worktree whose main repository is trusted | Loaded: a worktree takes its main repository's trust. |
+| Same, with `-c projects."..".trust_level="untrusted"` | Still loaded: this does not turn it off. |
+| Same worktree, an empty `CODEX_HOME` | Not loaded. |
+
+**Change from the brief:** the brief asks for no folder trust. A Claude Code session with no trust record stops at a question nobody
+sees, so Team-written work keeps its trust record, in the Team account only. The flags are the barrier, as the runs above show.
+
+### Task 4: moved out of this change
+
+The plan first had a `post-checkout` warning for main-account agents. It needs git settings injected into every main-account
+session, and it can only warn. The server's check on assignment, start and Ready covers the workflow's own paths, so the warning is
+left out here. What that leaves open is below.
+
+### Task 5: docs and proof
+
+- Update `docs/security/2026-11-02-team-account-boundary.md` with H2's status and what stays open.
+- Run the full backend Super Tab integration suite, `npm run test:core` and the affected Desktop test.
+
+## What this does not close
+
+- **An agent told outside the workflow.** A main-account agent that runs `gh pr checkout` on a branch it was never assigned, for
+ example because a chat message asked it to (M3), still runs that code as the owner. The server only controls who gets the work.
+- **A push after the check.** A Team agent can push between a clean reading and the Reviewer's fetch. The next Ready reads again
+ and tells every main-account member to stop, but by then one may have run the code.
+- **A rewrite by a person or an owner's agent.** An owner's agent on its own project pushes with the owner's login, so GitHub shows
+ it as a person. If a person or that agent rebases or cherry-picks a Team agent's commits, the new commits have new ids and the
+ branch reads clean. A marked task keeps its mark; a new branch on another task does not get one.
+- **Old pushes.** The scan of the bot's pushes stops a week before the older of the pull request and its oldest commit. A commit's
+ date can be forged, which can only narrow this back to the pull request's own week.
+- **The default branch.** It reads clean without a check, because it passed review. A Team token could push to it if the branch
+ were unprotected. Here it is protected, and that protection is what this rests on.
+- **The PM.** It is exempt as "never builds or runs it", but nothing enforces that. It builds batch branches in the main account, and
+ a `Makefile` or `.claude` settings from a batch branch would run as the owner. The batch and `make merge-pr` must run from a
+ default-branch checkout. That is a rule for the project's instructions, not something this code enforces.
+
+Closing the first two takes a sandbox for every main-account agent, or a repository rule that keeps the app's bot to its own branch
+prefix. The rule is the stronger next step. It needs a change to repository settings, so it is Ken's decision and not part of this
+task.
+
+## Work that needs the owner's tools or devices
+
+A Team account has none of the owner's tools or devices, so firmware on a plugged-in device and other owner-only checks have no home
+once a task is marked. This code offers no exception. The default is that such a task is reviewed in a Team account, merged, and then
+checked on the owner's device, because code on the default branch has passed review. Scholes and Ken can decide otherwise.
+
+## Design
+
+- **Growth:** one boolean on a task, removed with the task. The origin cache keeps at most 1,000 heads in memory. A Codex agent's own
+ home is deleted when the Swarm ends that agent.
+- **Concurrency:** the mark is set inside the existing per-tab command transaction. GitHub reads run outside it, and their
+ result is applied by a command that only ever adds the mark, so a late read can't clear one.
+- **Read cost:** per new head, up to 3 pull request reads, 3 pages of the branch's log and 20 pages of the bot's pushes. A head with
+ an answer is not read again, and an `unknown` is read again after a minute at most.
+- **Scale:** at 10x pushes the activity log's 5,000-an-hour app limit warns first. A rate limit reads `unknown`, which fails closed
+ and refuses main-account work, so the refusal count is the metric to log.
+- **Compatibility:** an older CLI on a Team account ignores the stamp, so its session reads project settings there, with the Team
+ account's rights and not the owner's. An older backend sends no stamp and refuses nothing, so the rule starts with the backend
+ release. Desktop lists the new mode by name, and an older Desktop shows it as unknown.
+- **Migration and rollback:** no migration. Tasks open today carry no mark until an assignment or a reading sets it. Rollback
+ removes the refusal, and the mark is harmless left behind.
+- **Audience:** the server enforces who takes the work. The verdict carries no names or titles.
+- **Identity:** the mark comes from the Swarm's own record of the account and GitHub's record of the pusher, never from commit
+ authors or the machine owner's login.
+- **Failure:** `unknown` refuses, with a reason that names the Team account as the way forward. Nothing passes silently.
+- **Platforms:** the rule is the same wherever a Team account runs. A machine with no Team account can't take a marked task.
+
+## Privacy, concurrency and lifecycle cases to test
+
+- Access lost: a read in flight when project access ends gets dropped, and the answer is the same refusal as a missing project.
+- Stale results: a reading for an old head can't change a newer head's answer, and a late reading can't clear a mark.
+- Failed first read that recovers: `unknown` becomes `clean`, and the refusal lifts on the next read with no stuck state.
+- Agent id or name reused across projects: the mark follows the task, never the agent's name.
+- Data at a limit: a task at its size limit still saves with the mark.
diff --git a/docs/security/2026-11-02-team-account-boundary.md b/docs/security/2026-11-02-team-account-boundary.md
index 40a73f7e2..ac5830fdb 100644
--- a/docs/security/2026-11-02-team-account-boundary.md
+++ b/docs/security/2026-11-02-team-account-boundary.md
@@ -15,7 +15,7 @@ Team agent the owner's full rights (H1, H2), and files and command lines the own
| ID | Rating | Finding | Status |
|---|---|---|---|
| H1 | **High** | The owner's local credential goes to whoever holds the daemon's port | Fixed for hooks, the CLI and Desktop (task #2016); what stays open is under its fix |
-| H2 | **High** | A Team agent's branch runs with the owner's rights when an owner's agent builds it | Read in code, fix requested |
+| H2 | **High** | A Team agent's branch runs with the owner's rights when an owner's agent builds it | Proved with the real engines; fixed for assigned work (#2025), and what stays open is listed under H2 |
| M1 | **Medium** | The owner's files in the shared `/tmp` are readable, and can be planted | Seen on the Mac Studio, fix requested |
| M2 | **Medium** | Tokens on tmux's command line show in `ps` to every account | Seen on the Mac Studio, fix requested |
| M3 | **Medium** | A Team agent's chat message reaches the owner's agents, which act with the owner's rights | Read in code, decision requested |
@@ -77,6 +77,28 @@ without permission prompts, so nothing stops to ask. This was not tried. M3 is t
**Fix:** build and run a branch that a Team agent wrote only in a Team account or a sandbox, never in the main account, and read it
there with its project settings off. Until then, route those Reviewers and Testers to Team accounts.
+**Status (task #2025, `docs/plans/2026-11-02-team-written-branch-plan.md`):** the attack was then tried with Claude Code 2.1.316 on a
+fixture: planted `settings.json`, `settings.local.json` and `.mcp.json` all ran in a trusted folder. The fix:
+
+- The server refuses a main-account agent for a task a Team agent worked on, and for any pull request GitHub's activity log shows the
+ app's bot pushed to. If GitHub can't say, or a review names no pull request, the main account is refused too.
+- A new mark tells every main-account member of the task and its steps to stop, and another agent's post can't name them.
+- These agents start with project settings off, and a daemon in the main account refuses such a start.
+
+**Still open:**
+- a main-account agent that checks out a branch outside the workflow, for example when a chat message asks it to (M3);
+- a push between the check and the fetch;
+- a rebase or cherry-pick of a Team agent's commits by a person or an owner's agent, whose push GitHub shows as a person's;
+- pushes more than a week before the pull request and its oldest commit;
+- the default branch, which reads clean because it is protected;
+- the PM, which builds batch branches in the main account. The batch and `make merge-pr` must run from a default-branch checkout.
+
+The server decides who gets work and cannot stop a shell. Closing the first two takes a sandbox for every main-account agent, or a
+repository rule that keeps the app's bot to its own branch prefix.
+
+Work that needs the owner's tools or devices has no home once its task is marked: it is reviewed in a Team account, merged, and then
+checked on the owner's device, unless the owners decide otherwise.
+
### M1. The owner's files in the shared `/tmp` are readable, and can be planted (Medium)
Setup closes the home, and agents also write to `/private/tmp`, which every account shares. On the Mac Studio, the account
diff --git a/docs/superpowers/plans/2026-10-19-device-notify-tiers.md b/docs/superpowers/plans/2026-10-19-device-notify-tiers.md
index 83d206e86..02f010e57 100644
--- a/docs/superpowers/plans/2026-10-19-device-notify-tiers.md
+++ b/docs/superpowers/plans/2026-10-19-device-notify-tiers.md
@@ -1,5 +1,7 @@
# Device Notification Tiers Implementation Plan
+> Superseded on 2026-11-02 by `docs/superpowers/specs/2026-11-02-device-notify-no-jev-design.md`: device tiers no longer ask Jev, and `HARNESS_NOTIFY_SMART` is gone.
+
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** The round dial and the Pro notify only when it is worth it:
diff --git a/docs/superpowers/plans/2026-11-02-device-notify-no-jev.md b/docs/superpowers/plans/2026-11-02-device-notify-no-jev.md
new file mode 100644
index 000000000..d8f68809d
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-02-device-notify-no-jev.md
@@ -0,0 +1,67 @@
+# Device Notifications Without Jev: Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** A harness agent's finished turn alerts the devices and a Swarm agent's is silent, decided by fixed rules with no Jev call.
+
+**Architecture:** `createTierDecider` drops the Jev step and ends with two rules (Swarm -> silent, else alert). `TierInput` gains `swarm`. One shared check decides whether an agent is a Swarm agent, used by the recaps service and by the devices service.
+
+**Tech Stack:** TypeScript, vitest (cli/).
+
+**Spec:** `docs/superpowers/specs/2026-11-02-device-notify-no-jev-design.md`
+
+## Global Constraints
+
+- Rule order: `failed` -> alert (`rule:failed`); `subagent` -> silent; `onScreen` -> silent; empty recap -> silent (`rule:empty`); `swarm` -> silent (`rule:swarm`); otherwise -> alert (`rule:turn`).
+- No Jev client is created, passed or called for this decision; `HARNESS_NOTIFY_SMART` is removed.
+- `fallbackTier` stays exported (used by `lib/commander.ts`).
+- A Swarm agent: its registry row has `swarmSkill` (any role), or it runs on a Harness Team account machine.
+- Log lines keep their shape: `notify · <agent> · <tier> · rule:<name> · <detail> · <ms>ms` and the day's counts.
+- `src/services` stays at 100% per-file coverage (`npm run test:core`). Do not edit `cli/src/lib/e2ee/core.ts`.
+
+## Review Focus
+
+- An agent whose row has `swarmSkill` with role `buddy` or `lead` (not only `agent`) is silent. Test in Task 2.
+- A remote agent's card that arrives without a tier (older machine) still gets a decision and never throws. Test in Task 2.
+- A failed Swarm turn: the existing `rule:swarm-worker` path for `turn.error` is unchanged. Test in Task 2.
+- A Jev decision model installed locally (`jev:` engine ids in `lib/localModels.ts`) is not touched by this change.
+- `commander.ts` still settles a superseded turn with `fallbackTier`. Test in Task 1 (existing commander spec stays green).
+
+---
+
+### Task 1: Rules-only tier decider
+
+**Files:**
+- Modify: `cli/src/lib/notifyTier.ts`
+- Test: `cli/src/lib/notifyTier.spec.ts`
+
+**Interfaces:**
+- Produces: `TierInput` with `swarm: boolean`; `createTierDecider(opts: { now?: () => number; log: (line: string) => void; tally?: ReturnType<typeof createTally> }): (input: TierInput) => Promise<TierDecision>`; `fallbackTier`, `isTier`, `createTally` unchanged.
+
+- [ ] **Step 1: Write the failing tests** in `notifyTier.spec.ts` (replace the Jev cases):
+ - `a harness agent's finished turn alerts` -> `{ tier: 'alert', by: 'rule:turn' }`.
+ - `a Swarm agent's finished turn is silent` (`swarm: true`) -> `{ tier: 'silent', by: 'rule:swarm' }`.
+ - `the fixed rules come first`: `failed` + `swarm` -> alert `rule:failed`; `subagent`, `onScreen`, empty recap -> silent with their rule.
+ - `takes no Jev`: `createTierDecider` called with only `{ log }` decides; the module no longer exports `tierState`.
+- [ ] **Step 2: Run** `cd cli && npx vitest run src/lib/notifyTier.spec.ts`. Expected: FAIL (`rule:turn` / `rule:swarm` missing).
+- [ ] **Step 3: Implement**: remove the Jev import, `QUESTIONS`, `tierState`, `WINDOW_MS`/`recent`, `RECAP_MAX`, budget and timeout; after the fixed rules return `rule('silent', 'swarm')` for `input.swarm`, else `rule('alert', 'turn')`. Update the file's header comment.
+- [ ] **Step 4: Run** the same spec and `npx vitest run src/lib/commander.spec.ts`. Expected: PASS.
+- [ ] **Step 5: Commit** `fix(cli): device notifications follow fixed rules, not Jev: a harness turn alerts, a Swarm turn is silent`.
+
+### Task 2: Tell Swarm agents in both deciders
+
+**Files:**
+- Modify: `cli/src/services/recaps.ts:35,52-64,105-111`, `cli/src/services/devices.ts:62,100,378-401,420-427`
+- Test: `cli/src/services/recaps.spec.ts`, `cli/src/services/devices.spec.ts`
+
+**Interfaces:**
+- Consumes: Task 1's `createTierDecider({ log })` and `TierInput.swarm`.
+- Produces: in `devices.ts`, `swarmAgent(event: DialEvent): boolean` (any `swarmSkill` role, or a Team machine) beside the existing `swarmWorker` (unchanged, still `role === 'agent'` for the `turn.error` rule); in `recaps.ts`, the session's row read through `core.agents` to set `swarm`.
+
+- [ ] **Step 1: Write the failing tests:**
+ - recaps.spec: `decides a Swarm agent's turn silent` for rows with `swarmSkill.role` `lead`, `buddy`, `agent`; `decides a harness agent's turn alert`; remove the `HARNESS_NOTIFY_SMART` cases and assert no Jev client is built.
+ - devices.spec: a card without an upstream tier for a local Swarm agent (any role) and for an agent on a Team machine -> `summary` sent with tier `silent`; for a harness agent -> `alert`; a remote agent's card without a tier still gets a tier; `turn.error` for a Swarm worker still logs `rule:swarm-worker`. Remove the `HARNESS_NOTIFY_SMART` case.
+- [ ] **Step 2: Run** `cd cli && npx vitest run src/services/recaps.spec.ts src/services/devices.spec.ts`. Expected: FAIL.
+- [ ] **Step 3: Implement**: build the decider with `createTierDecider({ log })` in both services (drop `createJevDecide` and the env check; fix the two doc comments); pass `swarm` from the row (`swarmSkill` present) or a Team machine.
+- [ ] **Step 4: Run** the same specs, then `npm run test:core` and `npx tsc --noEmit`. Expected: PASS, 100% coverage.
+- [ ] **Step 5: Commit** `fix(cli): Swarm agents' finished turns are silent on devices; drop the Jev decider`.
diff --git a/docs/superpowers/specs/2026-10-19-device-notify-tiers-design.md b/docs/superpowers/specs/2026-10-19-device-notify-tiers-design.md
index bdfe6d718..b1a92feb3 100644
--- a/docs/superpowers/specs/2026-10-19-device-notify-tiers-design.md
+++ b/docs/superpowers/specs/2026-10-19-device-notify-tiers-design.md
@@ -1,5 +1,7 @@
# Device notifications: fewer, and each one worth it
+> Superseded on 2026-11-02 by `docs/superpowers/specs/2026-11-02-device-notify-no-jev-design.md`: device tiers no longer ask Jev, and `HARNESS_NOTIFY_SMART` is gone.
+
Date: 2026-10-19. Status: the direction was approved in brainstorming (a hybrid of rules and Jev). This spec is waiting for review.
## Problem
diff --git a/docs/superpowers/specs/2026-11-02-device-notify-no-jev-design.md b/docs/superpowers/specs/2026-11-02-device-notify-no-jev-design.md
new file mode 100644
index 000000000..568c3f835
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-02-device-notify-no-jev-design.md
@@ -0,0 +1,76 @@
+# Device notifications without Jev
+
+Date: 2026-11-02. Requested by Diego.
+
+## Problem
+
+When an agent finishes a turn, the recaps service decides how loudly the person's devices hear of it
+(`cli/src/lib/notifyTier.ts` `createTierDecider`, used by `cli/src/services/recaps.ts:61-64` and
+`cli/src/services/devices.ts:378-401`; design `docs/superpowers/specs/2026-10-19-device-notify-tiers-design.md`):
+
+1. fixed rules: a failed turn alerts; a sub-agent's turn, an agent on screen or an empty recap is silent;
+2. **Jev** (a hosted model) picks alert, list or silent;
+3. when Jev cannot answer, a duration fallback: 120 s or more is list, shorter is silent.
+
+Diego does not want a model deciding whether he is told. Today Jev marks most finished turns silent, so the dial
+rarely tells him a harness agent is done. The same decider also runs for Swarm agents (PM, Buddy, workers), whose
+news already reaches the dial through the Swarm chat cards (`cli/src/superTabs/cards.ts`).
+
+## Decision (Diego, 11-02)
+
+- Remove the Jev step.
+- A harness agent's finished turn that passes the fixed rules **alerts** (option A).
+- A Swarm agent's finished turn is **silent** on devices: the Swarm tells its news through the chat cards, which this
+ change does not touch.
+
+## Design
+
+- `createTierDecider` keeps the fixed rules, in order, then:
+ - a Swarm agent (`swarm: true`) -> silent, `rule:swarm`;
+ - otherwise -> alert, `rule:turn`.
+- It no longer takes, creates or calls a Jev client, and no longer keeps the 30-minute `recent` window. `tierState`,
+ the Jev questions and the `jev` option go; `fallbackTier` stays, because `lib/commander.ts` still uses it when a
+ decision is superseded before it lands.
+- `TierInput` gains `swarm: boolean`.
+- A Swarm agent is an agent whose registry row carries `swarmSkill` (any role: PM, Buddy, Builder, Reviewer, Tester),
+ or any agent on a Harness Team account machine. `devices.ts` already tells a Swarm worker this way (`swarmWorker`,
+ :423-427, role `agent` only); it widens to every role and is shared by the recaps' and the dial's decisions.
+- `recaps.ts` decides with the session's row; `devices.ts` (a card that arrives without an upstream tier) decides with
+ the same check. A remote agent's card normally carries its own machine's tier, so nothing changes for it.
+- The decision log keeps its shape (`notify · <agent> · <tier> · rule:<name> · …` and the day's counts), so the log
+ still shows the volume.
+- `HARNESS_NOTIFY_SMART` loses its meaning and is removed.
+
+## Who is affected
+
+The tier is decided once for the dial, the Harness Pro, and apps listening over the relay (the phone reads it from
+`turn_summary`). So a harness agent's finished turn now alerts on all of them, and a Swarm agent's turn is silent on
+all of them. The Desktop window on the same computer reads no tier, so it is unchanged.
+
+## Known limits
+
+- A Swarm agent started without its Swarm skill has no `swarmSkill` on its row, so its turns alert like a harness
+ agent's (`superTabs/start.ts` sets the role only with a skill mode).
+- A card from an older remote daemon that sends no tier is decided here; a Swarm agent there that is not on a Team
+ machine alerts, because this machine cannot read its row.
+
+## Non-goals
+
+- Swarm chat notices on the dial (cards), and making device counts match the apps (the attention-summary work).
+- Re-announcing open questions after a daemon restart.
+
+## Design checklist
+
+- Growth, concurrency, read cost, scale: one fewer network call per finished turn; nothing stored.
+- Compatibility: devices already accept all three tiers; older daemons keep deciding with Jev.
+- Migration and rollback: none; reverting restores Jev.
+- Audience, identity: nothing leaves the machine any more for this decision (Jev received the recap text).
+- Failure: no external call, so no timeout path; the fixed rules always answer.
+- Platforms: all.
+
+## Testing
+
+- `notifyTier.spec`: a harness turn alerts (`rule:turn`); a Swarm turn is silent (`rule:swarm`); the fixed rules win
+ over both (failed alerts, sub-agent, on screen and empty recap are silent); no Jev client is called or accepted.
+- `recaps` / `devices` specs: an agent with `swarmSkill` (role `lead`, `buddy`, `agent`) and an agent on a Team
+ machine are decided silent; a plain harness agent alerts.