From d44cee6cf9621d3975be13fbb66b489cb96b8f18 Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:33:00 +0800 Subject: [PATCH] Fix solver acceptance, gap redispatch, and long budgets --- scripts/mathematics/runNativeSkillBaseline.ts | 2 +- scripts/test-codex-backend-delivery.ts | 2 +- src/runtime/executionDeadline.ts | 13 +++-- src/solver/cooperationCore.ts | 28 +++++---- src/solver/evaluation.ts | 14 +++-- src/solver/run.ts | 14 ++--- tests/agentTeamProof.test.ts | 21 ++++++- tests/agentTeamSolver.test.ts | 2 +- tests/evaluatorExecution.test.ts | 7 ++- tests/evaluatorRun.test.ts | 13 +++-- tests/executionDeadline.test.ts | 18 ++++++ tests/solverNextCheckPlanLifecycle.test.ts | 58 ++++++++++++++++++- 12 files changed, 152 insertions(+), 40 deletions(-) diff --git a/scripts/mathematics/runNativeSkillBaseline.ts b/scripts/mathematics/runNativeSkillBaseline.ts index 10e2fc5e..f0f91873 100644 --- a/scripts/mathematics/runNativeSkillBaseline.ts +++ b/scripts/mathematics/runNativeSkillBaseline.ts @@ -140,7 +140,7 @@ export async function runNativeSkillBaseline(argv: string[]): Promise { emit('proof_check_started'); check = await checkSolverProof(problem, worktree, prepared.environment, lease.signal, undefined, Infinity); emit('proof_checked', { commit: check.commit, passed: check.passed }); - if (check.passed) evaluation = await evaluateSolverProof(problem, worktree, check, prepared.environment, + if (check.passed) evaluation = await evaluateSolverProof(problem, check, prepared.environment, lease.signal, { timeoutMs: Infinity }); } catch (cause) { error = cause instanceof Error && /^math_/u.test(cause.message) ? cause.message : 'native_comparison_verifier_unavailable'; diff --git a/scripts/test-codex-backend-delivery.ts b/scripts/test-codex-backend-delivery.ts index 28d85e67..375494c4 100644 --- a/scripts/test-codex-backend-delivery.ts +++ b/scripts/test-codex-backend-delivery.ts @@ -279,7 +279,7 @@ export async function verifyNativeProofDelivery(input: { repository: string; exe assert.ok(state.agentTeam!.leadExposures?.some(exposure => exposure.kind === 'inspected' && exposure.deliveryId === reference.id)); assert.ok(state.agentTeam!.leadExposures?.some(exposure => exposure.kind === 'adopted' && exposure.deliveryId === reference.id)); assert.equal(git(receipt.workspaceRoot, ['rev-parse', 'HEAD']), problem.baseCommit, 'Research must not publish into the original workspace.'); - const evaluation = await evaluateSolverProof(problem, worktree, winner.check, environment, signal, + const evaluation = await evaluateSolverProof(problem, winner.check, environment, signal, { timeoutMs: Infinity, teamContributions: true }); assert.equal(evaluation.status, 'passed'); const contributions = buildAgentTeamContributions(state, evaluation); diff --git a/src/runtime/executionDeadline.ts b/src/runtime/executionDeadline.ts index 5fe98630..3256ef56 100644 --- a/src/runtime/executionDeadline.ts +++ b/src/runtime/executionDeadline.ts @@ -1,6 +1,8 @@ +import { scheduleMathTimeout } from '../math/mathTimers'; + /** A finite execution allowance that excludes time explicitly spent waiting for a person. */ export class ExecutionDeadline { - private timer?: ReturnType; + private cancelTimer?: () => void; private activeSince = Date.now(); private usedMs = 0; private waitedMs = 0; @@ -19,7 +21,7 @@ export class ExecutionDeadline { const now = Date.now(); if (waiting) { this.usedMs = this.executionMs(); - clearTimeout(this.timer); + this.cancelTimer?.(); // A late pause must not revive an execution allowance that already ran out. if (this.usedMs >= this.limitMs) { this.stopped = true; this.expire(); return; } this.waitingSince = now; @@ -37,10 +39,13 @@ export class ExecutionDeadline { this.waitedMs = this.waitingMs(); this.waitingSince = undefined; this.stopped = true; - clearTimeout(this.timer); + this.cancelTimer?.(); } private arm() { - if (Number.isFinite(this.limitMs)) this.timer = setTimeout(() => { this.stop(); this.expire(); }, this.remainingMs()); + this.cancelTimer = scheduleMathTimeout(() => { + this.stop(); + this.expire(); + }, this.remainingMs()); } } diff --git a/src/solver/cooperationCore.ts b/src/solver/cooperationCore.ts index 85534f0a..4b818e83 100644 --- a/src/solver/cooperationCore.ts +++ b/src/solver/cooperationCore.ts @@ -406,17 +406,25 @@ export abstract class CooperationCore { ...proposedDefinitionContractChecks(this.archive, identity, now)]) { const previous = this.archive.nextChecks?.find(record => record.id === proposed.record.id); if (previous) { - // A pause or removed downstream path can expire an unfinished definition check. - // When that exact question becomes relevant again, resume its one existing record. - if (previous.origin === 'definition-contract' && previous.status === 'stale' && !previous.outcome) { - const node = this.archive.tasks.find(item => item.nextCheckId === previous.id); - if (currentNextCheck({ ...previous, status: 'pending' }, this.archive, identity)) { - previous.status = 'pending'; - if (node) { node.task = { ...node.task, status: 'active' }; this.moveTask(node, 'pending', 'reopened'); } - else this.archive.tasks.push(proposed.node); - this.input.emit('next_check_resumed', { checkId: previous.id, taskId: previous.taskId }); - } + if (previous.status !== 'stale' || previous.outcome) continue; + const nodeIndex = this.archive.tasks.findIndex(item => item.nextCheckId === previous.id); + if (previous.origin === 'definition-contract') { + // An unfinished definition check can resume when the same question becomes relevant again. + if (!currentNextCheck({ ...previous, status: 'pending' }, this.archive, identity)) continue; + previous.status = 'pending'; + const node = this.archive.tasks[nodeIndex]; + if (node) { node.task = { ...node.task, status: 'active' }; this.moveTask(node, 'pending', 'reopened'); } + else this.archive.tasks.push(proposed.node); + } else { + // A republished gap needs a current delivery and a fresh assignment. + const { record, node } = proposed; + if (record.gapDeliveryId === previous.gapDeliveryId || !currentNextCheck(record, this.archive, identity)) continue; + Object.assign(previous, { status: 'pending', gapDeliveryId: record.gapDeliveryId, scope: record.scope, + check: record.check, proofSearchSeed: record.proofSearchSeed }); + if (nodeIndex < 0) this.archive.tasks.push(node); + else this.archive.tasks[nodeIndex] = { ...node, attempts: this.archive.tasks[nodeIndex].attempts }; } + this.input.emit('next_check_resumed', { checkId: previous.id, taskId: previous.taskId }); continue; } // A model task cannot take ownership of the host's deterministic check id. diff --git a/src/solver/evaluation.ts b/src/solver/evaluation.ts index dce81c6e..14eeecf5 100644 --- a/src/solver/evaluation.ts +++ b/src/solver/evaluation.ts @@ -2,7 +2,7 @@ import { MATH_PROOF_ENVIRONMENT_ENV } from '../math/mathProofEnvironment'; import { runMathematicsSandboxedCommand, type MathematicsSandboxCommandResult } from '../math/verifier'; import { runPersistedLeanEvalOfficialGate } from '../math/leanEvalBootstrap'; import { checkSolverProof, type ProofCheck } from './modules/evidence'; -import { git, type SolverProblem } from './problem'; +import { git, withSolverWorktree, type SolverProblem } from './problem'; /** Execution failures cannot decide whether a mathematical submission is correct. */ export function evaluatorExecutionFailure(result: Pick> { const deadline = Date.now() + options.timeoutMs; const controller = new AbortController(); @@ -54,9 +54,13 @@ export async function evaluateSolverProof(problem: SolverProblem, worktree: stri assertActive(); if (!finalCheck.passed || finalCheck.commit !== receipt.commit || finalCheck.sourceDigest !== receipt.sourceDigest) throw new Error('math_integrated_proof_mismatch'); - if (options.command) { - const result = await runMathematicsSandboxedCommand({ checkoutRoot: worktree, projectRelative: problem.projectRelative, - command: '/bin/sh', args: ['-c', options.command], timeoutMs: options.timeoutMs, env, signal: evaluationSignal }); + const command = options.command; + if (command) { + const result = await withSolverWorktree(problem.workspace, finalCheck.commit, checkoutRoot => { + assertActive(); + return runMathematicsSandboxedCommand({ checkoutRoot, projectRelative: problem.projectRelative, + command: '/bin/sh', args: ['-c', command], timeoutMs: options.timeoutMs, env, signal: evaluationSignal }); + }); assertActive(); const reason = evaluatorExecutionFailure(result); return { status: reason ? 'error' : result.exitCode === 0 ? 'passed' : 'failed', diff --git a/src/solver/run.ts b/src/solver/run.ts index 7207b383..c05017c5 100644 --- a/src/solver/run.ts +++ b/src/solver/run.ts @@ -6,6 +6,7 @@ import { VerificationCheckpointError, withVerificationCheckpoints } from './veri import { parseArgs } from 'node:util'; import { readMathBuildManifest } from '../math/mathBuildManifest'; import { MathGitError } from '../math/mathGit'; +import { scheduleMathTimeout } from '../math/mathTimers'; import { canonicalMathJson, mathDigest, readMathJson, readMathText, withMathRuntimeLease, writeMathJsonDurable, type MathLease } from '../math/mathRuntimeIo'; import { projectMathematicsRuntimeEnvironment, resolveMathematicsRuntimeEnvironment } from '../math/mathRuntimeEnvironment'; import { checkResolvedLeanToolchainReadiness } from '../math/leanToolchainReadiness'; @@ -248,7 +249,7 @@ export async function runSolver(args: string[], root: string, customModules?: So let preparing = true; let deadline = Infinity; let executionClock: ExecutionDeadline | undefined; - let timer: ReturnType | undefined = Number.isFinite(preparationMs) ? setTimeout(abort, preparationMs) : undefined; + const cancelPreparation = scheduleMathTimeout(abort, preparationMs); let ownedState: SolverRunState | undefined; let proofEnvironment: Awaited> | undefined; let continuationSeeding = false; @@ -371,7 +372,7 @@ export async function runSolver(args: string[], root: string, customModules?: So } return; } - clearTimeout(timer); timer = undefined; + cancelPreparation(); try { await disposeProofEnvironment(); await generateSolverExplanations({ problem: state.problem, worktree, directory, root, buildManifest: buildFile, @@ -685,13 +686,12 @@ export async function runSolver(args: string[], root: string, customModules?: So return 0; } signal.throwIfAborted(); - clearTimeout(timer); + cancelPreparation(); preparing = false; state.solveStartedAt = Date.now(); state.solveFinishedAt = undefined; state.solveWaitingMs = 0; deadline = state.solveStartedAt + maxRunMs; - timer = undefined; executionClock = new ExecutionDeadline(maxRunMs, abort); const executionBudget = { remainingMs: () => executionClock!.remainingMs(), @@ -716,8 +716,6 @@ export async function runSolver(args: string[], root: string, customModules?: So profile, signal, deadline, executionBudget, maxTurns, maxTurnMs, maxTotalTokens, proofTimeoutMs, freshContinuationChecks, prepareTeamWorker, save, emit })); - clearTimeout(timer); - timer = undefined; executionClock.stop(); state.solveWaitingMs = executionClock.waitingMs(); state.solveFinishedAt = Date.now(); @@ -727,7 +725,7 @@ export async function runSolver(args: string[], root: string, customModules?: So readMathBuildManifest(buildFile, root, bundleRoot); const evaluationStarted = Date.now(); emit('evaluation_started', { workerId: state.winningWorker ?? 'solver' }); - evaluation = await evaluateSolverProof(state.problem, winner.worktree, winner.check, env, signal, + evaluation = await evaluateSolverProof(state.problem, winner.check, env, signal, { command: values['evaluator-command'], timeoutMs: evaluatorMs, teamContributions: state.agentTeam?.transport === 'native-agent-control' && state.agentTeam.deliveries.length > 0 }); emit('evaluation_finished', { status: evaluation.status, durationMs: Date.now() - evaluationStarted }); @@ -799,7 +797,7 @@ export async function runSolver(args: string[], root: string, customModules?: So return controller.signal.aborted ? 4 : 1; } finally { executionClock?.stop(); - clearTimeout(timer); + cancelPreparation(); hostSignal?.removeEventListener('abort', hostAbort); process.removeListener('SIGINT', abort); process.removeListener('SIGTERM', abort); } diff --git a/tests/agentTeamProof.test.ts b/tests/agentTeamProof.test.ts index eac7e078..7279e458 100644 --- a/tests/agentTeamProof.test.ts +++ b/tests/agentTeamProof.test.ts @@ -156,6 +156,25 @@ describe('agent-owned declaration deliveries with real Lean', () => { expect(f.state.check).toBeUndefined(); }, 90_000); + it('evaluates the checked commit even if the worker keeps editing afterward', async () => { + const f = fixture(); + const verifiedSource = original.replaceAll('by sorry', 'by trivial'); + fs.writeFileSync(f.source(f.worktree), verifiedSource); + const checked = await checkSolverProof(f.problem, f.worktree, f.common.env, f.common.signal); + expect(checked.passed).toBe(true); + const laterSource = verifiedSource.replaceAll('by trivial', 'by exact True.intro'); + fs.writeFileSync(f.source(f.worktree), laterSource); + + const evaluation = await evaluateSolverProof(f.problem, checked, f.common.env, f.common.signal, { + command: "grep -qFx 'theorem original : True := by trivial' Submission.lean", + timeoutMs: 30_000, + }); + + expect(evaluation).toMatchObject({ status: 'passed', method: 'external-command', result: { exitCode: 0 } }); + expect(git(f.problem.workspace, ['rev-parse', 'HEAD'])).toBe(checked.commit); + expect(fs.readFileSync(f.source(f.worktree), 'utf8')).toBe(laterSource); + }, 30_000); + it('matches versions and separates final direct, transitive, absent and unknown references', async () => { const f = fixture(), problem = f.problem, lead = path.join(f.directory, 'runtime/worktree'); git(problem.workspace, ['worktree', 'add', '--quiet', '--detach', lead, problem.baseCommit]); @@ -177,7 +196,7 @@ describe('agent-owned declaration deliveries with real Lean', () => { fs.writeFileSync(f.source(lead), edited); state.check = await checkSolverProof(problem, lead, f.common.env, f.common.signal); expect(state.check.passed).toBe(true); - const evaluation = await evaluateSolverProof(problem, lead, state.check, f.common.env, f.common.signal, { timeoutMs: 30_000, teamContributions: true }); + const evaluation = await evaluateSolverProof(problem, state.check, f.common.env, f.common.signal, { timeoutMs: 30_000, teamContributions: true }); expect(evaluation.status).toBe('passed'); const report = buildAgentTeamContributions(state, evaluation), relations = (r: typeof report) => Object.fromEntries(r.declarations.map(d => [d.name, d.targets.map(t => t.relation)])); diff --git a/tests/agentTeamSolver.test.ts b/tests/agentTeamSolver.test.ts index 02adb534..fa35e789 100644 --- a/tests/agentTeamSolver.test.ts +++ b/tests/agentTeamSolver.test.ts @@ -431,7 +431,7 @@ describe.skipIf(process.platform !== 'linux')('Agent team through native tool RP expect(source).toContain('exact combined n'); expect(source).not.toContain('sorry'); expect(git(receipt.workspaceRoot, ['rev-parse', 'HEAD'])).toBe(problem.baseCommit); - const evaluation = await evaluateSolverProof(problem, winner!.worktree, winner!.check, + const evaluation = await evaluateSolverProof(problem, winner!.check, environment, controller.signal, { timeoutMs: 30_000 }); expect(evaluation).toMatchObject({ status: 'passed', method: 'host-lean-kernel-all-targets', verification: { passed: true, commit: winner!.check.commit, verification: { status: 'kernel_verified' } } }); diff --git a/tests/evaluatorExecution.test.ts b/tests/evaluatorExecution.test.ts index d63ff341..d603b347 100644 --- a/tests/evaluatorExecution.test.ts +++ b/tests/evaluatorExecution.test.ts @@ -7,7 +7,8 @@ import type { SolverProblem } from '../src/solver/problem'; const host = vi.hoisted(() => ({ run: vi.fn(), check: vi.fn(), git: vi.fn(), official: vi.fn() })); vi.mock('../src/math/verifier', () => ({ runMathematicsSandboxedCommand: host.run })); vi.mock('../src/solver/modules/evidence', () => ({ checkSolverProof: host.check })); -vi.mock('../src/solver/problem', () => ({ git: host.git })); +vi.mock('../src/solver/problem', () => ({ git: host.git, + withSolverWorktree: (_workspace: string, _commit: string, run: (checkout: string) => Promise) => run('/fixture/snapshot') })); vi.mock('../src/math/leanEvalBootstrap', () => ({ runPersistedLeanEvalOfficialGate: host.official })); const commandResult = (changes: Partial = {}): MathematicsSandboxCommandResult => ({ @@ -16,7 +17,7 @@ const commandResult = (changes: Partial = {}): }); const receipt = { passed: true, commit: 'candidate', sourceDigest: 'source', verification: {} } as ProofCheck; const problem = { kind: 'lean-task', workspace: '/fixture/main', projectRelative: 'generated/problem', baseCommit: 'base' } as SolverProblem; -const evaluate = (input = problem) => evaluateSolverProof(input, '/fixture/worker', receipt, {}, +const evaluate = (input = problem) => evaluateSolverProof(input, receipt, {}, new AbortController().signal, { command: 'original-comparator comparator.json', timeoutMs: Infinity }); beforeEach(() => { @@ -82,7 +83,7 @@ describe('external evaluator execution failures', () => { stderrPreview: "could not execute external process 'lean'\n" }; host.official.mockResolvedValue({ comparison }); const value = await evaluateSolverProof({ ...problem, kind: 'lean-eval', sourceRepository: '/fixture/source' }, - '/fixture/worker', receipt, {}, new AbortController().signal, { timeoutMs: Infinity }); + receipt, {}, new AbortController().signal, { timeoutMs: Infinity }); expect(value).toEqual({ status: 'error', reason: 'math_evaluator_environment_unavailable', method: 'official-comparator', official: true, comparison }); expect(host.run).not.toHaveBeenCalled(); diff --git a/tests/evaluatorRun.test.ts b/tests/evaluatorRun.test.ts index 064dafd4..abd63977 100644 --- a/tests/evaluatorRun.test.ts +++ b/tests/evaluatorRun.test.ts @@ -62,16 +62,19 @@ describe('evaluator failure attribution in persisted run results', () => { expect(host.evaluate).not.toHaveBeenCalled(); }); - it('still interrupts preparation when an explicit finite deadline expires', async () => { + it.each([1, 2_147_484])('interrupts preparation at its explicit %s-second deadline', async seconds => { vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }); + let observed: { timeoutMs: number; abortedBeforeDeadline: boolean; abortedAtDeadline: boolean } | undefined; host.prepare.mockImplementation(async ({ timeoutMs, signal }) => { - expect(timeoutMs).toBeGreaterThan(0); - expect(timeoutMs).toBeLessThanOrEqual(1000); - await vi.advanceTimersByTimeAsync(1001); + await vi.advanceTimersByTimeAsync(seconds * 1000 - 1); + const abortedBeforeDeadline = signal.aborted; + await vi.advanceTimersByTimeAsync(1); + observed = { timeoutMs, abortedBeforeDeadline, abortedAtDeadline: signal.aborted }; signal.throwIfAborted(); throw new Error('fixture_finite_preparation_should_abort'); }); - expect(await runSolver([...args, '--prepare-timeout-seconds', '1', '--startup-only'], directory)).toBe(4); + expect(await runSolver([...args, '--prepare-timeout-seconds', String(seconds), '--startup-only'], directory)).toBe(4); + expect(observed).toEqual({ timeoutMs: seconds * 1000, abortedBeforeDeadline: false, abortedAtDeadline: true }); expect(JSON.parse(fs.readFileSync(output, 'utf8'))).toMatchObject({ status: 'limit_reached', reason: 'math_preparation_stopped' }); expect(vi.getTimerCount()).toBe(0); expect(host.research).not.toHaveBeenCalled(); diff --git a/tests/executionDeadline.test.ts b/tests/executionDeadline.test.ts index c54c2fe1..8381d915 100644 --- a/tests/executionDeadline.test.ts +++ b/tests/executionDeadline.test.ts @@ -53,4 +53,22 @@ describe('execution time with human approval waits', () => { expect(vi.getTimerCount()).toBe(0); clock.stop(); }); + + it('uses the full long execution allowance across a pause without expiring at the timer limit', async () => { + const limitMs = 3_000_000_000; + const expire = vi.fn(), clock = new ExecutionDeadline(limitMs, expire); + await vi.advanceTimersByTimeAsync(125); + expect(expire).not.toHaveBeenCalled(); + clock.setWaiting(true); + await vi.advanceTimersByTimeAsync(limitMs); + expect(expire).not.toHaveBeenCalled(); + expect(clock.remainingMs()).toBe(limitMs - 125); + clock.setWaiting(false); + await vi.advanceTimersByTimeAsync(limitMs - 126); + expect(expire).not.toHaveBeenCalled(); + expect(clock.remainingMs()).toBe(1); + await vi.advanceTimersByTimeAsync(1); + expect(expire).toHaveBeenCalledOnce(); + expect(vi.getTimerCount()).toBe(0); + }); }); diff --git a/tests/solverNextCheckPlanLifecycle.test.ts b/tests/solverNextCheckPlanLifecycle.test.ts index e52633d1..29b87e8e 100644 --- a/tests/solverNextCheckPlanLifecycle.test.ts +++ b/tests/solverNextCheckPlanLifecycle.test.ts @@ -3,7 +3,7 @@ import path from 'node:path'; import { afterEach, expect, it, vi } from 'vitest'; import { currentNextCheck } from '../src/solver/nextChecks'; import { commitSolverSources } from '../src/solver/problem'; -import { parseCooperationPlan } from '../src/solver/tasks'; +import { parseCooperationPlan, taskVersion } from '../src/solver/tasks'; import { cooperativeResearch } from './helpers/cooperation'; import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; @@ -105,6 +105,62 @@ it('preserves the host check and its dispatch identity across a group revision', expect(f.state.cooperation!.invalidTaskTransitions ?? []).toEqual([]); }); +it('redispatches an unfinished gap check from a fresh report after a group revision', async () => { + const example = localExample('next-check-gap-lifecycle-'); + const lead = leadWorker(example.problem, example.workspace); + const author = peerWorker(example, 'author'), checker = peerWorker(example, 'checker'), prover = peerWorker(example, 'prover'); + const plan = parseCooperationPlan(example.problem, { tasks: [ + ...example.problem.targets.map((target, index) => ({ ...target, id: `goal_${index}`, kind: 'goal', + objective: 'Prove the original target.', ownerId: prover.id })), + { id: 'survey', kind: 'research', objective: 'Study the missing step.', ownerId: author.id }, + ] }); + const state = solverState(example.problem, example.workspace, { runId: 'next-check-gap-fixture', phase: 'running', + cooperation: { canonicalCommit: example.problem.baseCommit, + tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), + groups: plan.groups.map(group => ({ group, turns: 0 })) } }); + const controller = new AbortController(); + const cooperation = cooperativeResearch({ state, workers: [lead, author, checker, prover], retrievalRoot: example.directory, + signal: controller.signal }); + cleanup.push(async () => { controller.abort(); await cooperation.stop(); fs.rmSync(example.directory, { recursive: true, force: true }); }); + await cooperation.restore(); + const budget = { maxTurns: Infinity, remainingMs: Infinity }; + const archive = state.cooperation!, target = plan.tasks.find(task => task.id === 'goal_0')!; + const mathematicalGap = { + consumer: { taskId: target.id, taskDigest: taskVersion(target) }, previousGap: 'Missing the main inference.', + remaining: 'Connect the estimates.', reduced: 'The estimates are stated.', evidenceScope: 'Current goal.', + reconsiderWhen: [], nextCheck: { action: 'feasibility', objective: 'Check the remaining inference.', + expectedEvidence: 'Find an exact missing premise.' }, + }; + const report = async (summary: string) => { + const action = await cooperation.next(author, budget); + if (action?.kind !== 'task' || action.task.id !== 'survey') throw new Error('fixture_expected_survey'); + expect(cooperation.started(author, action)).toBe(true); + fs.writeFileSync(path.join(author.worktree, 'RESEARCH.md'), JSON.stringify({ summary, conclusion: 'inconclusive', mathematicalGap })); + await cooperation.deliver(author, action, commitSolverSources(example.problem, author.worktree)); + return archive.deliveries!.at(-1)!; + }; + + const firstDelivery = await report('First delivery.'); + const record = archive.nextChecks![0]; + expect(record).toMatchObject({ status: 'pending', gapDeliveryId: firstDelivery.id }); + const firstAssignment = await cooperation.next(checker, budget); + if (firstAssignment?.kind !== 'task') throw new Error('fixture_expected_gap_check'); + expect(firstAssignment.task.id).toBe(record.taskId); + const revised = structuredClone(plan); + revised.groups[0].revision++; + await (cooperation as unknown as { acceptPlan(plan: typeof revised): Promise }).acceptPlan(revised); + expect(firstDelivery.status).toBe('superseded'); + expect(record.status).toBe('stale'); + + const freshDelivery = await report('Updated notes on the same question.'); + expect(archive.nextChecks).toHaveLength(1); + expect(record).toMatchObject({ status: 'pending', gapDeliveryId: freshDelivery.id }); + const reassignment = await cooperation.next(checker, budget); + expect(reassignment).toMatchObject({ kind: 'task', task: { id: record.taskId } }); + expect(reassignment?.kind === 'task' && reassignment.assignment.assignmentId).not.toBe(firstAssignment.assignment.assignmentId); + expect(archive.invalidTaskTransitions ?? []).toEqual([]); +}); + it('expires a changed exact definition contract without leaving an ordinary orphan task', async () => { const f = await fixture(), previous = f.state.cooperation!.nextChecks![0]; const changed = structuredClone(f.plan), target = changed.tasks.find(task => task.id === 'witness')!;