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.

fix(super-tabs): an ended Buddy's sent-files cleanup fails by fixed codes, never with a path (#2406)

0xken1505c9ba35a59c
diff --git a/cli/src/lib/buddyGuard.spec.ts b/cli/src/lib/buddyGuard.spec.ts
index fbc7de5a0..159886c17 100644
--- a/cli/src/lib/buddyGuard.spec.ts
+++ b/cli/src/lib/buddyGuard.spec.ts
@@ -3,9 +3,11 @@ import { createHash } from 'node:crypto'
import { appendFileSync, chmodSync, existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, symlinkSync,
truncateSync, utimesSync, writeFileSync, type Stats } from 'node:fs'
import { tmpdir } from 'node:os'
+import { inspect } from 'node:util'
import { basename, dirname, join } from 'node:path'
import { afterAll, beforeEach, describe, expect, it } from 'vitest'
-import { allowBuddyReads, artifactLinks, buddyGuardCommand, buddyGuardSource, buddyReadsOf, forgetBuddyReads, grantBuddyWide, recordBuddyApprovals } from './buddyGuard.js'
+import { allowBuddyReads, artifactLinks, buddyGuardCommand, buddyGuardSource, buddyReadsOf, forgetBuddyReads, grantBuddyWide, recordBuddyApprovals,
+ SentListsError } from './buddyGuard.js'
// The guard Claude Code runs before each of a Buddy's tool calls, run here as it runs there: the script, with node, the
// hook's input on stdin and its decision on stdout.
@@ -594,6 +596,17 @@ describe('the host\'s list of what a Buddy\'s person sent it', () => {
rmSync(lists, { recursive: true, force: true })
for (const path of [sent, later]) { rmSync(path, { force: true }); writeFileSync(path, 'bytes') }
})
+ // Follow-up to #2389's security re-check 2: the host logs what an end failed with, and a filesystem error's message names
+ // its path, under the person's home. It fails by fixed codes alone, carrying nothing of the error it caught.
+ const failsWith = (session: string, codes: string[]) => {
+ let thrown: unknown
+ try { forgetBuddyReads(session, lists) } catch (error) { thrown = error }
+ expect(thrown).toBeInstanceOf(SentListsError)
+ expect((thrown as SentListsError).codes).toEqual(codes)
+ expect((thrown as Error).message).toBe(codes.join(', '))
+ expect((thrown as Error).cause).toBeUndefined()
+ expect(inspect(thrown)).not.toContain(parent)
+ }
it('is kept for each Buddy session apart, in Harness\'s data folder, beside its downloads folder', () => {
expect(buddyReadsOf('session-key')).toEqual({
@@ -752,7 +765,7 @@ describe('the host\'s list of what a Buddy\'s person sent it', () => {
expect(decide('Read', { file_path: later }, theirGuard)).toBe('deny')
expect(() => forgetBuddyReads('harness-1', lists)).not.toThrow()
expect(existsSync(mine.file)).toBe(false)
- expect(() => forgetBuddyReads('harness-2', lists)).toThrow(/director/i)
+ failsWith('harness-2', ['SENT_LIST_KEPT'])
expect(existsSync(mark(theirs.file, 'harness-2'))).toBe(true)
expect(decide('Read', { file_path: later }, theirGuard)).toBe('deny')
} finally { rmSync(theirs.file, { recursive: true, force: true }) }
@@ -766,7 +779,7 @@ describe('the host\'s list of what a Buddy\'s person sent it', () => {
const own = mark(mine.file, 'harness-1')
rmSync(own); mkdirSync(join(own, 'held'), { recursive: true })
try {
- expect(() => forgetBuddyReads('harness-1', lists)).toThrow(/director/i)
+ failsWith('harness-1', ['SENT_LIST_MARK_KEPT'])
expect(existsSync(mine.file)).toBe(false)
expect(decide('Read', { file_path: sent }, guard)).toBe('deny')
} finally { rmSync(own, { recursive: true, force: true }) }
@@ -799,7 +812,7 @@ describe('the host\'s list of what a Buddy\'s person sent it', () => {
expect(decide('Read', { file_path: sent }, guard)).toBe('allow')
chmodSync(lists, 0o500)
try {
- expect(() => forgetBuddyReads('harness-1', lists)).toThrow(/EACCES|EPERM/)
+ failsWith('harness-1', ['SENT_LIST_KEPT'])
expect(existsSync(mine.file)).toBe(true)
expect(existsSync(mark(mine.file, 'harness-1'))).toBe(true)
expect(decide('Read', { file_path: sent }, guard)).toBe('deny')
@@ -824,7 +837,7 @@ describe('the host\'s list of what a Buddy\'s person sent it', () => {
chmodSync(lists, 0o500)
try {
expect(() => forgetBuddyReads('harness-2', lists)).not.toThrow()
- expect(() => forgetBuddyReads('harness-1', lists)).toThrow(/EACCES|EPERM/)
+ failsWith('harness-1', ['SENT_LIST_KEPT'])
expect(existsSync(mine.file)).toBe(true)
} finally { chmodSync(lists, 0o700) }
expect(() => forgetBuddyReads('harness-1', lists)).not.toThrow()
@@ -838,7 +851,7 @@ describe('the host\'s list of what a Buddy\'s person sent it', () => {
writeFileSync(orphan, JSON.stringify({ version: 1, session: 'harness-2', files: [], links: [] }))
chmodSync(orphan, 0o000)
try {
- expect(() => forgetBuddyReads('harness-1', lists)).toThrow(/EACCES|EPERM/)
+ failsWith('harness-1', ['SENT_LIST_UNREAD'])
expect(existsSync(orphan)).toBe(true)
writeFileSync(mark(orphan, 'harness-2'), '')
expect(() => forgetBuddyReads('harness-1', lists)).not.toThrow()
@@ -874,6 +887,33 @@ describe('the host\'s list of what a Buddy\'s person sent it', () => {
expect(held().session).toBe('harness-1')
})
+ // Follow-up to #2389's security re-check 2: a lists folder that could not be read threw the read's own error, its path with
+ // it, into the daemon's log. It fails by its kind alone, deletes nothing, and the end is tried again.
+ it('fails by a fixed code, with no path, when the lists folder cannot be read, deletes nothing, and finishes once it can', () => {
+ allowBuddyReads(mine, { session: 'harness-1', files: [sent], links: [] })
+ const before = readdirSync(lists).sort()
+ chmodSync(lists, 0o000)
+ try {
+ failsWith('harness-1', ['SENT_LISTS_UNREAD'])
+ } finally { chmodSync(lists, 0o700) }
+ expect(readdirSync(lists).sort()).toEqual(before)
+ expect(decide('Read', { file_path: sent }, guard)).toBe('allow')
+ expect(() => forgetBuddyReads('harness-1', lists)).not.toThrow()
+ expect(readdirSync(lists)).toEqual([])
+ expect(decide('Read', { file_path: sent }, guard)).toBe('deny')
+ })
+
+ it('names each kind of failure once, in a fixed order, when an end meets several', () => {
+ allowBuddyReads(mine, { session: 'harness-1', files: [sent], links: [] })
+ const orphans = ['orphan-a.json', 'orphan-b.json'].map(name => join(lists, name))
+ for (const orphan of orphans) { writeFileSync(orphan, JSON.stringify({ version: 1, session: 'harness-2', files: [], links: [] })); chmodSync(orphan, 0o000) }
+ chmodSync(lists, 0o500)
+ try {
+ failsWith('harness-1', ['SENT_LIST_UNREAD', 'SENT_LIST_KEPT'])
+ for (const file of [mine.file, ...orphans]) expect(existsSync(file)).toBe(true)
+ } finally { chmodSync(lists, 0o700); for (const orphan of orphans) chmodSync(orphan, 0o600) }
+ })
+
it('forgets nothing, and fails nothing, where no list was ever written', () => {
expect(() => forgetBuddyReads('harness-1', lists)).not.toThrow()
expect(existsSync(lists)).toBe(false)
diff --git a/cli/src/lib/buddyGuard.ts b/cli/src/lib/buddyGuard.ts
index 167605cb1..5e251bb29 100644
--- a/cli/src/lib/buddyGuard.ts
+++ b/cli/src/lib/buddyGuard.ts
@@ -1118,47 +1118,64 @@ export function recordBuddyApprovals(input: { reads: BuddyReads; session: string
* an own list it cannot delete (a folder it cannot write to), which it empties in place where it can, needing only the
* file, so the guard allows nothing meanwhile, keeping that list's mark and its session so the next try finds it; and a
* mark it cannot delete. A list that went between the folder's read and its own counts as gone.
+ *
+ * It fails by fixed codes alone (`SentListsError`), never with the error it caught: the host logs what it failed with, and
+ * a filesystem error's message names its path, in the person's home (follow-up to #2389's security re-check 2).
*/
export function forgetBuddyReads(session: string, dir = listsDir()): void {
let names: string[]
try { names = readdirSync(dir) } catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return
- throw error
+ throw new SentListsError(['SENT_LISTS_UNREAD'])
}
const own = `.${sha256(session)}.owner`
const marked = new Set(names.filter(name => name.endsWith(own)).map(name => `${name.slice(0, -own.length)}.json`))
const kept = new Set<string>()
- let failed: unknown
+ const failed = new Set<SentListsFailure>()
// Only a list's own name: a .tmp is a write not yet renamed, which no guard reads.
for (const name of names) {
if (!name.endsWith('.json')) continue
const file = join(dir, name)
- let text: string | undefined, unreadable: unknown
- try { text = readFileSync(file, 'utf8') } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') unreadable = error }
+ let text: string | undefined, unreadable = false
+ try { text = readFileSync(file, 'utf8') } catch (error) { unreadable = (error as NodeJS.ErrnoException).code !== 'ENOENT' }
let named: unknown
try { named = text === undefined ? undefined : (JSON.parse(text) as { session?: unknown } | null)?.session } catch { /* not JSON: it names no session */ }
if (!marked.has(name)) {
// Not its own by mark. One it cannot read is another session's to remove when that session's mark is beside it, and
// otherwise whose it is cannot be told: kept, and the end fails so it is tried again, as before marks (review of #2261).
- if (unreadable !== undefined) {
+ if (unreadable) {
const base = `${name.slice(0, -'.json'.length)}.`
- if (!names.some(other => other.startsWith(base) && MARK.test(other))) failed ??= unreadable
+ if (!names.some(other => other.startsWith(base) && MARK.test(other))) failed.add('SENT_LIST_UNREAD')
continue
}
if (named !== session) continue
} else if (typeof named === 'string' && named !== session) continue
- try { rmSync(file, { force: true }) } catch (error) {
+ try { rmSync(file, { force: true }) } catch {
const empty: List = { version: 1, session, files: [], links: [] }
try { writeFileSync(file, `${JSON.stringify(empty)}\n`) } catch { /* neither: the host's next try is all that is left */ }
kept.add(name)
- failed ??= error
+ failed.add('SENT_LIST_KEPT')
}
}
for (const name of names) {
if (!name.endsWith(own) || kept.has(`${name.slice(0, -own.length)}.json`)) continue
- try { rmSync(join(dir, name), { force: true }) } catch (error) { failed ??= error }
+ try { rmSync(join(dir, name), { force: true }) } catch { failed.add('SENT_LIST_MARK_KEPT') }
+ }
+ if (failed.size) throw new SentListsError(SENT_LISTS_FAILURES.filter(code => failed.has(code)))
+}
+
+/** What kept an ended session's lists from all going, in the order they are named: its lists folder could not be read; a list
+ * whose session could not be told could not be read, and was kept; one of its own lists could not be deleted, and was emptied
+ * where it could be; or the mark beside one could not be deleted. */
+const SENT_LISTS_FAILURES = ['SENT_LISTS_UNREAD', 'SENT_LIST_UNREAD', 'SENT_LIST_KEPT', 'SENT_LIST_MARK_KEPT'] as const
+export type SentListsFailure = typeof SENT_LISTS_FAILURES[number]
+
+/** `forgetBuddyReads`'s failure: its codes, each once, and nothing of the errors behind them, whose messages name paths. */
+export class SentListsError extends Error {
+ constructor(readonly codes: readonly SentListsFailure[]) {
+ super(codes.join(', '))
+ this.name = 'SentListsError'
}
- if (failed) throw failed
}
const shellQuote = (value: string) => `'${value.replace(/'/g, `'\\''`)}'`
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index 7afe20deb..b777a3188 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -4,10 +4,16 @@ import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync,
import { tmpdir } from 'node:os'
import { basename, dirname, join } from 'node:path'
import { prepareSwarmSkill } from '../lib/swarmSkills.js'
-import { allowBuddyReads, buddyAccountFile, buddyApprovalsOf, buddyGuardSource, buddyLaunchFile, buddyReadsOf, buddyWideOf } from '../lib/buddyGuard.js'
+import { allowBuddyReads, buddyAccountFile, buddyApprovalsOf, buddyGuardSource, buddyLaunchFile, buddyReadsOf, buddyWideOf, forgetBuddyReads } from '../lib/buddyGuard.js'
import { env } from '../config/env.js'
import { PASTE_DROPS_DIR } from '../lib/pasteDropFiles.js'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+// The real lists cleanup, which one test makes throw what it never throws today: an error that is not its own.
+vi.mock('../lib/buddyGuard.js', async original => {
+ const actual = await original<typeof import('../lib/buddyGuard.js')>()
+ return { ...actual, forgetBuddyReads: vi.fn(actual.forgetBuddyReads) }
+})
import type { BackendNotice, CoreApi, TurnDelivery } from '../core/api.js'
import { fakeCore } from '../testing/fakeCore.js'
import { backend, BUDDY_SESSION_GONE_MS, BUDDY_SESSION_IDLE_MS, BUDDY_SESSION_SLEEP_GAP_MS, buddyChatIdOf, swarmRoleFor, hostJournalFile, SuperTabHost, type SuperTabHostOptions } from './host.js'
@@ -3385,6 +3391,52 @@ describe('closing the sessions the backend ends', () => {
for (const file of [buddyReadsOf('other-buddy').file, shot]) rmSync(file)
})
+ // Follow-up to #2389's security re-check 2: a lists folder that could not be read threw the read's own error into this log,
+ // its path under the person's home with it. It is logged by a fixed code, once, nothing is deleted, and the end waits.
+ it('logs a lists folder it cannot read by a fixed code, with no path, deletes nothing, and acknowledges the end once it can', async () => {
+ const t = lifeFixture([leadRow({ lead: false })])
+ mkdirSync(PASTE_DROPS_DIR, { recursive: true })
+ const shot = join(PASTE_DROPS_DIR, `${randomUUID().slice(0, 8)}-screen.png`)
+ writeFileSync(shot, 'png')
+ const reads = buddyReadsOf('unread-folder-buddy'), lists = dirname(reads.file)
+ allowBuddyReads(reads, { session: 'harness', files: [shot], links: [] })
+ const before = readdirSync(lists).sort()
+ await t.poll()
+ chmodSync(lists, 0o000)
+ try {
+ t.rows.splice(0, 1, ended())
+ await t.poll()
+ await vi.waitFor(() => expect(t.closeMember).toHaveBeenCalledTimes(1))
+ for (let i = 0; i < 3; i++) await t.poll(60_000)
+ expect(t.commands).toEqual([])
+ const line = 'Could not delete what session harness\'s person sent it, so its end is not acknowledged yet: SENT_LISTS_UNREAD'
+ expect(t.log.mock.calls.filter(([said]) => said === line)).toHaveLength(1)
+ const said = t.log.mock.calls.flat().join('\n')
+ for (const path of [lists, env.ADAPTER_DATA_DIR, tmpdir()]) expect(said).not.toContain(path)
+ } finally { chmodSync(lists, 0o700) }
+ expect(readdirSync(lists).sort()).toEqual(before)
+ await t.poll()
+ await vi.waitFor(() => expect(t.commands).toHaveLength(1))
+ expect(existsSync(reads.file)).toBe(false)
+ rmSync(shot)
+ })
+
+ // Follow-up to #2389's security re-check 2: the host logs an end's failure by its codes alone. One that is not the cleanup's
+ // own, whose message may name a path, is logged by kind, never by its message.
+ it('logs a failure that is not the lists cleanup\'s own by kind, never by its message', async () => {
+ const t = lifeFixture([leadRow({ lead: false })])
+ await t.poll()
+ vi.mocked(forgetBuddyReads).mockImplementationOnce(() => { throw new Error('EACCES: permission denied, scandir \'/Users/person/.harness/buddy-reads\'') })
+ t.rows.splice(0, 1, ended())
+ await t.poll()
+ expect(t.log).toHaveBeenCalledWith('Could not delete what session harness\'s person sent it, so its end is not acknowledged yet: SENT_LISTS_FAILED')
+ expect(t.log.mock.calls.flat().join('\n')).not.toContain('/Users/person')
+ await vi.waitFor(() => expect(t.closeMember).toHaveBeenCalledTimes(1))
+ expect(t.commands).toEqual([])
+ await t.poll()
+ await vi.waitFor(() => expect(t.commands).toHaveLength(1))
+ })
+
// Re-check 2 of #2248: a list the host could not delete was only logged; the end was acknowledged, the backend dropped the
// row, and nothing tried again, so the list kept allowing its file for the rest of the day.
it('acknowledges a Buddy session\'s end only once its list is deleted, and its guard allows nothing meanwhile', async () => {
@@ -3409,7 +3461,9 @@ describe('closing the sessions the backend ends', () => {
expect(t.commands).toEqual([])
expect(existsSync(reads.file)).toBe(true)
expect(guardReads(guard, folder, shot)).toBe('deny')
- expect(t.log).toHaveBeenCalledWith(expect.stringContaining('so its end is not acknowledged yet'))
+ // By its kind alone (follow-up to #2389's security re-check 2): the error it caught named the list's path.
+ expect(t.log).toHaveBeenCalledWith('Could not delete what session harness\'s person sent it, so its end is not acknowledged yet: SENT_LIST_KEPT')
+ expect(t.log.mock.calls.flat().join('\n')).not.toContain(dirname(reads.file))
} finally { chmodSync(dirname(reads.file), 0o700) }
await t.poll()
await vi.waitFor(() => expect(t.commands).toHaveLength(1))
diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.ts
index fa6bf5b3a..4c575d033 100644
--- a/cli/src/superTabs/host.ts
+++ b/cli/src/superTabs/host.ts
@@ -39,7 +39,7 @@ export { backend, identifier, object, SuperTabHostError } from './wire.js'
import { backend, ENDED_WORK, identifier, object, SuperTabHostError } from './wire.js'
import { recordSwarmSkillNotice, refreshSwarmSkill, type SkillRefresh, type SwarmSkillGrant, type SwarmSkillMode } from '../lib/swarmSkills.js'
import { allowBuddyReads, artifactLinks, buddyApprovalsOf, buddyLaunchOf, buddyReadsOf, forgetBuddyReads, grantBuddyWide, hasBuddyApprovals,
- judgeBuddyApprovals, recordBuddyApprovals, writeBuddyAccount, type JudgedApprovals } from '../lib/buddyGuard.js'
+ judgeBuddyApprovals, recordBuddyApprovals, SentListsError, writeBuddyAccount, type JudgedApprovals } from '../lib/buddyGuard.js'
/** The skills of a group's project in a tab state: a group from before projects is in the first, and a project from before
* modes, or a Swarm from before projects, is orchestration. */
@@ -1098,7 +1098,9 @@ export class SuperTabHost {
// could not be read held back every Buddy's end on the machine (follow-up to #2248, lib/buddyGuard.ts `forgetBuddyReads`).
if (!state.forgotten) {
try { forgetBuddyReads(agent.harnessId); state.forgotten = true; delete state.unforgotten } catch (error) {
- const why = error instanceof Error ? error.message : String(error)
+ // By fixed codes alone: a filesystem error's message names its path, in the person's home (follow-up to #2389's
+ // security re-check 2). Anything else it might throw is named by kind too, never by its message.
+ const why = error instanceof SentListsError ? error.message : 'SENT_LISTS_FAILED'
if (why !== state.unforgotten) {
this.log(`Could not delete what session ${agent.harnessId.slice(0, 8)}'s person sent it, so its end is not acknowledged yet: ${why}`)
}