From 275ca69f6ed5819d7fabf16daff40bb7dbeafc7e Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:12:22 +0800 Subject: [PATCH] Fix team recovery, route retirement, and inbox paging --- src/solver/agentTeam.ts | 22 +++++++-- src/solver/agentTeamContext.ts | 7 ++- src/solver/agentTeamState.ts | 3 +- src/solver/agentTeamViews.ts | 9 ++-- src/solver/incrementalHelpers.ts | 9 +++- src/solver/proofReuse.ts | 3 +- src/solver/skillResearchContext.ts | 4 +- tests/agentTeamNativeLifecycle.test.ts | 68 ++++++++++++++++++++++++++ tests/agentTeamSourceRecovery.test.ts | 60 +++++++++++++++++++++-- 9 files changed, 165 insertions(+), 20 deletions(-) diff --git a/src/solver/agentTeam.ts b/src/solver/agentTeam.ts index d4d40cff..5dee24ec 100644 --- a/src/solver/agentTeam.ts +++ b/src/solver/agentTeam.ts @@ -73,6 +73,10 @@ function followupObjective(task: AgentTeamTask, message: string): string { return !inherited.length || agentTeamProfileSelection(message).length ? message : 'Profiles: ' + inherited.join(', ') + '\n' + message; } +function openRouteTask(task: AgentTeamTask) { + return !task.cancelRequested && !task.deliveryId && ['queued', 'running', 'paused', 'interrupted'].includes(task.status); +} + function correctableSourceFailure(error: unknown) { return error instanceof SolverSourceError || error instanceof Error && error.message === 'math_source_outside_ownership'; } @@ -297,7 +301,7 @@ export class AgentResearchTeam { for (const worker of this.archive.workers) { const pending = worker.pendingDelivery?.taskId; const affected = worker.tasks.filter(task => task.routeId === input.routeId && - (['queued', 'running', 'paused'].includes(task.status) || pending === task.id || task.helperSubmission)); + (openRouteTask(task) || pending === task.id || task.helperSubmission)); if (!affected.length) continue; const executing = affected.find(task => task.status === 'running' || pending === task.id || task.helperSubmission); for (const task of affected) { @@ -310,7 +314,7 @@ export class AgentResearchTeam { } } const live = this.live.get(worker.id); - if (!worker.tasks.some(task => !task.cancelRequested && ['queued', 'running', 'paused'].includes(task.status))) { + if (!worker.tasks.some(openRouteTask)) { worker.status = 'stopped'; worker.activity = live ? 'stopping' : 'idle'; releasedAgentIds.push(worker.id); @@ -977,6 +981,7 @@ export class AgentResearchTeam { turnId = activeTurnId; milestone.start(); worker.threadId = entry.session!.threadId; worker.cursor = context.inboxThrough ?? worker.cursor; + worker.previewCursor = context.inboxPreviewThrough ?? worker.previewCursor; usage.turnStarted(turnId); this.input.save(); if (worker.threadId !== worker.native!.threadId) throw new Error('math_team_native_start_identity_changed'); const accepted = this.nativeControl.accepted(worker, entry.session!, turnId); @@ -1241,7 +1246,7 @@ export class AgentResearchTeam { if (this.live.get(targetId)?.session || target?.writerStopUnconfirmed || targetId === 'lead' && (this.leadSession || state.writerStopUnconfirmed)) throw new Error('math_team_target_writing'); const worktree = target?.worktree ?? state.worktree; - const helpers = this.archive.deliveries.filter(delivery => delivery.kind === 'helpers' && + const helpers = target?.status === 'stopped' ? [] : this.archive.deliveries.filter(delivery => delivery.kind === 'helpers' && !this.archive.adoptions.some(adoption => adoption.deliveryId === delivery.id && adoption.targetId === targetId)); const queued = this.archive.adoptions.filter(item => item.targetId === targetId && ['queued', 'integrating'].includes(item.status)); if (!helpers.length && !queued.length) return; @@ -1361,6 +1366,17 @@ export class AgentResearchTeam { } await this.flushHelperSubmissions(worker); if (worker.pendingDelivery) await this.finishDelivery(worker); + // Older hosts left interrupted assignments open even after Lead retired their route. + let closedRetiredTask = false; + for (const task of worker.tasks) { + if (task.status !== 'interrupted' || !openRouteTask(task)) continue; + const retirement = this.archive.retiredRoutes?.find(route => route.routeId === task.routeId); + if (!retirement) continue; + task.cancelRequested = { at: retirement.retiredAt, reason: retirement.reason }; + task.status = 'cancelled'; task.finishedAt = retirement.retiredAt; + closedRetiredTask = true; + } + if (closedRetiredTask && !worker.tasks.some(openRouteTask)) worker.status = 'stopped'; } await this.flushAdoptions(); for (const worker of this.archive.workers) { diff --git a/src/solver/agentTeamContext.ts b/src/solver/agentTeamContext.ts index f768701d..2c19c36b 100644 --- a/src/solver/agentTeamContext.ts +++ b/src/solver/agentTeamContext.ts @@ -53,7 +53,7 @@ export function agentTeamWorkerDeliveryHelp(): string { /** Refresh current work without promoting a prior task, peer message or Lead check into this member's result. */ export function agentTeamWorkerSection(state: Readonly, role: AgentTeamRole, - assignment: AgentTeamAssignment): { section: ContextSection; inboxThrough: number } { + assignment: AgentTeamAssignment): { section: ContextSection; inboxThrough: number; inboxPreviewThrough: number } { const worker = state.agentTeam?.workers.find(item => item.id === role.id); if (!worker) throw new Error('math_team_agent_unknown:' + role.id); const current = worker.tasks.find(item => item.id === assignment.taskId); @@ -61,9 +61,8 @@ export function agentTeamWorkerSection(state: Readonly, role: Ag const overview = agentTeamOverview(state, { focusAgentId: role.id, assignmentTaskId: current.id }); const own = overview.workers.find(item => item.id === role.id)!; const prior = own.tasks.filter(item => item.id !== current.id && ['completed', 'failed', 'interrupted', 'cancelled', 'paused'].includes(item.status)).at(-1); - const inbox = agentTeamInboxPreview(state.agentTeam!, role.id, worker.cursor); - const inboxThrough = inbox.through; - return { inboxThrough, section: { id: 'agent-team-assignment', kind: 'assignment', + const inbox = agentTeamInboxPreview(state.agentTeam!, role.id, worker.cursor, worker.previewCursor); + return { inboxThrough: inbox.through, inboxPreviewThrough: inbox.previewThrough, section: { id: 'agent-team-assignment', kind: 'assignment', text: 'Current native task instructions (latest accepted followup; earlier instructions remain in native history; frozen problem and source constraints still apply):\n' + JSON.stringify({ agentId: role.id, coordinator: 'lead', taskId: current.id, objective: assignment.message, objectiveRevision: current.objectiveRevision ?? 1, workKind: current.workKind, diff --git a/src/solver/agentTeamState.ts b/src/solver/agentTeamState.ts index 62e60bc9..f28c6eac 100644 --- a/src/solver/agentTeamState.ts +++ b/src/solver/agentTeamState.ts @@ -115,7 +115,8 @@ export const agentTeamStateSchema = z.object({ schema: z.literal('theorem-os.age pendingSourceBase: z.string().regex(/^[a-f0-9]{40,64}$/u).optional(), pendingPeerDeliveries: z.array(z.string().regex(/^[a-f0-9]{64}$/u)).optional(), writerProcess: writerProcessSchema.optional(), - cursor: z.number().int().nonnegative(), pendingDelivery: z.object({ taskId: z.string(), + cursor: z.number().int().nonnegative(), previewCursor: z.number().int().nonnegative().optional(), + pendingDelivery: z.object({ taskId: z.string(), seedCommit: z.string(), declarations: z.array(declaration), commit: z.string().optional(), sourceDigest: z.string().optional() }).strict().optional(), writerStopUnconfirmed: z.object({ at: z.number(), reason: z.string() }).strict().optional(), diff --git a/src/solver/agentTeamViews.ts b/src/solver/agentTeamViews.ts index 6c6be00c..12004eb1 100644 --- a/src/solver/agentTeamViews.ts +++ b/src/solver/agentTeamViews.ts @@ -335,11 +335,12 @@ function eventPreview(event: AgentTeamState['events'][number]) { } /** A truncated preview never acknowledges the unreturned message body. */ -export function agentTeamInboxPreview(team: Readonly, actor: string, after: number) { +export function agentTeamInboxPreview(team: Readonly, actor: string, after: number, previewAfter = after) { const events: ReturnType[] = []; let through = after, truncated = false, more = false; + const start = Math.max(after, previewAfter); for (const item of team.events) { - if (item.to !== actor || item.sequence <= after) continue; + if (item.to !== actor || item.sequence <= start) continue; if (events.length === EVENTS) { more = true; break; @@ -347,9 +348,9 @@ export function agentTeamInboxPreview(team: Readonly, actor: str const event = eventPreview(item); events.push(event); truncated ||= Boolean(event.textTruncated); - if (!truncated) through = event.sequence; + if (start === after && !truncated) through = event.sequence; } - return { after, through, previewThrough: events.at(-1)?.sequence ?? after, events, + return { after, through, previewAfter: start, previewThrough: events.at(-1)?.sequence ?? start, events, more: more || truncated, continuation: 'Read addressed native messages for complete updates; use history and inspect-research for saved task results. Previews do not acknowledge their bodies.' }; } diff --git a/src/solver/incrementalHelpers.ts b/src/solver/incrementalHelpers.ts index 61811d7e..af60f796 100644 --- a/src/solver/incrementalHelpers.ts +++ b/src/solver/incrementalHelpers.ts @@ -9,10 +9,11 @@ import type { DeclarationArtifactIdentity } from './declarationArtifacts'; import { checkProjectedDeclarations } from './modules/evidence'; import { assertSolverSources, committedSource, commitSolverSources, git, solverProofImports, SolverSourceError, withSolverWorktree } from './problem'; -import { proofReuseEnvironment } from './proofReuse'; +import { hasDeterministicLeanFailure, hasLeanResourceLimitFailure, proofReuseEnvironment } from './proofReuse'; import { solverSourceContext } from './sourceContext'; import { allowedKnowledgeFile, locateKnowledgeDeclaration } from './theoremKnowledge'; import type { CooperativeTask } from './tasks'; +import { VerifierFailureError } from './verifierFailure'; const leanName = z.string().min(1).max(1000).refine(isSimpleLeanName); const leanFile = z.string().refine(value => value.endsWith('.lean') && allowedKnowledgeFile(value)); @@ -213,6 +214,12 @@ export async function landVerifiedHelpers(input: VerifiedHelpersInput): Promise< return reject('source_rejected', error.message); throw error; }); + const receipt = verification.verification; + // An interrupted or unbound check must leave the frozen nomination available for recovery. + if (receipt.results.some(result => result.cleanupError) || + !verification.passed && !hasDeterministicLeanFailure(receipt) && + !(batch.length === 1 && hasLeanResourceLimitFailure(receipt))) + throw new VerifierFailureError({ stage: 'incremental-helper-check', sourceCommit, verification: receipt }); for (const [index, declaration] of batch.entries()) { const result = verification.verification.results[index]; if (result?.status !== 'kernel_verified' || result.verifier !== 'lean-kernel' || result.cleanupError || result.sorryCount !== 0 || diff --git a/src/solver/proofReuse.ts b/src/solver/proofReuse.ts index 0991ba16..01cf9b8c 100644 --- a/src/solver/proofReuse.ts +++ b/src/solver/proofReuse.ts @@ -50,7 +50,8 @@ export function hasDeterministicLeanFailure(verification: MathematicsVerifierBat return verification.status === 'failed' && verification.results.some(result => result.status === 'failed') && verification.results.every(result => { const output = `${result.error || ''}\n${result.stdoutPreview || ''}\n${result.stderrPreview || ''}`; - const sourceRejection = result.error === 'Proof source contains sorry or admit.' && + const sourceRejection = (result.error === 'Proof source contains sorry or admit.' || + result.error === 'Helper source contains sorry or admit.') && ((Number.isSafeInteger(result.sorryCount) && result.sorryCount > 0) || (Number.isSafeInteger(result.admitCount) && result.admitCount > 0)) || Boolean(result.axioms?.length && result.error === `Proof source declares explicit axioms: ${result.axioms.join(', ')}.`) || diff --git a/src/solver/skillResearchContext.ts b/src/solver/skillResearchContext.ts index 51c9f0ce..4ad6fbe8 100644 --- a/src/solver/skillResearchContext.ts +++ b/src/solver/skillResearchContext.ts @@ -56,7 +56,7 @@ export function agentTeamContextSection(state: Readonly): Contex /** Stable host contracts and current facts; research methods live in the pinned skill. */ export function buildSkillResearchContext(problem: SolverProblem, state: Readonly, - access: ContextAccess & { researchSkill: MathAgentSkill }): ContextBundle & { inboxThrough?: number } { + access: ContextAccess & { researchSkill: MathAgentSkill }): ContextBundle & { inboxThrough?: number; inboxPreviewThrough?: number } { const skill = access.researchSkill; assertMathAgentSkillsCurrent([skill]); if (!state.researchSkill || state.researchSkill.digest !== skill.digest || state.researchSkill.name !== skill.name || @@ -158,6 +158,6 @@ export function buildSkillResearchContext(problem: SolverProblem, state: Readonl maxOptionalContextBytes: access.maxOptionalContextBytes, inlineManifest: false }); const continued = compile({ continuation: true }); return { instructions, ...compile(), continuationMessage: continued.message, continuationManifest: continued.manifest, - compileDispatch: compile, inboxThrough: workerContext?.inboxThrough, + compileDispatch: compile, inboxThrough: workerContext?.inboxThrough, inboxPreviewThrough: workerContext?.inboxPreviewThrough, scope: 'original-problem-and-allowed-library', sources: { problemReceiptDigest: problem.receiptDigest } }; } diff --git a/tests/agentTeamNativeLifecycle.test.ts b/tests/agentTeamNativeLifecycle.test.ts index 8a60cf1f..69c6d1e0 100644 --- a/tests/agentTeamNativeLifecycle.test.ts +++ b/tests/agentTeamNativeLifecycle.test.ts @@ -561,6 +561,74 @@ describe('native AgentControl preserves the mathematical team lifecycle', () => expect(f.sessions[2].message).toContain('Continue the original approach'); }); + it('releases an interrupted route for a replacement, retaining the stopped draft', async () => { + const f = fixture(); + await f.spawn('analyst', 'Route: obsolete\nInvestigate the initial route.'); + const worker = f.team.archive.workers[0], task = worker.tasks[0]; + fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'Partial result.\n'); + await f.native('interrupt', { caller: ROOT, target: { kind: 'id', threadId: worker.native!.threadId }, version: 'v2' }); + await expect.poll(() => f.team.hasActiveWorkers).toBe(false); + expect(task.status).toBe('interrupted'); + const commit = task.sourceCommit; + await f.spawn('peer'); + await expect(f.tool({ operation: 'retire_route', routeId: 'obsolete', reason: 'Refuted by the saved probe.' })) + .resolves.toMatchObject({ cancelledTaskIds: [task.id], releasedAgentIds: [worker.id] }); + await f.spawn('replacement'); + expect(task).toMatchObject({ status: 'cancelled', sourceCommit: commit }); + expect(fs.readFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'utf8')).toBe('Partial result.\n'); + }); + + it('keeps another interrupted route resumable when retiring a paused route', async () => { + const f = fixture(); + await f.spawn('analyst', 'Route: keep\nInvestigate this route.'); + const worker = f.team.archive.workers[0], target = { kind: 'id', threadId: worker.native!.threadId }; + await f.native('interrupt', { caller: ROOT, target, version: 'v2' }); + await expect.poll(() => f.team.hasActiveWorkers).toBe(false); + const followup = (text: string) => f.native('send', { caller: ROOT, target, input: { + kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text } } }); + await followup('Route: obsolete\nExplore another approach.'); + await f.tool({ operation: 'yield', reason: 'Awaiting evidence.' }, worker.id); + await f.sessions[1].complete(); + await expect.poll(() => f.team.hasActiveWorkers).toBe(false); + expect(await f.tool({ operation: 'retire_route', routeId: 'obsolete', reason: 'No longer needed.' })) + .toMatchObject({ releasedAgentIds: [] }); + await followup('Continue the remaining approach.'); + expect(worker.tasks.map(task => [task.routeId, task.status])).toEqual([['keep', 'running'], ['obsolete', 'cancelled']]); + }); + + it('releases a slot left on a retired interrupted assignment by an older checkpoint', async () => { + const f = fixture(); await f.spawn('analyst', 'Route: obsolete\nInvestigate this route.'); + const worker = f.team.archive.workers[0]; + await f.native('interrupt', { caller: ROOT, target: { kind: 'id', threadId: worker.native!.threadId }, version: 'v2' }); + await expect.poll(() => f.team.hasActiveWorkers).toBe(false); + f.team.archive.retiredRoutes = [{ routeId: 'obsolete', retiredAt: Date.now(), reason: 'Refuted.', source: 'lead' }]; + await f.team.restore(); + expect(worker.status).toBe('stopped'); + expect(worker.tasks[0]).toMatchObject({ status: 'cancelled', cancelRequested: { reason: 'Refuted.' } }); + await f.spawn('peer'); await f.spawn('replacement'); + }); + + it('dispatches the next preview page without acknowledging a truncated body', async () => { + const f = fixture(); await f.spawn('analyst'); + await f.sessions[0].complete(); + await expect.poll(() => f.team.hasActiveWorkers).toBe(false); + const team = f.team.archive, worker = team.workers[0], seq = team.events.at(-1)?.sequence ?? 0; + for (let i = 1; i <= 9; i++) team.events.push({ sequence: seq + i, at: Date.now(), from: 'lead', to: worker.id, + kind: 'message', text: i === 1 ? 'A'.repeat(801) : 'fixed-notice-' + i }); + for (let turn = 1; turn <= 2; turn++) { + await f.native('send', { caller: ROOT, target: { kind: 'id', threadId: worker.native!.threadId }, input: { + kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text: 'Check step ' + turn } } }); + const message = f.sessions[turn].message; + expect(message).toContain(turn === 1 ? 'fixed-notice-8' : 'fixed-notice-9'); + expect(message).not.toContain(turn === 1 ? 'fixed-notice-9' : 'fixed-notice-8'); + const saved = readSolverRunState(path.join(f.directory, 'state.json')).agentTeam!.workers[0]; + expect(saved.previewCursor).toBeGreaterThanOrEqual(seq + (turn === 1 ? 8 : 9)); + expect(saved.cursor).toBeLessThan(seq + 1); + await f.sessions[turn].complete(); + await expect.poll(() => f.team.hasActiveWorkers).toBe(false); + } + }); + it('holds legacy queued routes for reassignment when the checkpoint has only one native input', async () => { const f = fixture(); await f.spawn('analyst', 'Route: initial\nInvestigate the first approach.'); const worker = f.state.agentTeam!.workers[0]; diff --git a/tests/agentTeamSourceRecovery.test.ts b/tests/agentTeamSourceRecovery.test.ts index a18d0b2b..ed5f498f 100644 --- a/tests/agentTeamSourceRecovery.test.ts +++ b/tests/agentTeamSourceRecovery.test.ts @@ -14,9 +14,10 @@ import { readAgentTeamProofDelivery } from '../src/solver/agentTeamProof'; import { LEAN_MEMORY_LIMIT_ERROR } from '../src/math/verifier'; import { DeclarationArtifactCheckError } from '../src/solver/declarationArtifacts'; import { directSolverModules } from '../src/solver/modules'; +import * as evidence from '../src/solver/modules/evidence'; import { agentLibrary, LIBRARY_ACCESS_FILE, LIBRARY_REQUEST_FILE, type LibraryAccess, writeLibraryAccess } from '../src/solver/libraryAccess'; import { writeLibraryCatalog } from '../src/solver/libraryCatalog'; -import { git, readSolverProblem } from '../src/solver/problem'; +import { git, pinSolverResearchSkill, readSolverProblem } from '../src/solver/problem'; import { RESEARCH_TOOL_HELP_FILE } from '../src/solver/researchToolHelp'; import { prepareResearchSkill, researchSkillIdentity } from '../src/solver/researchSkill'; import type { SoftSliceSettings } from '../src/solver/softSlice'; @@ -307,10 +308,16 @@ describe('native team source handling', () => { it('lands standalone helpers with the producer task open and installs them in a peer with unpublished work', async () => { const f = fixture({ maxAgents: 3 }); + await f.spawn('retired', 'Route: discarded\nExplore this route.'); + const retired = f.team.archive.workers[0]!; + expect(await f.call({ operation: 'retire_route', routeId: 'discarded', reason: 'Close this independent route.', + evidenceRefs: ['RESEARCH.md'] })).toMatchObject({ releasedAgentIds: ['retired'] }); + await idle(f.team); + const retiredHead = git(retired.worktree, ['rev-parse', 'HEAD']); await f.spawn('member', 'Prove the goal and its helper lemmas.'); - const a = await f.session(0), producer = f.team.archive.workers[0]!; + const a = await f.session(1), producer = f.team.archive.workers[1]!; await f.spawn('peer', 'Draft another proof step.'); - const b = await f.session(1), consumer = f.team.archive.workers[1]!; + const b = await f.session(2), consumer = f.team.archive.workers[2]!; const helperProofs = helper + 'theorem second : True := helper\n'; const draft = 'theorem draft : True := by sorry\n'; fs.writeFileSync(f.source(producer.worktree), original.replace('theorem goal', helperProofs + 'theorem goal')); @@ -338,12 +345,14 @@ describe('native team source handling', () => { await f.team.close(); const saved = readSolverRunState(f.stateFile), restored = f.makeTeam(saved); await restored.restore(); + expect(restored.archive.adoptions.some(item => item.targetId === retired.id)).toBe(false); + expect(git(retired.worktree, ['rev-parse', 'HEAD'])).toBe(retiredHead); expect(fs.readFileSync(f.source(f.state.worktree), 'utf8')).toContain('theorem goal : True := by sorry'); const seeded = fs.readFileSync(f.source(consumer.worktree), 'utf8'); expect(seeded).toContain(helperProofs); expect(seeded).toContain(draft); await f.followup('peer', 'Use the landed helpers to finish both proofs.', restored); - const next = await f.session(2); + const next = await f.session(3); expect(next.message).toContain('landedHelpers'); expect(next.message).toContain('Recovery.second'); fs.writeFileSync(f.source(consumer.worktree), seeded.replaceAll('by sorry', 'by exact second')); @@ -357,6 +366,49 @@ describe('native team source handling', () => { expect(saved.check).toBeUndefined(); }, 60_000); + it('rechecks the frozen standalone helper on restore after the verifier was unavailable', async () => { + const f = fixture(); + await f.spawn('member', 'Prove the helper.'); + const first = await f.session(0), worker = f.team.archive.workers[0]!; + fs.writeFileSync(f.source(worker.worktree), original.replace('theorem goal', helper + 'theorem goal')); + const check = evidence.checkProjectedDeclarations; + vi.spyOn(evidence, 'checkProjectedDeclarations').mockImplementationOnce((problem, checkout, worktree, commit, targets, options) => + check(problem, checkout, worktree, commit, targets, { ...options, verifierCommandPath: path.join(f.directory, 'missing-lean') })); + expect(await f.call({ operation: 'submit', helpersOnly: true, declarations, summary: 'Reusable fact.' }, worker.id)) + .toMatchObject({ ok: true }); + first.complete(); await idle(f.team); await f.team.close(); + + const saved = readSolverRunState(f.stateFile), task = saved.agentTeam!.workers[0]!.tasks[0]!; + expect(saved.agentTeam!.deliveries).toHaveLength(0); + expect(saved.agentTeam!.workers[0]!.error).toBe('math_verifier_unavailable'); + expect(task.helperSubmission).toEqual(declarations); + expect(task.sourceCommit).toBe(git(worker.worktree, ['rev-parse', 'HEAD'])); + // The research entry point binds the pinned Lead skill to the reloaded problem before team recovery. + pinSolverResearchSkill(saved.problem, saved.worktree, readMathAgentSkill(path.join(saved.worktree, '.agents/skills/theoremos-research/SKILL.md'))); + const restored = f.makeTeam(saved); + await restored.restore(); + expect(restored.archive.deliveries).toEqual([expect.objectContaining({ kind: 'helpers', taskId: task.id })]); + expect(task.helperSubmission).toBeUndefined(); + expect(restored.archive.adoptions.filter(item => item.targetId === 'lead')).toEqual([ + expect.objectContaining({ status: 'completed' }), + ]); + expect(fs.readFileSync(f.source(saved.worktree), 'utf8')).toContain(helper); + expect(f.sessions).toHaveLength(1); + }, 60_000); + + it('returns a standalone helper containing sorry to its author for correction', async () => { + const f = fixture(); + await f.spawn('member', 'Prove the helper.'); + const first = await f.session(0), worker = f.team.archive.workers[0]!; + fs.writeFileSync(f.source(worker.worktree), original.replace('theorem goal', helper.replace('trivial', 'sorry') + 'theorem goal')); + expect(await f.call({ operation: 'submit', helpersOnly: true, declarations, summary: 'Check this draft.' }, worker.id)) + .toMatchObject({ ok: true }); + first.complete(); await idle(f.team); + expect(worker.tasks[0]!.error).toContain('Helper source contains sorry or admit.'); + expect(worker.tasks[0]!.helperSubmission).toBeUndefined(); + expect(f.team.archive.deliveries).toHaveLength(0); + }, 60_000); + it('replays a recorded submit_helpers call from an older member thread', async () => { const f = fixture(); const originalCall = { operation: 'submit_helpers', summary: 'Verified standalone facts.', declarations };