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-06 k0945: #3297 #3294 #3293 #3303 #3301 (#3308)

0xken15bb34f2907d52
diff --git a/backend/src/superTabs/cards.ts b/backend/src/superTabs/cards.ts
index 9525e7ed9..9b30ff9cf 100644
--- a/backend/src/superTabs/cards.ts
+++ b/backend/src/superTabs/cards.ts
@@ -12,6 +12,9 @@ export interface GroupCards {
task?: string
/** Each linked pull request's card: the first main-chat message that linked it, and when a merge was recorded. */
pullRequests?: PullRequestCard[]
+ /** Pull requests only a merge record linked as the task's code, none of its own words (commands.ts conversation.merged, #3574): the
+ * record never makes one the task's own, so recording it again closes nothing. */
+ recorded?: string[]
/** Its one line in its project chat and what it last showed (taskLine.ts). */
line?: import('./taskLine.js').TaskLine
}
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 63e683857..ef8ee0a6c 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -2723,6 +2723,16 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
const pullRequestUrl = projectPullRequestUrl(command.pullRequestUrl, repositoryUrl)
?? fail('PULL_REQUEST_REPOSITORY', `This pull request is not in the project's repository (${own!.fullName}).`, 400)
const shippedAt = group.ledger?.shippedAt, linked = group.pullRequestUrls?.includes(pullRequestUrl)
+ // Whether the task itself named this pull request before the record: in its result or a check's evidence (the Ready line), or in
+ // its code list (its brief, its builder's or the project's own posts). A builder lost before its Ready line has only the
+ // posts, and its merged task must still close (task #3574). Read before the record links anything.
+ const assignment = group.assignment
+ // Only the code list: a task stored before it existed reads every link it held as its code, posts' and earlier merge records' included.
+ const namedBefore = group.codePullRequestUrls?.includes(pullRequestUrl) ?? false
+ const ownPullRequest = (namedBefore && !group.cards?.recorded?.includes(pullRequestUrl))
+ || (!!assignment && [assignment.result, ...group.checks.map(check => check.evidence)].some(text => !!text && pullRequestLinks(text, repositoryUrl).includes(pullRequestUrl)))
+ // What only this record linked stays marked, so a repeated record of an unrelated pull request closes nothing (Aster, #3259).
+ if (!ownPullRequest && !group.cards?.recorded?.includes(pullRequestUrl)) group.cards = { ...group.cards, recorded: [...group.cards?.recorded ?? [], pullRequestUrl] }
appendPullRequestUrls(group, [pullRequestUrl], repositoryUrl)
// The pull request that merged is the task's own code.
appendCodePullRequestUrls(group, [pullRequestUrl], repositoryUrl)
@@ -2745,11 +2755,9 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
// A merged task whose builder is gone closes itself with the merge as its result (task #3510): a released builder can
// no longer set its own Done, and the task would stay in review for good. A live builder still closes its own task, and
// a step never closes here, nor its parent through it. Only the task's own pull request closes it: one its builder named in
- // its result (the Ready line) or a check's evidence names, which a merge record never writes. A merge of an unrelated one
- // recorded here, even twice, only links it (Aster, review of #3259).
- const assignment = group.assignment
- const ownPullRequest = assignment && [assignment.result, ...group.checks.map(check => check.evidence)]
- .some(text => !!text && pullRequestLinks(text, repositoryUrl).includes(pullRequestUrl))
+ // its result (the Ready line), a check's evidence or its own posts, which a merge record never writes. A merge of an unrelated
+ // one recorded here, even twice, only links it (Aster, review of #3259). Closed whenever the record is made: a lost attempt, a
+ // merge recorded again later (#3574).
if (ownPullRequest && !isStep(group) && assignment && !['done', 'cancelled'].includes(assignment.status) && builderGone(state, assignment)) {
const previous = assignment.status
assignment.status = 'done'
diff --git a/backend/src/superTabs/mergedCloses.test.ts b/backend/src/superTabs/mergedCloses.test.ts
index 6423b31a4..56f5e980f 100644
--- a/backend/src/superTabs/mergedCloses.test.ts
+++ b/backend/src/superTabs/mergedCloses.test.ts
@@ -1,7 +1,7 @@
// Task #3510 (anh Dee's Swarm redesign): a recorded merge closes a task whose builder is gone, so a released builder no longer
// leaves its merged task in review for good; a live builder still closes its own task.
import { describe, expect, it } from 'vitest'
-import { appendPullRequestUrls } from './model.js'
+import { appendCodePullRequestUrls, appendPullRequestUrls } from './model.js'
import { stepsFixture } from './steps.test-support.js'
const PR = 'https://github.com/acme/app/pull/7'
@@ -107,3 +107,97 @@ describe('a recorded merge closes a task whose builder is gone (#3510)', () => {
expect(effects.closedAssignment).toBeUndefined()
})
})
+
+// Task #3574: seven merged tasks stayed lost on the board. A builder that is lost before its Ready line has no result naming its
+// pull request; the pull request its own posts named (the code list) is still the task's own, so its merge closes the task.
+describe('a merged task ends done whatever happened to its builder (#3574)', () => {
+ /** A task whose builder posted its pull request (the store lists it as the task's code) but never wrote a Ready line naming it. */
+ function postedFixture() {
+ const f = mergedFixture()
+ f.group(f.task).assignment!.result = 'Working on it'
+ appendPullRequestUrls(f.group(f.task), [PR])
+ appendCodePullRequestUrls(f.group(f.task), [PR])
+ return f
+ }
+
+ it('closes a lost attempt, whose result names no pull request, when its merge is recorded', () => {
+ const f = postedFixture()
+ f.group(f.task).assignment!.status = 'lost'
+ const effects = f.merge()
+ expect(f.group(f.task).assignment).toMatchObject({ id: f.assignment, status: 'done' })
+ expect(f.group(f.task).assignment!.result).toContain(PR)
+ expect(effects.closedAssignment).toEqual({ assignmentId: f.assignment, outcome: 'done' })
+ })
+
+ it('closes a task whose merge was already recorded when it is recorded again after its attempt was lost', () => {
+ const f = postedFixture()
+ f.merge()
+ expect(f.group(f.task).assignment).toMatchObject({ status: 'review' })
+ f.group(f.task).assignment!.status = 'lost'
+ const effects = f.merge()
+ expect(f.group(f.task).assignment).toMatchObject({ id: f.assignment, status: 'done' })
+ expect(effects.closedAssignment).toEqual({ assignmentId: f.assignment, outcome: 'done' })
+ })
+
+ it('closes a stopped attempt the same way', () => {
+ const f = postedFixture()
+ f.group(f.task).assignment!.status = 'stopped'
+ f.merge()
+ expect(f.group(f.task).assignment).toMatchObject({ status: 'done' })
+ })
+
+ it('lets the closed task be archived, where a lost one was refused', () => {
+ const f = postedFixture()
+ f.group(f.task).assignment!.status = 'lost'
+ expect(() => f.run({ type: 'conversation.archive', conversationId: f.task, archived: true }, f.as(f.lead))).toThrow(/did not finish/)
+ f.merge()
+ f.run({ type: 'conversation.archive', conversationId: f.task, archived: true }, f.as(f.lead))
+ expect(f.group(f.task).archived).toBe(true)
+ })
+
+ // The ownership Aster's review asked for still holds: a pull request only the merge record linked never closes a task.
+ it('still closes nothing for a pull request only a merge record linked, however often it is recorded', () => {
+ const f = postedFixture()
+ const other = { type: 'conversation.merged' as const, conversationId: f.task, pullRequestUrl: 'https://github.com/acme/app/pull/99' }
+ f.group(f.task).assignment!.status = 'lost'
+ f.run(other, f.as(f.lead))
+ f.run(other, f.as(f.lead))
+ expect(f.group(f.task).assignment).toMatchObject({ status: 'lost' })
+ })
+ // Review of #3294: a task stored before the code list existed reads every link it ever held as its code. Its ownership stays what
+ // #3259 read (the result or a check's evidence), so a pull request only mentioned in a post, or only linked by an earlier merge
+ // record, closes nothing.
+ describe('a task stored without a code list', () => {
+ const OTHER = 'https://github.com/acme/app/pull/99'
+ function legacyFixture() {
+ const f = postedFixture()
+ delete f.group(f.task).codePullRequestUrls
+ f.group(f.task).assignment!.status = 'lost'
+ return f
+ }
+
+ it('closes nothing for a pull request an agent only mentioned in a post', () => {
+ const f = legacyFixture()
+ appendPullRequestUrls(f.group(f.task), [OTHER])
+ f.run({ type: 'conversation.merged', conversationId: f.task, pullRequestUrl: OTHER }, f.as(f.lead))
+ expect(f.group(f.task).assignment).toMatchObject({ status: 'lost' })
+ })
+
+ it('closes nothing for a pull request an earlier merge record linked, before the marker existed', () => {
+ const f = legacyFixture()
+ // Linked by a merge record of an earlier release: it left a link and no marker.
+ appendPullRequestUrls(f.group(f.task), [OTHER])
+ const effects = f.run({ type: 'conversation.merged', conversationId: f.task, pullRequestUrl: OTHER }, f.as(f.lead))
+ f.run({ type: 'conversation.merged', conversationId: f.task, pullRequestUrl: OTHER }, f.as(f.lead))
+ expect(f.group(f.task).assignment).toMatchObject({ status: 'lost' })
+ expect(effects.closedAssignment).toBeUndefined()
+ })
+
+ it('still closes on a pull request its result names', () => {
+ const f = legacyFixture()
+ f.group(f.task).assignment!.result = `Ready for review: ${PR} at abc1234`
+ f.merge()
+ expect(f.group(f.task).assignment).toMatchObject({ status: 'done' })
+ })
+ })
+})
diff --git a/backend/src/superTabs/releaseWatch.test.ts b/backend/src/superTabs/releaseWatch.test.ts
index a270d94e2..15eaff7e1 100644
--- a/backend/src/superTabs/releaseWatch.test.ts
+++ b/backend/src/superTabs/releaseWatch.test.ts
@@ -101,6 +101,23 @@ describe('readReleases.mergeCommit and contains', () => {
expect(await readReleases(none.get).mergeCommit(REPO, 7, T)).toBeNull()
})
+ // Task #3586: a merge recorded long after its batch landed is outside the recorded time's window; main's newest commits are read.
+ it('finds a batch commit outside the merge\'s time window in main\'s newest commits', async () => {
+ const asked: string[] = []
+ const get: GitHubGet = async (_repository, path) => {
+ asked.push(path)
+ if (path === '/repos/acme/app') return repo
+ if (path === '/repos/acme/app/pulls/7') return { status: 200, body: { merged_at: null, state: 'closed' } }
+ if (path.includes('since=')) return { status: 200, body: [] }
+ return { status: 200, body: [{ sha: 'newer', commit: { message: 'Merge batch i3: #70 (#81)' } }, { sha: 'batch', commit: { message: 'Merge batch i0: #6 #7 (#79)' } }] }
+ }
+ expect(await readReleases(get).mergeCommit(REPO, 7, T)).toBe('batch')
+ expect(asked.at(-1)).toBe('/repos/acme/app/commits?sha=main&per_page=100')
+ // Nothing anywhere: not found, rather than a guess.
+ const none: GitHubGet = async (_repository, path) => path === '/repos/acme/app' ? repo : path.endsWith('/pulls/7') ? { status: 200, body: { merged_at: null } } : { status: 200, body: [] }
+ expect(await readReleases(none).mergeCommit(REPO, 7, T)).toBeNull()
+ })
+
it('looks for a batch every pass in the merge\'s first hour, then every 30 minutes, then every 2 hours after a day', () => {
const HOUR = 3_600_000, half = 30 * 60_000, at = 100 * 24 * HOUR
expect(batchLookupDue(at, at + 10 * 60_000 + 7)).toBe(true)
@@ -155,7 +172,8 @@ describe('watchReleases', () => {
// g1's merge commit waits for Desktop and Web, which GitHub could not read: it is found again next pass.
resolved: [{ groupId: 'g1', url: 'https://github.com/acme/app/pull/7', components: ['desktop', 'web'] },
{ groupId: 'g2', url: 'https://github.com/acme/app/pull/8', sha: 'm8' }],
- releases: { backend: { tag: 'v1.4.17_backend', sha: 'b', at: T, carries: [pendingKey({ groupId: 'g2', url: 'https://github.com/acme/app/pull/8' })] } } } }])
+ releases: { backend: { tag: 'v1.4.17_backend', sha: 'b', at: T, carries: [pendingKey({ groupId: 'g2', url: 'https://github.com/acme/app/pull/8' })],
+ compared: [pendingKey({ groupId: 'g2', url: 'https://github.com/acme/app/pull/8' })] } } } }])
})
it('reads an open step\'s component too, and nothing for a project with nothing to settle', async () => {
@@ -180,12 +198,13 @@ describe('watchReleases', () => {
})
it('compares again only for a new tag or a newly resolved merge, and leaves out a release whose comparison GitHub could not answer', async () => {
- const known = { pending: [{ groupId: 'g2', url: 'https://github.com/acme/app/pull/8', mergedAt: T - 1, components: ['backend' as const], sha: 'm8' }],
+ const known = { pending: [{ groupId: 'g2', url: 'https://github.com/acme/app/pull/8', mergedAt: T - 1, components: ['backend' as const], sha: 'm8',
+ checked: { backend: 'v1.4.17_backend' } }],
last: { backend: { tag: 'v1.4.17_backend', sha: 'b', at: T } } }
const same = scene(known)
await watchReleases(same.db, same.store, same.fake, T, { warn: () => {}, info: () => {} })
expect(same.read).toEqual(['latest backend', 'done'])
- const unsure = scene({ ...known, last: {} }, { contains: async () => null })
+ const unsure = scene({ pending: [{ ...known.pending[0]!, checked: undefined }], last: {} }, { contains: async () => null })
await watchReleases(unsure.db, unsure.store, unsure.fake, T, { warn: () => {}, info: () => {} })
expect(unsure.settled[0]!.facts.releases).toEqual({})
})
@@ -205,7 +224,37 @@ describe('watchReleases', () => {
{ ...readReleases(g.get), done: async () => {} })
await watchReleases(s.db, s.store, s.fake, T + 6 * 60_000, { warn: () => {}, info: () => {} })
expect(s.settled[0]!.facts.releases.cli).toEqual({ tag: 'v0.5.55_cli', sha: 'm7', at: T + 5 * 60_000,
- carries: [pendingKey({ groupId: 'g1', url: 'https://github.com/acme/app/pull/7' })] })
+ carries: [pendingKey({ groupId: 'g1', url: 'https://github.com/acme/app/pull/7' })], compared: [pendingKey({ groupId: 'g1', url: 'https://github.com/acme/app/pull/7' })] })
+ })
+
+ // Task #3586 (anh Dee, 2026-11-06): #3307 and #3353 went out in CLI 0.5.57, cut before the backend recorded releases, and the Swarm
+ // kept them waiting: a release already settled was compared only with merges found since. Every waiting merge is compared with
+ // each release once, whenever the release was cut.
+ it('compares a waiting merge with the release already settled, once, if it was never compared with it', async () => {
+ const entry = { groupId: 'g2', url: 'https://github.com/acme/app/pull/8', mergedAt: T - 1, components: ['backend' as const], sha: 'm8' }
+ const s = scene({ pending: [entry], last: { backend: { tag: 'v1.4.17_backend', sha: 'b', at: T } } })
+ await watchReleases(s.db, s.store, s.fake, T, { warn: () => {}, info: () => {} })
+ expect(s.read).toEqual(['latest backend', 'contains m8 b', 'done'])
+ expect(s.settled[0]!.facts.releases.backend).toMatchObject({ tag: 'v1.4.17_backend', carries: [pendingKey(entry)], compared: [pendingKey(entry)] })
+ // Compared and not carried, it is not compared with that release again.
+ const no = scene({ pending: [{ ...entry, checked: { backend: 'v1.4.17_backend' } }], last: { backend: { tag: 'v1.4.17_backend', sha: 'b', at: T } } })
+ await watchReleases(no.db, no.store, no.fake, T, { warn: () => {}, info: () => {} })
+ expect(no.read).toEqual(['latest backend', 'done'])
+ // A newer tag is compared with it again.
+ const newer = scene({ pending: [{ ...entry, checked: { backend: 'v1.4.16_backend' } }], last: { backend: { tag: 'v1.4.16_backend', sha: 'a', at: T - 1 } } })
+ await watchReleases(newer.db, newer.store, newer.fake, T, { warn: () => {}, info: () => {} })
+ expect(newer.read).toContain('contains m8 b')
+ })
+
+ it('looks for every merge commit on the first pass after a start, whatever the lookup schedule says', async () => {
+ const old = { groupId: 'g2', url: 'https://github.com/acme/app/pull/8', mergedAt: T - 3 * 86_400_000, components: ['backend' as const] }
+ const at = T + 17 * 60_000 // not a pass the schedule looks on for a merge three days old
+ const idle = scene({ pending: [old] })
+ await watchReleases(idle.db, idle.store, idle.fake, at, { warn: () => {}, info: () => {} })
+ expect(idle.read).not.toContain('merge 8')
+ const first = scene({ pending: [old] })
+ await watchReleases(first.db, first.store, first.fake, at, { warn: () => {}, info: () => {} }, undefined, true)
+ expect(first.read).toContain('merge 8')
})
// Review 2 of #3228: a merge commit found in a pass whose comparison GitHub could not answer is found again, so the tag
diff --git a/backend/src/superTabs/releaseWatch.ts b/backend/src/superTabs/releaseWatch.ts
index e4b420a51..1522f6796 100644
--- a/backend/src/superTabs/releaseWatch.ts
+++ b/backend/src/superTabs/releaseWatch.ts
@@ -46,8 +46,10 @@ const BATCH_BEFORE_MS = 6 * 3_600_000, BATCH_AFTER_MS = 3_600_000, COMMIT_PAGES
const BATCH_TITLE = /^Merge batch [^:\n]*:((?:\s+#\d+)+)\s+\(#\d+\)\s*$/
/** Whether the pass looks for [mergedAt]'s merge commit at [now]: every pass for an hour, then every 30 minutes, and after a
- * day every 2 hours, so a batch never found costs a few reads an hour rather than five pages every 5 minutes for 14 days. */
-export function batchLookupDue(mergedAt: number, now: number): boolean {
+ * day every 2 hours, so a batch never found costs a few reads an hour rather than five pages every 5 minutes for 14 days.
+ * [first]: the first pass after a start looks for every one (task #3586), so merges already waiting are settled at once. */
+export function batchLookupDue(mergedAt: number, now: number, first = false): boolean {
+ if (first) return true
const age = now - mergedAt, PASS = 5 * 60_000
return age < 3_600_000 || now % (age < 86_400_000 ? 30 * 60_000 : 2 * 3_600_000) < PASS
}
@@ -99,6 +101,19 @@ export function readReleases(get: GitHubGet): Omit<ReleaseReader, 'done'> {
}
path = answer.next
}
+ if (found) return found
+ // A merge recorded long after its batch landed (a release cut before releases were recorded, task #3586) is outside the
+ // window of the time it was recorded: main's newest commits are read, newest first, so the last one naming it is the oldest.
+ path = `/repos/${repository.fullName}/commits?sha=${encodeURIComponent(main)}&per_page=100`
+ for (let page = 0; path && page < COMMIT_PAGES; page++) {
+ const answer = await get(repository, path)
+ if (answer.status !== 200 || !Array.isArray(answer.body)) return null
+ for (const commit of answer.body as Array<{ sha?: unknown; commit?: { message?: unknown } }>) {
+ if (typeof commit.sha === 'string' && typeof commit.commit?.message === 'string' && names(commit.commit.message)) found = commit.sha
+ }
+ if (found) break
+ path = answer.next
+ }
return found
},
async contains(repository, base, head) {
@@ -173,7 +188,7 @@ type Log = Pick<typeof logger, 'warn' | 'info'>
* it could not read is logged and skipped; the others go on. The projects settled.
*/
export async function watchReleases(db: PrismaClient, store: Pick<SuperTabStore, 'settleReleases'>, reader: ReleaseReader, now: number,
- log: Log = logger, candidates: () => Promise<Map<string, string[]>> = () => reflectionCandidates(db, now, log)): Promise<number> {
+ log: Log = logger, candidates: () => Promise<Map<string, string[]>> = () => reflectionCandidates(db, now, log), first = false): Promise<number> {
let settled = 0
try {
for (const [tabId, projectIds] of await candidates()) {
@@ -199,7 +214,7 @@ export async function watchReleases(db: PrismaClient, store: Pick<SuperTabStore,
const files = number ? await reader.files(repository, number) : null
if (files) known.components = found.components = componentsOf(files)
}
- if (known.components?.length && !known.sha && batchLookupDue(entry.mergedAt, now)) {
+ if (known.components?.length && !known.sha && batchLookupDue(entry.mergedAt, now, first)) {
const sha = number ? await reader.mergeCommit(repository, number, entry.mergedAt) : null
if (sha) { known.sha = found.sha = sha; fresh.add(pendingKey(entry)) }
}
@@ -216,14 +231,18 @@ export async function watchReleases(db: PrismaClient, store: Pick<SuperTabStore,
// A new tag is compared with every merge waiting for it; the tag already settled only with merges resolved since.
const carries: string[] = []
let unsure = false
+ const compared: string[] = []
+ // Each waiting merge is compared once with each release, whenever the release was cut (task #3586); a release cut
+ // before the merge was recorded holds it all the same.
for (const entry of entries.filter(e => e.sha && e.components?.includes(component.id) && !e.shippedIn?.[component.id]
- && (release.tag !== last?.tag || fresh.has(pendingKey(e))))) {
+ && e.checked?.[component.id] !== release.tag)) {
const inside = await reader.contains(repository, entry.sha!, release.sha)
if (inside === null) { unsure = true; break }
+ compared.push(pendingKey(entry))
if (inside) carries.push(pendingKey(entry))
}
if (unsure) unknown.push(component.id)
- else facts.releases[component.id] = { ...release, carries }
+ else facts.releases[component.id] = { ...release, carries, compared }
}
// A merge commit found this pass is kept only when every release it waits for was compared with it: one kept after an
// unsure comparison is no longer new next pass, so the tag already settled would never be compared with it.
@@ -260,7 +279,7 @@ export const CANDIDATES_MS = 60 * 60_000
/** Runs the release watch every 5 minutes in the singleton worker. */
export function startReleaseWatch(db: PrismaClient, store: Pick<SuperTabStore, 'settleReleases'>, reader: () => ReleaseReader, everyMs = 5 * 60_000): () => void {
- let running = false
+ let running = false, first = true
let kept: { at: number; value: Map<string, string[]> } | null = null
const candidates = async (now: number) => {
if (!kept || now - kept.at >= CANDIDATES_MS) kept = { at: now, value: await reflectionCandidates(db, now) }
@@ -270,7 +289,9 @@ export function startReleaseWatch(db: PrismaClient, store: Pick<SuperTabStore, '
if (running) return
running = true
const now = Date.now()
- void watchReleases(db, store, reader(), now, logger, () => candidates(now))
+ const start = first
+ first = false
+ void watchReleases(db, store, reader(), now, logger, () => candidates(now), start)
.catch(error => logger.warn('[swarm-releases] pass failed', { error: error instanceof Error ? error.message : String(error) }))
.finally(() => { running = false })
}
diff --git a/backend/src/superTabs/releases.test.ts b/backend/src/superTabs/releases.test.ts
index b8db637a8..877430ee1 100644
--- a/backend/src/superTabs/releases.test.ts
+++ b/backend/src/superTabs/releases.test.ts
@@ -195,6 +195,16 @@ describe('settleReleases', () => {
expect(state.conversations.find(c => c.id === 'g12')!.released).toBeUndefined()
})
+ // Task #3586: a merge compared with a release and not carried is not compared with it again; the next release that holds it ships it.
+ it('marks a merge compared with a release that does not hold it, and ships it with the release that does', () => {
+ const state = swarm([entry({ groupId: 'g12', mergedAt: T - 5 * MINUTE, components: ['desktop'], sha: 'm12' })])
+ settleReleases(state, 'p1', { resolved: [], releases: { desktop: { ...desktopRelease([]), compared: [key12] } } }, T)
+ expect(ledgerOf(state).pending[0]!.checked).toEqual({ desktop: 'v1.3.78_desktop' })
+ const later = settleReleases(state, 'p1', { resolved: [], releases: { desktop: { ...desktopRelease([key12], 'v1.3.79_desktop'), compared: [key12] } } }, T + MINUTE)
+ expect(later.shipped).toEqual(['g12'])
+ expect(state.conversations.find(c => c.id === 'g12')!.released).toMatchObject({ tags: ['v1.3.79_desktop'] })
+ })
+
it('ships work that changed no released part at its merge', () => {
const state = swarm([entry({ groupId: 'g13', url: 'https://github.com/o/r/pull/13', mergedAt: T - MINUTE, components: undefined })])
state.conversations.find(c => c.id === 'g13')!.releasing = []
diff --git a/backend/src/superTabs/releases.ts b/backend/src/superTabs/releases.ts
index 045ab2f31..6650fbb88 100644
--- a/backend/src/superTabs/releases.ts
+++ b/backend/src/superTabs/releases.ts
@@ -60,7 +60,10 @@ export const backendPaused = (rules: ReleaseRules, now: number): boolean =>
* request's files, and `sha` until it found the merge's commit on main (its own merge commit, or the batch's that closed
* it); `shippedIn` names, per component, the verified release that carries it. */
export interface PendingRelease { groupId: string; url: string; mergedAt: number; components?: ReleaseComponentId[]; sha?: string
- shippedIn?: Partial<Record<ReleaseComponentId, string>> }
+ shippedIn?: Partial<Record<ReleaseComponentId, string>>
+ /** Per component, the newest verified release this merge was compared with and found not in it (task #3586): it is compared
+ * once with each release, so one cut before the merge was recorded still ships it, and one that does not hold it is not read again. */
+ checked?: Partial<Record<ReleaseComponentId, string>> }
/** A component's newest verified release: its tag, the tag's commit, and when its release ran (the pace counts from it). */
export interface VerifiedRelease { tag: string; sha: string; at: number }
@@ -146,7 +149,7 @@ export interface ReleaseFacts {
resolved: Array<{ groupId: string; url: string; components?: ReleaseComponentId[]; sha?: string }>
/** Each component's newest verified release on main, with the entries whose merge commits GitHub says its tag contains
* (pendingKey). A component GitHub could not read or compare is absent, and nothing of it changes. */
- releases: Partial<Record<ReleaseComponentId, VerifiedRelease & { carries: string[] }>>
+ releases: Partial<Record<ReleaseComponentId, VerifiedRelease & { carries: string[]; compared?: string[] }>>
}
/** What a settle did: rows to write, the tasks it marked released, the release step it opened, the entries it dropped. */
export interface SettledReleases { messages: MessageDraft[]; shipped: string[]; opened: string | null; dropped: PendingRelease[] }
@@ -197,9 +200,11 @@ export function settleReleases(state: SuperTabState, projectId: string, facts: R
// A re-run of an older tag's workflow is no newer release; the same tag read again only carries merges resolved since.
const order = read && known ? compareTags(read.tag, known.tag) : 1
if (!read || order < 0) continue
- const { carries: keys, ...release } = read
+ const { carries: keys, compared, ...release } = read
const carried = waitingFor(ledger, component.id).filter(e => keys.includes(pendingKey(e)))
for (const entry of carried) (entry.shippedIn ??= {})[component.id] = release.tag
+ // Compared and not held: not compared with this release again (task #3586).
+ for (const entry of waitingFor(ledger, component.id)) if (compared?.includes(pendingKey(entry)) && !keys.includes(pendingKey(entry))) (entry.checked ??= {})[component.id] = release.tag
if (order === 0) continue
;(ledger.last ??= {})[component.id] = release
const step = ledger.steps?.[component.id]
diff --git a/backend/src/superTabs/removedRefusals.test.ts b/backend/src/superTabs/removedRefusals.test.ts
index a5bf35ef5..c112c9d89 100644
--- a/backend/src/superTabs/removedRefusals.test.ts
+++ b/backend/src/superTabs/removedRefusals.test.ts
@@ -3,16 +3,23 @@ import { join, relative } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
-// Project instructions, phase 4 is done when no refusal the instructions replaced is reachable: the server refuses only facts
-// and access (design, "What the server still enforces"). ENGINE_UNAVAILABLE stays for signed-out and suspended engines.
-const REMOVED = ['WORKER_DECISION_REQUIRED', 'LEAD_REQUIRED', 'REVIEW_OPEN', 'REVIEW_PENDING', 'REVIEW_TARGET', 'CHECKS_PENDING',
- 'BRIEF_REQUIRED', 'INDEPENDENT_REVIEW', 'REVIEWER_NOT_ASSIGNABLE', 'REVIEW_GROUP', 'REVIEWER_NOT_LEAD', 'ROLE_LEAD', 'ROLE_NAME',
- 'ROLE_UNAVAILABLE', 'ROLE_KIND', 'ROLE_IN_USE', 'ROLE_GONE', 'OVERRIDE_REASON_REQUIRED', 'ROUTE_REQUIRED', 'RULE_BROKEN',
- 'REQUIREMENT_UNMET', 'REVIEW_REFUSED', 'STEPPED_UP', 'BUILD_REFUSED', 'MERGE_RECORDER', 'TELL_FORBIDDEN', 'DECISION_FORBIDDEN',
- 'MENTION_FORBIDDEN', 'OWNER_MESSAGE_REQUIRED', 'WORK_REQUIRED', 'REVIEW_SHIPS_NOTHING']
+// Dee, 2026-11-06: checkable rules belong in code. Phase 4's facts/access-only ban is superseded;
+// rule refusals may use their plain names. Only the retired custom role registry must stay gone.
+const REMOVED = {
+ ROLE_KIND: 'Roles are free-text names; the removed registry must not impose a fixed kind enum.',
+ ROLE_UNAVAILABLE: 'A role name does not need an entry in the removed custom role registry.',
+ ROLE_IN_USE: 'There is no custom role record whose deletion must wait for agents using it.',
+ ROLE_GONE: 'A start must not depend on a custom role record surviving in the retired registry.',
+}
const SRC = join(fileURLToPath(new URL('.', import.meta.url)), '..')
+const quoted = (code: string) => new RegExp(`['"\`]${code}['"\`]`)
+
+function removedRefusals(text: string): string[] {
+ return Object.keys(REMOVED).filter(code => quoted(code).test(text))
+}
+
/** Every TypeScript source file under backend/src, tests left out. */
function sources(dir: string): string[] {
return readdirSync(dir).flatMap(name => {
@@ -22,15 +29,33 @@ function sources(dir: string): string[] {
})
}
-describe('the refusals project instructions removed', () => {
- it('reaches none of the refusals the instructions replaced', () => {
+describe('retired role-registry refusals', () => {
+ it.each(['\'', '"', '`'])('allows plain rule refusal codes in %s quotes', quote => {
+ const codes = ['WORKER_DECISION_REQUIRED', 'LEAD_REQUIRED', 'REVIEW_OPEN', 'REVIEW_PENDING', 'REVIEW_TARGET',
+ 'CHECKS_PENDING', 'BRIEF_REQUIRED', 'INDEPENDENT_REVIEW', 'REVIEWER_NOT_ASSIGNABLE', 'REVIEW_GROUP',
+ 'REVIEWER_NOT_LEAD', 'ROLE_LEAD', 'ROLE_NAME', 'OVERRIDE_REASON_REQUIRED', 'ROUTE_REQUIRED', 'RULE_BROKEN',
+ 'REQUIREMENT_UNMET', 'REVIEW_REFUSED', 'STEPPED_UP', 'BUILD_REFUSED', 'MERGE_RECORDER', 'TELL_FORBIDDEN',
+ 'DECISION_FORBIDDEN', 'MENTION_FORBIDDEN', 'OWNER_MESSAGE_REQUIRED', 'WORK_REQUIRED', 'REVIEW_SHIPS_NOTHING']
+ expect(removedRefusals(codes.map(code => `throw new Error(${quote}${code}${quote})`).join('\n'))).toEqual([])
+ })
+
+ it.each(['ROLE_KIND', 'ROLE_UNAVAILABLE', 'ROLE_IN_USE', 'ROLE_GONE'])('still detects the retired registry code %s', code => {
+ for (const quote of ['\'', '"', '`']) {
+ expect(removedRefusals(`throw new Error(${quote}${code}${quote})`)).toEqual([code])
+ }
+ })
+
+ it('keeps a reason for each banned code', () => {
+ for (const reason of Object.values(REMOVED)) expect(reason.trim()).not.toBe('')
+ })
+
+ it('reaches none of the retired registry refusals', () => {
const files = sources(SRC)
// The walk itself is checked: it reads the command handlers, where these codes were thrown.
expect(files.map(f => relative(SRC, f))).toEqual(expect.arrayContaining(['superTabs/commands.ts', 'superTabs/store.ts', 'routes/superTabs.ts']))
- const quoted = (code: string) => new RegExp(`['"\`]${code}['"\`]`)
const found = files.flatMap(file => {
const text = readFileSync(file, 'utf8')
- return REMOVED.filter(code => quoted(code).test(text)).map(code => `${code} in ${relative(SRC, file)}`)
+ return removedRefusals(text).map(code => `${code} in ${relative(SRC, file)}`)
})
expect(found).toEqual([])
// The same search finds refusals that stay: settings and who coordinates stay the coordinator's or a person's.
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index c37bc54da..ce8edc288 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -5944,6 +5944,22 @@ class AppNotifier extends ChangeNotifier {
FileSystemEntityType.notFound;
};
+ /// Whether the CLI's own sign-in file is on this computer (task #3561). Looked at, never read: this app holds no
+ /// token. `harness logout` deletes it, so a sign-out in a terminal while the app was closed waits for the signed-in
+ /// check as before. Product installs keep it at `~/.harness/auth/session.json`; tests answer no.
+ @visibleForTesting
+ bool Function() cliSessionOnDisk = kUnderTest
+ ? () => false
+ : () {
+ final home = maybeHomeDir();
+ if (home == null) return false;
+ final sep = Platform.pathSeparator;
+ return FileSystemEntity.typeSync(
+ '$home$sep.harness${sep}auth${sep}session.json',
+ ) ==
+ FileSystemEntityType.file;
+ };
+
TerminalPane? get focusedPane {
final id = focusedPaneId;
if (id == null) return null;
@@ -7534,6 +7550,7 @@ class AppNotifier extends ChangeNotifier {
/// load and update-check startup, which already ran on the launch that got stuck here.
Future<void> _continueAfterEnvironmentReady({
Future<CliAuthStatus?>? early,
+ bool fromKept = true,
}) async {
agentPrefetch?.setupRunning = false;
final revision = _authRevision;
@@ -7550,6 +7567,11 @@ class AppNotifier extends ChangeNotifier {
// refreshes it itself. This app never reads, stores, or refreshes a token of its own; it just
// asks the CLI whether this computer is currently signed in.
try {
+ if (early != null &&
+ fromKept &&
+ await _openFromKeptSignIn(early, revision)) {
+ return;
+ }
final authStatus = await early ?? await cliLogin.checkStatus();
_markStartup('signed-in check');
if (!_authWorkCurrent(revision)) return;
@@ -7588,6 +7610,98 @@ class AppNotifier extends ChangeNotifier {
}
}
+ /// Opens the window as the account this computer was last proven signed in as, while `harness auth status` still
+ /// runs (task #3561: 245 ms of a launch, a Node start). What is stored is the kept profile ([ProfileCache]): written
+ /// only once the CLI named its machine and the server named the account, and cleared by every sign-out this app sees
+ /// and every signed-out launch. With none kept, or no CLI sign-in file, the launch waits for the check as before.
+ /// Whatever the check then says, [_confirmKeptSignIn] ends the launch where a launch that waited would have ended.
+ Future<bool> _openFromKeptSignIn(
+ Future<CliAuthStatus?> check,
+ int revision,
+ ) async {
+ if (viewer != null || !cliSessionOnDisk()) return false;
+ final kept = await _profileCache.readKept();
+ if (kept == null || !_authWorkCurrent(revision)) return false;
+ signedIn = true;
+ // Shown, not proven: nothing is kept and no picture is claimed under it until the check names this machine.
+ _provenMachineId = null;
+ _keptProfileId = kept.profile.id;
+ _profileConfirmed = false;
+ currentUser = kept.profile;
+ status = AppStatus.bootstrapping;
+ notifyListeners();
+ _launchProof = (revision: revision, settled: Completer<void>());
+ unawaited(_confirmKeptSignIn(check, kept.machineId, revision));
+ await _finishBootstrapSignedIn();
+ unawaited(_offerPhoneAtLaunch(revision));
+ return true;
+ }
+
+ /// Settles once the check behind a window [_openFromKeptSignIn] opened has answered. Until then the window shows only
+ /// this computer's restored desk: the account's work (its profile, devices, machine list and desk) waits for it, since
+ /// the CLI may be signed in as someone else and that work would run through their session (review of #3293).
+ ({int revision, Completer<void> settled})? _launchProof;
+ bool _layoutSaveHeld = false;
+
+ /// The signed-in check behind a window [_openFromKeptSignIn] opened. The same machine: proven, as
+ /// [_useKeptProfile] would have proven it. Signed out: the sign-in page, as when a sign-out elsewhere is noticed.
+ /// Another account, or no answer: the launch starts again from the CLI's answer, as one with nothing kept does.
+ Future<void> _confirmKeptSignIn(
+ Future<CliAuthStatus?> check,
+ String keptMachineId,
+ int revision,
+ ) async {
+ CliAuthStatus? answer;
+ try {
+ answer = await check ?? await cliLogin.checkStatus();
+ } catch (error) {
+ debugPrint('bootstrap: signed-in check failed behind the window: $error');
+ }
+ _markStartup('signed-in check');
+ // Each branch below decides synchronously, so the account work waiting on this resumes under its outcome: proven,
+ // or invalidated.
+ final proof = _launchProof;
+ final held = _layoutSaveHeld;
+ if (proof != null && proof.revision == revision) {
+ _launchProof = null;
+ _layoutSaveHeld = false;
+ proof.settled.complete();
+ }
+ if (!_authWorkCurrent(revision)) return;
+ if (answer != null &&
+ answer.loggedIn &&
+ answer.machineId == keptMachineId) {
+ _provenMachineId = keptMachineId;
+ unawaited(superTabImageCache.claim(keptMachineId));
+ if (held) _persistLayout();
+ return;
+ }
+ if (answer != null && !answer.loggedIn) {
+ _signedOutAtRuntime(_signedOutMessage);
+ return;
+ }
+ final again = _invalidateAuthWork();
+ currentUser = null;
+ _provenMachineId = null;
+ _keptProfileId = null;
+ _profileConfirmed = false;
+ _clearAccountWorkspace();
+ status = AppStatus.checkingEnvironment;
+ notifyListeners();
+ // Gone before the launch starts again, so it cannot open from it a second time.
+ await _profileCache.clear();
+ if (!_authWorkCurrent(again)) return;
+ if (_workspaceCleanup case final cleanup?) {
+ await cleanup;
+ if (!_authWorkCurrent(again)) return;
+ }
+ // Never from the kept record again: a delete that failed leaves it readable (review of #3293).
+ await _continueAfterEnvironmentReady(
+ early: answer == null ? null : Future.value(answer),
+ fromKept: false,
+ );
+ }
+
void showEnvironmentReview() {
environmentReadiness = environmentReadiness.copyWith(
phase: EnvironmentSetupPhase.review,
@@ -7866,6 +7980,12 @@ class AppNotifier extends ChangeNotifier {
appLog.info('startup', startupLogLine(_startupTimings));
_startupClock.stop();
notifyListeners();
+ // A window opened from the kept sign-in asks nothing of the account until the check proves it ([_launchProof]).
+ final proof = _launchProof;
+ if (proof != null && proof.revision == revision) {
+ await proof.settled.future;
+ if (!_authWorkCurrent(revision)) return;
+ }
// The CLI has confirmed daemon readiness. Display-name/avatar metadata is
// independent of machine discovery and must not delay work — and a guest
// has no profile to load.
@@ -22245,6 +22365,12 @@ class AppNotifier extends ChangeNotifier {
_announceVisibleAgents();
_freezeDeskLayouts();
_deskQueueDiff();
+ // Saved with an owner, so never under an account the signed-in check has not proven yet ([_launchProof]): held, and
+ // saved once it is (review of #3293).
+ if (_launchProof != null) {
+ _layoutSaveHeld = true;
+ return;
+ }
final saved = swarms.where((swarm) => !isDraftSwarm(swarm.id)).toList();
if (saved.isEmpty) return;
final savedActive = isDraftSwarm(activeSwarmId)
diff --git a/desktop/lib/state/profile_cache.dart b/desktop/lib/state/profile_cache.dart
index 90b05c74e..40d5ff9ca 100644
--- a/desktop/lib/state/profile_cache.dart
+++ b/desktop/lib/state/profile_cache.dart
@@ -14,28 +14,40 @@ class ProfileCache {
static const key = 'signed_in_profile_v1';
Future<CurrentUserProfile?> read(String machineId) async {
+ final kept = await readKept();
+ return kept == null || kept.machineId != machineId ? null : kept.profile;
+ }
+
+ /// The record with the machine id it was proven under, before the CLI has named one: what a launch opens as while
+ /// `harness auth status` still runs (task #3561). Only that answer proves it, as [read] does.
+ Future<({String machineId, CurrentUserProfile profile})?> readKept() async {
final storage = _storage;
if (storage == null) return null;
try {
final stored = await storage.read(key);
if (stored == null) return null;
final value = jsonDecode(stored);
- if (value is! Map || value['machineId'] != machineId) return null;
- final (id, email, name, avatar) = (
+ if (value is! Map) return null;
+ final (machineId, id, email, name, avatar) = (
+ value['machineId'],
value['id'],
value['email'],
value['name'],
value['avatarUrl'],
);
+ if (machineId is! String || machineId.isEmpty) return null;
if (id is! String || id.isEmpty || email is! String || email.isEmpty) {
return null;
}
if (name is! String? || avatar is! String?) return null;
- return CurrentUserProfile(
- id: id,
- email: email,
- name: name,
- avatarUrl: avatar,
+ return (
+ machineId: machineId,
+ profile: CurrentUserProfile(
+ id: id,
+ email: email,
+ name: name,
+ avatarUrl: avatar,
+ ),
);
} catch (_) {
return null;
@@ -71,7 +83,8 @@ class ProfileCache {
try {
await _storage?.delete(key);
} catch (_) {
- /* A record left behind is read only under its own machine id. */
+ /* A record left behind is read only under its own machine id, or by [readKept] for a launch that waits for the CLI
+ to name that id before it trusts it, and that never opens from it twice (task #3561). */
}
});
}
diff --git a/desktop/test/kept_sign_in_launch_test.dart b/desktop/test/kept_sign_in_launch_test.dart
new file mode 100644
index 000000000..0f7b38421
--- /dev/null
+++ b/desktop/test/kept_sign_in_launch_test.dart
@@ -0,0 +1,441 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/api/api_client.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/auth/cli_login.dart';
+import 'package:harness/auth/sign_in_provider.dart';
+import 'package:harness/bootstrap/environment_provisioner.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/local_key_value_store.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/logging/app_log.dart';
+import 'package:harness/measurement/speed_marks.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/pane_layout_store.dart';
+import 'package:harness/state/profile_cache.dart';
+import 'package:harness/ws/local_cli_discovery.dart';
+
+// Task #3561: the signed-in check (`harness auth status`, ~245 ms on a release build) no longer holds up the window.
+// A launch with a kept sign-in opens as that account and the check finishes behind it; whatever the check says then,
+// the launch ends where it would have ended had it waited. A memory store and a fake sign-in: nothing here runs the
+// real CLI.
+
+class _Memory implements LocalKeyValueStore {
+ final values = <String, String>{};
+ @override
+ Future<String?> read(String key) async => values[key];
+ @override
+ Future<void> write(String key, String value) async => values[key] = value;
+ @override
+ Future<void> delete(String key) async => values.remove(key);
+}
+
+class _Api extends ApiClient {
+ _Api() : super(config: AppConfig.dev, session: AuthSession());
+ final profiles = <Completer<Map<String, dynamic>?>>[];
+ int desks = 0, lists = 0;
+ @override
+ Future<Map<String, dynamic>?> desk() async {
+ desks++;
+ return null;
+ }
+
+ @override
+ Future<Map<String, dynamic>?> me() {
+ final answer = Completer<Map<String, dynamic>?>();
+ profiles.add(answer);
+ return answer.future;
+ }
+
+ @override
+ Future<List<Machine>> machines() async {
+ lists++;
+ return const [];
+ }
+}
+
+/// `harness auth status`, held until the test answers it.
+class _Cli extends CliLogin {
+ final answer = Completer<CliAuthStatus>();
+ bool fails = false;
+ int asked = 0;
+ @override
+ Future<CliAuthStatus> checkStatus() async {
+ asked++;
+ if (fails) throw CliNotAvailableException('no CLI');
+ return answer.future;
+ }
+
+ @override
+ Future<void> login({
+ void Function(String url)? onAuthorizeUrl,
+ SignInProvider? provider,
+ }) async {}
+ @override
+ Future<void> logout() async {}
+}
+
+class _Environment extends EnvironmentProvisioner {
+ @override
+ Future<EnvironmentReadiness> ensureReady({
+ required void Function(EnvironmentReadiness value) onProgress,
+ EnvironmentReadiness? resumeFrom,
+ bool install = true,
+ EnvironmentSetupMode? mode,
+ }) async {
+ final ready = EnvironmentReadiness(
+ steps: {
+ for (final step in EnvironmentStep.values)
+ step: EnvironmentStepStatus.ready,
+ },
+ phase: EnvironmentSetupPhase.ready,
+ );
+ onProgress(ready);
+ return ready;
+ }
+}
+
+class _Discovery extends LocalCliDiscovery {
+ _Discovery() : super(config: AppConfig.dev);
+ @override
+ Future<String?> computerId() async => null;
+ @override
+ Future<LocalCliEndpoint?> discover({String? expectedComputerId}) async =>
+ null;
+}
+
+class _App extends AppNotifier {
+ _App(_Cli cli, LocalKeyValueStore storage)
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ cliLogin: cli,
+ environmentProvisioner: _Environment(),
+ localCliDiscovery: _Discovery(),
+ paneLayoutStore: PaneLayoutStore(storage: storage),
+ );
+ Completer<void>? daemon;
+ @override
+ Future<void> ensureCliDaemonReady() async {
+ await daemon?.future;
+ }
+}
+
+class _Speed implements AppLog {
+ _Speed(this.lines);
+ final List<String> lines;
+ @override
+ void record(
+ AppLogLevel level,
+ String category,
+ String message, {
+ Object? error,
+ StackTrace? stackTrace,
+ }) {
+ if (category == 'speed') lines.add(message);
+ }
+}
+
+Future<void> _ticks() async {
+ for (var i = 0; i < 30; i++) {
+ await Future<void>.delayed(Duration.zero);
+ }
+}
+
+const _ada = CurrentUserProfile(
+ id: 'ada',
+ email: '[email protected]',
+ name: 'Ada',
+);
+
+Map<String, dynamic> _me(String id, String name) => {
+ 'user': {'id': id, 'email': '[email protected]', 'name': name},
+};
+
+/// What RootShell shows: the sign-in page, the workspace, or neither yet.
+String _screen(AppNotifier app) {
+ if (app.status == AppStatus.unauthenticated) return 'login';
+ if (app.status != AppStatus.authenticated) return 'starting';
+ return app.signInStepShowing ? 'sign-in' : 'workspace';
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late _Memory storage;
+ late _Cli cli;
+ late _Api api;
+ late _App app;
+
+ setUp(() {
+ storage = _Memory();
+ cli = _Cli();
+ api = _Api();
+ app = _App(cli, storage)..api = api;
+ // The CLI's sign-in file is on this computer.
+ app.cliSessionOnDisk = () => true;
+ });
+ tearDown(() => app.dispose());
+
+ Future<void> keptFrom(String machine) =>
+ ProfileCache(storage).write(machine, _ada);
+
+ test(
+ 'signed in: opens on the workspace as the kept account before the check answers',
+ () async {
+ await keptFrom('machine-a');
+ final before = appLog;
+ final speed = <String>[];
+ appLog = _Speed(speed);
+ addTearDown(() => appLog = before);
+ speedMarks.restart();
+
+ final boot = app.bootstrap();
+ await _ticks();
+ expect(cli.answer.isCompleted, isFalse);
+ expect(_screen(app), 'workspace');
+ expect(app.signedIn, isTrue);
+ expect(app.currentUser?.id, 'ada');
+
+ cli.answer.complete(
+ const CliAuthStatus(loggedIn: true, machineId: 'machine-a'),
+ );
+ await boot;
+ await _ticks();
+ expect(_screen(app), 'workspace');
+ expect(app.currentUser?.id, 'ada');
+ expect(await ProfileCache(storage).read('machine-a'), isNotNull);
+
+ final steps = [
+ for (final line in speed)
+ RegExp(r'^launch step=(\S+)').firstMatch(line)?.group(1),
+ ];
+ expect(steps, containsAll(['window', 'signed-in_check']));
+ expect(
+ steps.indexOf('window'),
+ lessThan(steps.indexOf('signed-in_check')),
+ reason: 'the window no longer waits for the signed-in check',
+ );
+ },
+ );
+
+ test(
+ 'signed out, nothing kept: waits for the check and lands on the sign-in page',
+ () async {
+ final boot = app.bootstrap();
+ await _ticks();
+ expect(_screen(app), 'starting');
+ cli.answer.complete(const CliAuthStatus(loggedIn: false));
+ await boot;
+ await _ticks();
+ expect(_screen(app), 'sign-in');
+ expect(app.signedIn, isFalse);
+ expect(app.currentUser, isNull);
+ },
+ );
+
+ test(
+ 'a kept profile but no CLI sign-in file (signed out in a terminal) waits for the check',
+ () async {
+ await keptFrom('machine-a');
+ app.cliSessionOnDisk = () => false;
+ final boot = app.bootstrap();
+ await _ticks();
+ expect(_screen(app), 'starting');
+ expect(app.currentUser, isNull);
+ cli.answer.complete(const CliAuthStatus(loggedIn: false));
+ await boot;
+ await _ticks();
+ expect(_screen(app), 'sign-in');
+ expect(storage.values, isNot(contains(ProfileCache.key)));
+ },
+ );
+
+ test(
+ 'kept, but the check says signed out: ends on the sign-in page, nobody shown, nothing kept',
+ () async {
+ await keptFrom('machine-a');
+ unawaited(app.bootstrap());
+ await _ticks();
+ expect(_screen(app), 'workspace');
+ cli.answer.complete(const CliAuthStatus(loggedIn: false));
+ await _ticks();
+ expect(_screen(app), 'sign-in');
+ expect(app.signedIn, isFalse);
+ expect(app.currentUser, isNull);
+ expect(storage.values, isNot(contains(ProfileCache.key)));
+ },
+ );
+
+ test(
+ 'kept, and the check says signed out before the window opens: still ends on the sign-in page',
+ () async {
+ await keptFrom('machine-a');
+ app.daemon = Completer<void>();
+ final boot = app.bootstrap();
+ await _ticks();
+ expect(_screen(app), 'starting');
+ cli.answer.complete(const CliAuthStatus(loggedIn: false));
+ await _ticks();
+ app.daemon!.complete();
+ await boot;
+ await _ticks();
+ expect(_screen(app), 'sign-in');
+ expect(app.signedIn, isFalse);
+ expect(app.currentUser, isNull);
+ },
+ );
+
+ test(
+ 'kept, but the check names another machine: signed in, nobody shown until the server answers, the old record gone',
+ () async {
+ await keptFrom('machine-a');
+ unawaited(app.bootstrap());
+ await _ticks();
+ final first = api.profiles.toList();
+ cli.answer.complete(
+ const CliAuthStatus(loggedIn: true, machineId: 'machine-b'),
+ );
+ await _ticks();
+ expect(_screen(app), 'workspace');
+ expect(app.signedIn, isTrue);
+ expect(app.currentUser, isNull);
+ expect(storage.values, isNot(contains(ProfileCache.key)));
+ // What the server said to the launch that opened as the kept account is not this one's.
+ for (final answer in first) {
+ answer.complete(_me('ada', 'Ada'));
+ }
+ await _ticks();
+ expect(app.currentUser?.id, isNot('ada'));
+ },
+ );
+
+ test(
+ 'kept, but the CLI cannot answer: ends on the login screen, as a launch that waited does',
+ () async {
+ await keptFrom('machine-a');
+ cli.fails = true;
+ await app.bootstrap();
+ await _ticks();
+ expect(_screen(app), 'login');
+ expect(app.currentUser, isNull);
+ },
+ );
+
+ test(
+ 'nothing of the account is asked before the check proves it: the CLI may be signed in as someone else (review of #3293)',
+ () async {
+ await keptFrom('machine-a');
+ unawaited(app.bootstrap());
+ await _ticks();
+ expect(_screen(app), 'workspace');
+ expect(api.lists, 0, reason: 'no machine list');
+ expect(api.desks, 0, reason: 'no desk joined or seeded');
+ expect(api.profiles, isEmpty, reason: 'no profile asked');
+ cli.answer.complete(
+ const CliAuthStatus(loggedIn: true, machineId: 'machine-b'),
+ );
+ await _ticks();
+ // Only the launch that started again from the CLI's answer reads them, as a launch with nothing kept does.
+ expect(app.currentUser, isNull);
+ expect(storage.values, isNot(contains(ProfileCache.key)));
+ },
+ );
+
+ test(
+ 'once the check proves the machine, the account work runs and the server\'s answer is kept',
+ () async {
+ await keptFrom('machine-a');
+ unawaited(app.bootstrap());
+ await _ticks();
+ expect(api.profiles, isEmpty);
+ cli.answer.complete(
+ const CliAuthStatus(loggedIn: true, machineId: 'machine-a'),
+ );
+ await _ticks();
+ expect(api.lists, greaterThan(0));
+ api.profiles.last.complete(_me('ada', 'Ada Two'));
+ await _ticks();
+ expect(app.currentUser?.name, 'Ada Two');
+ final kept =
+ jsonDecode(storage.values[ProfileCache.key]!) as Map<String, dynamic>;
+ expect(kept['name'], 'Ada Two');
+ expect(kept['machineId'], 'machine-a');
+ },
+ );
+
+ test(
+ 'a layout change before the check proves the machine is saved only once it does (review of #3293)',
+ () async {
+ await keptFrom('machine-a');
+ unawaited(app.bootstrap());
+ await _ticks();
+ expect(app.swarms, isNotEmpty);
+ final before = storage.values['swarm_layout_v1'];
+ app.renameSwarm(app.swarms.first.id, 'Renamed early');
+ await _ticks();
+ expect(
+ storage.values['swarm_layout_v1'],
+ before,
+ reason: 'nothing saved under an account not proven yet',
+ );
+ cli.answer.complete(
+ const CliAuthStatus(loggedIn: true, machineId: 'machine-a'),
+ );
+ await _ticks();
+ final saved =
+ jsonDecode(storage.values['swarm_layout_v1']!)
+ as Map<String, dynamic>;
+ expect(saved['owner'], 'ada');
+ expect(jsonEncode(saved['swarms']), contains('Renamed early'));
+ },
+ );
+
+ test(
+ 'a layout change before the check names another machine is never saved under the kept account',
+ () async {
+ await keptFrom('machine-a');
+ unawaited(app.bootstrap());
+ await _ticks();
+ app.renameSwarm(app.swarms.first.id, 'Renamed early');
+ await _ticks();
+ cli.answer.complete(
+ const CliAuthStatus(loggedIn: true, machineId: 'machine-b'),
+ );
+ await _ticks();
+ final raw = storage.values['swarm_layout_v1'];
+ if (raw != null) {
+ expect((jsonDecode(raw) as Map<String, dynamic>)['owner'], isNot('ada'));
+ }
+ },
+ );
+
+ test(
+ 'another machine, and the kept record cannot be deleted: the launch starts again once, never from it (review of #3293)',
+ () async {
+ final stuck = _Undeletable();
+ await ProfileCache(stuck).write('machine-a', _ada);
+ final again = _App(cli, stuck)..api = api;
+ again.cliSessionOnDisk = () => true;
+ addTearDown(again.dispose);
+ unawaited(again.bootstrap());
+ await _ticks();
+ cli.answer.complete(
+ const CliAuthStatus(loggedIn: true, machineId: 'machine-b'),
+ );
+ await _ticks();
+ expect(_screen(again), 'workspace');
+ expect(again.signedIn, isTrue);
+ expect(again.currentUser, isNull);
+ // The early check, then at most the restarted launch's own.
+ expect(cli.asked, lessThanOrEqualTo(2));
+ },
+ );
+}
+
+/// A store whose deletes fail, as a full disk fails the native store's rewrite, while its reads still work.
+class _Undeletable extends _Memory {
+ @override
+ Future<void> delete(String key) async => throw StateError('disk full');
+}
diff --git a/desktop/test/profile_cache_test.dart b/desktop/test/profile_cache_test.dart
index ed1df3b6f..cab3b1544 100644
--- a/desktop/test/profile_cache_test.dart
+++ b/desktop/test/profile_cache_test.dart
@@ -391,9 +391,33 @@ void main() {
test('reads as none when it is $name', () async {
storage.values[ProfileCache.key] = stored;
expect(await ProfileCache(storage).read('machine-a'), isNull);
+ expect(await ProfileCache(storage).readKept(), isNull);
});
}
+ test(
+ 'the record reads back with the machine it was proven under (task #3561)',
+ () async {
+ storage.values[ProfileCache.key] = jsonEncode(good);
+ final kept = await ProfileCache(storage).readKept();
+ expect(kept?.machineId, 'machine-a');
+ expect(kept?.profile.id, 'ada');
+ expect(kept?.profile.email, '[email protected]');
+ expect(kept?.profile.name, 'Ada');
+ expect(await ProfileCache(null).readKept(), isNull);
+ },
+ );
+
+ test('a record with no machine id reads as none', () async {
+ storage.values[ProfileCache.key] = jsonEncode({
+ ...good,
+ 'machineId': null,
+ });
+ expect(await ProfileCache(storage).readKept(), isNull);
+ storage.values[ProfileCache.key] = jsonEncode({...good, 'machineId': ''});
+ expect(await ProfileCache(storage).readKept(), isNull);
+ });
+
test('holds no more than who the person is', () async {
await ProfileCache(storage).write(
'machine-a',
diff --git a/docs/plans/2026-10-30-project-instructions-design.md b/docs/plans/2026-10-30-project-instructions-design.md
index 93a6fd1b1..7425fb05d 100644
--- a/docs/plans/2026-10-30-project-instructions-design.md
+++ b/docs/plans/2026-10-30-project-instructions-design.md
@@ -80,7 +80,16 @@ lead is always the PM. A team cannot define "QA on the device", "Designer" or "d
- Agents talking in a loop with nobody noticing, burning quota.
- Losing what teams already set: rules, policy notes and custom role texts survive in the document, in their own words.
-## What the server still enforces: facts and access only
+## Phase-4 enforcement policy (superseded 2026-11-06)
+
+Dee's 2026-11-06 decision supersedes the facts/access-only policy below and the blanket refusal-removal
+requirements in this design: every rule a program can check belongs in code; project instructions keep judgment
+and project facts. Rule refusals may use plain code names again. Task #3591 narrows `removedRefusals.test.ts`
+to the retired role-registry codes, each with its reason; it adds no runtime refusals. The facts and access checks
+below remain required. The role registry remains retired. The inventory and removal notes below record the
+historical phase-4 implementation, not a ban on future rule enforcement.
+
+### Original phase-4 policy
A start, assignment or message is refused only when it cannot happen or breaks an access rule:
diff --git a/docs/plans/2026-10-30-project-instructions-plan.md b/docs/plans/2026-10-30-project-instructions-plan.md
index 7d3fc78b3..0fa2e4766 100644
--- a/docs/plans/2026-10-30-project-instructions-plan.md
+++ b/docs/plans/2026-10-30-project-instructions-plan.md
@@ -654,7 +654,12 @@ Ships in one release with phases 3 and 5, backend first. It relies on phase 3's
`swarm-instructions` refresh, `instructions`, neutral start prompts) and changes none of it except where named. Tasks 1-10
are backend and run in order (most edit `commands.ts`); 11-13 are CLI (11 reads task 7's read); 14 is the done check.
-Phase 4 is done when `removedRefusals.test.ts` and `integration/superTabWorkflow.test.ts` (task 14) pass: no refusal code
+**Superseded 2026-11-06 (Dee, task #3591):** checkable rules belong in code. The blanket prohibition on the
+inventory's refusal codes below no longer applies; `removedRefusals.test.ts` guards only retired role-registry
+codes, each with a stated reason. Plain rule refusal codes are allowed. See the updated design's
+"Phase-4 enforcement policy" note. The tasks below are the historical phase-4 implementation.
+
+Original phase-4 completion criterion: `removedRefusals.test.ts` and `integration/superTabWorkflow.test.ts` (task 14) pass: no refusal code
in the inventory's list is reachable, and a Tester, an Engineer and a Reviewer run the template's workflow with no
coordinator action between "ready" and "passed".
diff --git a/docs/plans/2026-11-06-retire-refusal-ban-plan.md b/docs/plans/2026-11-06-retire-refusal-ban-plan.md
new file mode 100644
index 000000000..958ba7019
--- /dev/null
+++ b/docs/plans/2026-11-06-retire-refusal-ban-plan.md
@@ -0,0 +1,37 @@
+# Retire the phase-4 refusal ban
+
+> Execute task by task in this Engineer session, test first, with one independent PR review.
+
+**Goal:** Let checkable rules use plain refusal codes without reviving the retired role registry.
+
+**Architecture:** Narrow the existing source guard to obsolete role-registry codes, each with a reason. Exercise its matcher with allowed rule codes and prohibited registry codes; add no runtime refusal.
+
+**Tech Stack:** TypeScript, Vitest, Markdown.
+
+**Spec:** Task #3591; `2026-10-30-project-instructions-design.md`, superseded by Dee's 2026-11-06 decision that checkable rules belong in code.
+
+## Global Constraints
+
+- Own only `backend/src/superTabs/removedRefusals.test.ts` and `docs/plans/`.
+- No runtime behavior, access changes, new refusals, dependencies or schema changes.
+- Keep source-walk coverage and access-check positive controls.
+- Follow project instructions: run affected tests locally; full backend unit and Super Tab suites run in PR CI.
+
+## Review Focus
+
+- Rule codes must be accepted in single, double and backtick quotes, without renaming.
+- Registry codes must still be detected; every retained ban states why.
+- Source scanning must still cover handlers and routes and exclude tests.
+- Historical facts/access-only wording must be explicitly superseded, not presented as current policy.
+
+## Task 1: Narrow the guard and document the policy change
+
+**Files:** Modify `backend/src/superTabs/removedRefusals.test.ts`, `docs/plans/2026-10-30-project-instructions-design.md` and the phase-4 note in `docs/plans/2026-10-30-project-instructions-plan.md`.
+
+**Interfaces:** Test-local `removedRefusals(text: string): string[]` is shared by fixtures and the source scan. No production interface changes.
+
+- [x] Extract the existing matcher without changing its ban. Add fixture cases permitting all non-registry codes and rejecting `ROLE_KIND`, `ROLE_UNAVAILABLE`, `ROLE_IN_USE`, `ROLE_GONE`, across the three quote styles. Commit the tests.
+- [x] Run `npm test -- src/superTabs/removedRefusals.test.ts`; observe rule-code cases fail against the old ban.
+- [x] Replace the blanket list with the four registry codes and individual reasons. Mark the design's enforcement section and phase-4 completion note superseded by Dee's decision.
+- [x] Rerun the focused test; require all cases pass. Commit, push and record red/green evidence in the PR.
+- [ ] Mark ready and hand to the Integrator for one review; use PR CI for full unit/integration evidence.
diff --git a/docs/plans/2026-11-06-signed-in-check-off-launch-plan.md b/docs/plans/2026-11-06-signed-in-check-off-launch-plan.md
new file mode 100644
index 000000000..83e5d5e28
--- /dev/null
+++ b/docs/plans/2026-11-06-signed-in-check-off-launch-plan.md
@@ -0,0 +1,87 @@
+# The signed-in check no longer holds up the first window — plan (task #3561)
+
+**Goal:** Desktop opens its window without waiting for `harness auth status`. The check is the second slowest launch
+step (245 ms median, 303 ms slowest on a release build, speed plan C for Huy); it is a Node process start, about 200 ms
+on an M2 Ultra even when it has nothing to refresh. A signed-out person still lands on the sign-in page.
+
+**Architecture:** "What's already stored" is the kept profile (`ProfileCache`, task #2169): it is written only after the
+CLI proved the account by its machine id and the server named it, and every sign-out the app sees clears it. When it is
+there, and the CLI's own sign-in file is on disk (looked at, never read), the launch opens as that account at once and
+the check finishes in the background. The check then either proves the same machine id (nothing changes), says signed
+out (the window goes to the sign-in page through the existing runtime sign-out path, `_signedOutAtRuntime`, as when a
+sign-out elsewhere is noticed), or names another account or cannot answer (the launch starts again from the CLI's
+answer, as a launch with nothing kept does today). With nothing kept, or no sign-in file, the launch waits for the
+check exactly as before.
+
+**Tech Stack:** Flutter 3.47 / Dart 3.13, `flutter_test` with a memory store and a fake sign-in.
+
+**Spec:** River's brief on task #3561: show the window from what's already stored and finish the check in the
+background, or make it cheaper; a signed-out person still lands on sign-in; before/after speed marks; tests that
+signed-in and signed-out launches both land on the right screen. Two security reviews (sign-in state).
+
+This plan is written and carried out by its Engineer, test first; there is no execution handoff.
+
+## Design
+
+- Growth: nothing new is stored; the kept profile is the one record it already was, cleared as before.
+- Concurrency: one isolate. The background check runs under the launch's auth revision; a sign-out or sign-in meanwhile
+ invalidates it, as every other auth work.
+- Read cost: one key read of the kept profile (already read today, after the check) and one `stat` of
+ `~/.harness/auth/session.json`. No token is read.
+- Scale: N/A because it is one launch of one app.
+- Compatibility: no CLI, API or file format change. An older CLI answers `auth status` as before.
+- Migration + rollback: none; reverting puts the check back in front of the window.
+- Audience: the server still enforces every request; the daemon, not the app, holds the session. The early window shows
+ only this computer's saved desk and the kept profile of the account the computer was last proven signed in as.
+- Identity: the account is the CLI's sign-in, proven by its machine id; never the machine owner's login.
+- Failure: a check that says signed out shows the sign-in page with "You were signed out on this computer"; one that
+ cannot run ends on the login screen, as today.
+- Platforms: macOS, Windows and Linux share this Dart path; a viewer (web, phone) has no CLI and is unchanged.
+
+## Global Constraints
+
+- A signed-out computer never opens as signed in when the app knows it: no kept profile (every in-app sign-out and
+ every signed-out launch clears it) or no CLI sign-in file (`harness logout` deletes it) waits for the check as before.
+- The one case the early window can be wrong is a sign-in ended while the app was closed that left the file on disk
+ (a server revoke or refused refresh, marked inside the file). The window then shows the saved desk for as long as
+ the check takes (about 200 ms) and goes to the sign-in page, as a running app does when the same thing happens to it.
+- Desktop tests use a memory store and a fake sign-in; nothing runs the real CLI.
+- No switch: the optimisation ships on.
+
+## Review Focus
+
+- Every disagreement between the check and the kept profile ends where today's launch would have ended.
+- No profile is kept, and no picture cache claimed, before the check proves the machine id.
+
+## Tasks
+
+### 1. The kept record can be read without a machine id (`desktop/lib/state/profile_cache.dart`)
+
+Files: `desktop/lib/state/profile_cache.dart`, `desktop/test/profile_cache_test.dart`.
+Interfaces: `Future<({String machineId, CurrentUserProfile profile})?> ProfileCache.readKept()`.
+
+- [x] Failing test: `readKept` returns the record with its machine id; malformed records read as none.
+- [x] Code that passes it; `read(machineId)` uses it.
+
+### 2. A launch with a kept sign-in opens before the check (`desktop/lib/state/app_state.dart`)
+
+Files: `desktop/lib/state/app_state.dart`, `desktop/test/kept_sign_in_launch_test.dart`.
+Interfaces: `bool Function() AppNotifier.cliSessionOnDisk` (`@visibleForTesting`, false under test).
+
+- [x] Failing tests (memory store, fake sign-in whose check is held):
+ - signed in with a kept profile: the window (`authenticated`, workspace, not the sign-in page) opens while the check
+ is still running, then the check proves it and nothing changes; the `window` speed mark comes before
+ `signed-in check`;
+ - signed out (nothing kept): the launch waits for the check and lands on the sign-in page;
+ - kept profile but no CLI sign-in file: waits, as before;
+ - kept profile, check says signed out: ends on the sign-in page, nobody shown, the kept profile gone;
+ - kept profile, check names another machine: ends signed in with nobody shown until the server answers, the old
+ record gone;
+ - kept profile, CLI cannot answer: ends on the login screen, as today;
+ - no profile is kept before the check proves the machine id.
+- [x] Code that passes them.
+
+### 3. Before/after numbers
+
+- [x] Speed marks of a launch with a check held for the measured 245 ms, before and after, in the PR; the release-build
+ launch on a Mac where the app can run is the Tester's.
diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yaml
index 4bb9e87d1..69755265a 100644
--- a/mobile/pubspec.yaml
+++ b/mobile/pubspec.yaml
@@ -2,7 +2,7 @@ name: harness_mobile
description: "Harness viewer for iOS and Android."
publish_to: 'none'
-version: 1.0.12+81
+version: 1.0.12+85
environment:
sdk: ^3.13.0