From 7d98747e6fdb360aa7197a09468165515f2af744 Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:15:16 +0800 Subject: [PATCH] Fix proof checkpoint scheduling and delivery recovery --- src/math/mathGit.ts | 4 +- src/solver/archive.ts | 10 +- src/solver/contextCompiler.ts | 9 +- src/solver/continuationSeed.ts | 3 +- src/solver/cooperation.ts | 71 ++++-- src/solver/cooperationInputs.ts | 3 +- src/solver/cooperationShared.ts | 1 + src/solver/cooperationTaskProofs.ts | 283 +++++++++++++++++---- src/solver/deliveries.ts | 12 + src/solver/leadInbox.ts | 9 +- src/solver/research.ts | 10 +- src/solver/researchCheckpoints.ts | 5 +- src/solver/taskConnections.ts | 14 + src/solver/tasks.ts | 2 +- tests/consumerConnections.test.ts | 97 ++++++- tests/solverCooperativeCheckpoints.test.ts | 131 ++++++++++ tests/solverResearchDrafts.test.ts | 131 +++++++++- 17 files changed, 688 insertions(+), 107 deletions(-) diff --git a/src/math/mathGit.ts b/src/math/mathGit.ts index 919caf6c..f2f70fde 100644 --- a/src/math/mathGit.ts +++ b/src/math/mathGit.ts @@ -1,6 +1,6 @@ import { spawnSync } from 'node:child_process'; -type GitOptions = { maxBuffer: number; timeout?: number; errorMessage?: string }; +type GitOptions = { maxBuffer: number; timeout?: number; errorMessage?: string; input?: Buffer }; export type MathGitFailureDiagnostic = Readonly<{ command: string; exitCode: number | null; signal: NodeJS.Signals | null; code?: string; commit?: string; file?: string; stderr?: string }>; @@ -15,7 +15,7 @@ export class MathGitError extends Error { /** Keep source bytes intact; callers own Git identity and tree-mode checks. */ export const mathGitResult = (root: string, args: readonly string[], options: GitOptions) => spawnSync('git', ['-C', root, ...args], { - maxBuffer: options.maxBuffer, timeout: options.timeout ?? 30_000, + maxBuffer: options.maxBuffer, timeout: options.timeout ?? 30_000, input: options.input, }); export function mathGitBytes(root: string, args: readonly string[], options: GitOptions): Buffer { diff --git a/src/solver/archive.ts b/src/solver/archive.ts index 8d7efaa4..daae7ffa 100644 --- a/src/solver/archive.ts +++ b/src/solver/archive.ts @@ -40,7 +40,7 @@ export type DispatchWaitObservation = { omittedCandidates: number; candidates: { taskId: string; taskDigest: string; reason: 'role' | 'engineer' | 'owner' | 'saved-assignment' | 'review-independence' | 'running-duplicate' | - 'preparing-type' | 'synchronizing' | 'capacity-expired' | 'policy-no-selection' | 'dependency' | 'integration-queue' }[]; + 'preparing-type' | 'synchronizing' | 'capacity-expired' | 'awaiting-lead' | 'policy-no-selection' | 'dependency' | 'integration-queue' }[]; }; export type SolverWorkerState = Pick value.candidateCount === value.candidates.length + value.omittedCandidates); const planPublication = z.object({ nonce: z.string().min(1), file: z.string().regex(/^DELIVERIES-[a-f0-9]{64}\.jsonl$/u), offset: safeCount, eventDigest: z.string().regex(/^[a-f0-9]{64}$/u), baseVersion: z.string(), planVersion: z.string(), @@ -271,7 +271,8 @@ const taskRecord = z.object({ task, status: z.enum(['pending', 'running', 'block environmentDigest: z.string().min(1), problemReceiptDigest: z.string().min(1), proof: z.boolean().optional() }).optional(), researchCompletion: researchRecordSchema.optional(), connectionCheckpoint: z.object({ basisDigest: z.string().regex(/^[a-f0-9]{64}$/u), - inputDigest: z.string().regex(/^[a-f0-9]{64}$/u), outputDigest: z.string().regex(/^[a-f0-9]{64}$/u) }).strict().optional(), + inputDigest: z.string().regex(/^[a-f0-9]{64}$/u), outputDigest: z.string().regex(/^[a-f0-9]{64}$/u), + leadDeliveryId: z.string().min(1).optional(), leadWake: safeCount.optional() }).strict().optional(), attempts: count, proof: check.optional(), integratedCheck: check.optional(), assignment: z.object({ taskId: z.string(), taskDigest: z.string(), workerId: z.string(), seedCommit: z.string(), assignmentId: z.string().optional(), connectionCheck: connectionCheck.optional(), researchBasis: researchBasisSchema.optional(), @@ -405,7 +406,8 @@ const runState = research.extend({ schema: z.literal('deepscientist.math.solver. status: z.enum(['active', 'paused', 'stopped']), revision: count }).passthrough(), turns: count }).passthrough()).optional(), history: z.array(z.object({ task, proof: check.optional(), integratedCheck: check.optional(), researchCompletion: researchRecordSchema.optional() }).passthrough()).optional(), - deliveries: z.array(z.object({ researchRecord: researchRecordSchema.optional(), + deliveries: z.array(z.object({ researchRecord: researchRecordSchema.optional(), leadDecisionRequested: z.literal(true).optional(), + submissionAliases: z.array(z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/u)).optional(), searchCheckpoint: proofSearchCheckpointReferenceSchema.optional() }).passthrough()).optional(), nextChecks: z.array(nextCheckRecordSchema).optional(), deliveryReceipts: z.array(deliveryReceiptSchema).optional(), blockers: z.array(routeBlocker).optional(), diff --git a/src/solver/contextCompiler.ts b/src/solver/contextCompiler.ts index d869bc78..be995eaa 100644 --- a/src/solver/contextCompiler.ts +++ b/src/solver/contextCompiler.ts @@ -3,7 +3,7 @@ import { canonicalMathJson, mathDigest } from '../math/mathRuntimeIo'; import { inspectLeanDeclarations, inspectLeanDeclarationRegions } from '../math/leanSource'; import { maskLeanCommentsAndStrings } from '../math/leanSyntax'; import type { CooperationState } from './cooperation'; -import { deliveryFinding, type DeliveryRecord } from './deliveries'; +import { deliveryFinding, researchFindingRequestsDecision, type DeliveryRecord } from './deliveries'; import { originalDeclarationRegions, type SolverProblem } from './problem'; import { assignmentDeliveryFile, hasTaskAcceptance, leadPlanDeliveryFile, taskGroup, taskReferenceDependencies, taskVersion, type CooperativeAction, type TaskRecord } from './tasks'; import { buildProofContinuation } from './progress'; @@ -421,12 +421,7 @@ export function leadResearchInputs(deliveries: readonly DeliveryRecord[], byId: if (record.lemmaRequests?.some(task => !byId.has(task.id))) return true; // Host-bound check outcomes have their own per-publication nextCheckDecisions contract. if (source.nextCheckId && record.checkOutcome?.checkId === source.nextCheckId && record.checkOutcomeScope) return false; - const text = deliveryFinding(record, source.finding); - if (text === undefined) return false; - try { - const finding = JSON.parse(text); - return finding?.conclusion === 'refuted' || finding?.needsDecision === true; - } catch { return false; } + return researchFindingRequestsDecision(record, source.finding); }); } diff --git a/src/solver/continuationSeed.ts b/src/solver/continuationSeed.ts index 67e7829b..c9e9c7cb 100644 --- a/src/solver/continuationSeed.ts +++ b/src/solver/continuationSeed.ts @@ -116,6 +116,7 @@ const researchDelivery = z.object({ id: z.string().min(1), producer: id, taskId: remainingObligations: z.array(z.string()), summary: z.string(), evidenceRefs: z.array(z.string()), createdAt: z.number().int().nonnegative(), commit: oid.optional(), sourceDigest: z.string().optional(), finding: z.string().optional(), findingDigest: hash.optional(), + leadDecisionRequested: z.literal(true).optional(), researchRecord: researchRecordSchema.optional(), mathematicalGap: mathematicalGapSchema.optional(), checkOutcome: checkOutcomeSchema.optional(), checkOutcomeScope: nextCheckScopeSchema.optional(), sourceUses: z.array(researchSourceUseSchema).max(32).optional(), @@ -428,7 +429,7 @@ function advisoryResearchDelivery(delivery: DeliveryRecord): DeliveryRecord { premises: delivery.premises, dependencies: delivery.dependencies, remainingObligations: delivery.remainingObligations, summary: delivery.summary, evidenceRefs: delivery.evidenceRefs, createdAt: delivery.createdAt, commit: delivery.commit, sourceDigest: delivery.sourceDigest, finding: delivery.finding, - findingDigest: delivery.findingDigest, researchRecord: delivery.researchRecord, + findingDigest: delivery.findingDigest, leadDecisionRequested: delivery.leadDecisionRequested, researchRecord: delivery.researchRecord, mathematicalGap: delivery.mathematicalGap, mathematicalGapScope: delivery.mathematicalGapScope, checkOutcome: delivery.checkOutcome, checkOutcomeScope: delivery.checkOutcomeScope, sourceUses: delivery.sourceUses, searchCheckpoint: delivery.searchCheckpoint, diff --git a/src/solver/cooperation.ts b/src/solver/cooperation.ts index 4ac74c4a..affe612c 100644 --- a/src/solver/cooperation.ts +++ b/src/solver/cooperation.ts @@ -5,7 +5,7 @@ import crypto from 'node:crypto'; import { VerificationCheckpointError } from './verificationCheckpoint'; import { canonicalMathJson, mathDigest, writeMathJsonDurable } from '../math/mathRuntimeIo'; import { inspectLeanDeclarationRegions, inspectLeanSource, inspectScopedLeanDeclarations } from '../math/leanSource'; -import { committedSource, git, originalDeclarationRegions, solverSourceConstraints } from './problem'; +import { committedSource, commitSolverSources, git, originalDeclarationRegions, solverSourceConstraints } from './problem'; import { solverProofFeedback, solverSourceFeedback } from './feedback'; import { assessTaskResponsibility, assignSharedResearchTask, independentFeasibilityWorker, researchWorkerCanNode, type ResearchWorker } from './modules/organization'; import type { DispatchWaitObservation } from './archive'; @@ -28,7 +28,7 @@ import { deliverHumanGuidance, readHumanGuidance } from './humanGuidance'; import { mathematicalGaps, mathematicalGapVisible } from './mathematicalGaps'; import { currentNextCheck, visibleNextChecks } from './nextChecks'; import { goalProgressForTask } from './goalProgress'; -import { automaticTaskConnection, createTaskConnectionCheck } from './taskConnections'; +import { automaticTaskConnection, createTaskConnectionCheck, taskConnectionNeedsRefresh } from './taskConnections'; import { TACTIC_BATTERY_TIMEOUT_MS } from './tacticBattery'; import { LIBRARY_APPLICATION_TIMEOUT_MS } from './libraryApplication'; import { knowledgeReferenceCoverage } from './knowledgeUsage'; @@ -379,7 +379,10 @@ export class CooperativeResearch extends CooperationInputs { } this.wakeLead('canonical-source-invalid'); } - for (const node of this.archive.tasks) if (node.status === 'running') this.moveTask(node, 'pending', 'interrupted'); + for (const node of this.archive.tasks) if (node.status === 'running') { + this.restoreConnectionHandoff(node); + this.moveTask(node, 'pending', 'interrupted'); + } for (const node of this.archive.tasks.filter(node => node.status === 'delivered')) await this.integrate(node); await this.integrateReady(); const statements = this.prepareStatementContexts(); if (statements) await statements; @@ -679,11 +682,25 @@ export class CooperativeResearch extends CooperationInputs { node.status === 'conditional' && taskDependenciesReady(node.task, this.archive.tasks))) || Boolean(this.archive.statementReviews?.some(review => route.has(review.taskId) && ['translating', 'reviewing'].includes(review.status))); } - private taskDispatchBlock(node: TaskRecord): 'preparing-type' | 'synchronizing' | 'capacity-expired' | undefined { + private taskDispatchBlock(node: TaskRecord): 'preparing-type' | 'synchronizing' | 'capacity-expired' | 'awaiting-lead' | undefined { if (this.preparingTaskTypes.has(node)) return 'preparing-type'; if (this.transferringResearch.has(node) || this.synchronizationBlocked(node.task)) return 'synchronizing'; if (node.capacityExploration && !currentCapacityExploration(node, this.archive.tasks, this.explorationIdentity)) return 'capacity-expired'; + const checkpoint = node.connectionCheckpoint; + if (!checkpoint || !this.liveWorkers.has(this.lead.id) || this.workerCoolingDown(this.lead.id)) return; + if (checkpoint.leadDeliveryId) { + const delivery = this.archive.deliveries?.find(record => record.id === checkpoint.leadDeliveryId); + if (!delivery || !leadResearchInputs([delivery], new Map(this.archive.tasks.map(task => [task.task.id, task])), + this.archive.researchDecisions).length) return; + // Match the planner's existing fallback when it cannot repair a rejected plan. + const rejection = this.archive.planRejection; + if (rejection?.stalled && rejection.inputDigest === this.planningInputDigest('rejection') && + rejection.proposalDigest === this.proposedPlanDigest()) return; + return 'awaiting-lead'; + } + // Older checkpoints recorded only the Lead turn's wake sequence. + if (checkpoint.leadWake !== undefined && this.archive.leadWakes!.settled < checkpoint.leadWake) return 'awaiting-lead'; } private transferringResearch = new Set(); private transferableResearch(node: TaskRecord, worker: ResearchWorker): boolean { @@ -857,10 +874,29 @@ export class CooperativeResearch extends CooperationInputs { node.assignment = undefined; const resumedAssignment = node.assignment; let resuming = resumedAssignment?.workerId === worker.id; - if (resuming && - (this.archive.researchDrafts?.[node.task.id]?.suspended || this.researchWorkspaceChanged(worker, node))) { + const connectionIdentity = { environmentDigest: this.input.state.environmentDigest, + problemReceiptDigest: this.input.state.problem.receiptDigest }; + const readSource = (worktree: string, commit: string) => (dependency: CooperativeTask) => + committedSource(worktree, commit, `${this.input.state.problem.projectRelative}/${dependency.proofPath}`); + const refreshDependencies = resuming && taskConnectionNeedsRefresh(node.task, resumedAssignment!, this.archive.tasks, + connectionIdentity, readSource(worker.worktree, resumedAssignment!.seedCommit), + readSource(this.lead.worktree, this.archive.canonicalCommit!)); + const restoreWorkspace = resuming && + (this.archive.researchDrafts?.[node.task.id]?.suspended || this.researchWorkspaceChanged(worker, node)); + if (refreshDependencies) { + // Wait for the previous reader/writer before changing its seed or the checkout. + if (this.active.get(worker.id)?.action.kind === 'task' || + [...this.proofPublications.values()].some(publication => publication.action.assignment === resumedAssignment)) + return this.waitForDispatch(); + if (!restoreWorkspace) { + const commit = commitSolverSources(this.input.state.problem, worker.worktree); + this.preserveResearchDraft(worker, { kind: 'task', task: node.task, assignment: resumedAssignment! }, commit, + captureDeliveryArtifacts({ problem: this.input.state.problem, worktree: worker.worktree, commit, assignment: resumedAssignment! })); + } + } + if (restoreWorkspace || refreshDependencies) { const previousAssignment = node.assignment; - const restored = await this.restoreResearchDraft(worker, node); + const restored = await this.restoreResearchDraft(worker, node, refreshDependencies); if (this.synchronizationBlocked(node.task) || !this.archive.tasks.includes(node) || node.status !== 'pending' || this.finalReviewCommit() && ordinaryAdvisoryTask(node.task) || !restored && node.assignment !== previousAssignment || @@ -873,13 +909,14 @@ export class CooperativeResearch extends CooperationInputs { node.feedback = 'math_research_draft_unavailable: No matching saved draft is available; continue from the current canonical sources and save findings for this assignment.'; this.input.emit('research_draft_unavailable', { taskId: node.task.id, workerId: worker.id }); } + if (refreshDependencies) node.connectionCheckpoint = undefined; } this.suspendResearchDrafts(worker, node.task.id); const seed = this.archive.canonicalCommit!; // Another reviewer's notes or notes for changed inputs cannot seed a fresh independent verdict. // Their pinned draft remains available as archived advisory evidence. if (!resuming && isFeasibilityReview(node.task)) fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), ''); - const scopedSeed = resuming ? seed : this.seed(worker, seed, node.task); + const scopedSeed = resuming ? node.assignment!.seedCommit : this.seed(worker, seed, node.task); const dispatchAssignment: TaskAssignment = resuming ? node.assignment! : { taskId: node.task.id, taskDigest: digest(node.task), workerId: worker.id, seedCommit: scopedSeed, assignmentId: crypto.randomUUID(), canonicalCommit: seed, groupId: taskGroup(node.task), routeId: selectedRoute?.id, @@ -1130,18 +1167,18 @@ export class CooperativeResearch extends CooperationInputs { } } let assignment = claimAssignment(); - if (!assignment.connectionCheck && automaticTaskConnection(node.task, this.archive.tasks, this.archive.groups)) { + if (!assignment.connectionCheck && (resuming && resumedAssignment?.connectionCheck && assignment !== resumedAssignment || + automaticTaskConnection(node.task, this.archive.tasks, this.archive.groups))) { + const candidate = resuming && assignment === resumedAssignment ? { ...assignment, assignmentId: crypto.randomUUID() } : assignment; + const check = createTaskConnectionCheck(node.task, candidate, this.archive.tasks, + connectionIdentity, readSource(worker.worktree, candidate.seedCommit)); // Upgrading an idle historical assignment keeps its saved draft but supersedes late publications. - if (resuming && assignment === resumedAssignment) { - assignment = { ...assignment, assignmentId: crypto.randomUUID() }; + if (check.assumedInputs?.length) { + assignment = candidate; + assignment.connectionCheck = check; node.assignment = assignment; + this.input.emit('task_connection_check_assigned', { taskId: node.task.id, workerId: worker.id, connectionCheck: check }); } - assignment.connectionCheck = createTaskConnectionCheck(node.task, assignment, this.archive.tasks, - { environmentDigest: this.input.state.environmentDigest, problemReceiptDigest: this.input.state.problem.receiptDigest }, - dependency => committedSource(worker.worktree, assignment.seedCommit, - `${this.input.state.problem.projectRelative}/${dependency.proofPath}`)); - this.input.emit('task_connection_check_assigned', { taskId: node.task.id, workerId: worker.id, - connectionCheck: assignment.connectionCheck }); } if (!advisory(node.task) && fs.existsSync(path.join(worker.worktree, this.input.state.problem.projectRelative, '.lake/source-constraints.json'))) { diff --git a/src/solver/cooperationInputs.ts b/src/solver/cooperationInputs.ts index 086e7548..b81761ef 100644 --- a/src/solver/cooperationInputs.ts +++ b/src/solver/cooperationInputs.ts @@ -521,7 +521,8 @@ export abstract class CooperationInputs extends CooperationPlanning { return; } // Legacy automatic ids already bind the assignment; unscoped old ids cannot identify a new seed. - const duplicate = this.archive.deliveries?.find(record => record.producer === worker.id && record.submissionId === value.id && + const duplicate = this.archive.deliveries?.find(record => record.producer === worker.id && + (record.submissionId === value.id || record.submissionAliases?.includes(value.id)) && record.taskId === action.task.id && record.taskDigest === action.assignment.taskDigest && (record.assignmentKey === assignmentKey || record.assignmentKey === undefined && scoped && value.id === automaticId)); if (duplicate) { diff --git a/src/solver/cooperationShared.ts b/src/solver/cooperationShared.ts index d7f84f81..c29f5cf1 100644 --- a/src/solver/cooperationShared.ts +++ b/src/solver/cooperationShared.ts @@ -200,6 +200,7 @@ export const deliveryInputFields = (record: DeliveryRecord) => ({ taskId: record.taskId, taskDigest: record.taskDigest, kind: record.kind, status: record.status, summary: record.summary, evidenceRefs: record.evidenceRefs, dependencies: record.dependencies, remainingObligations: record.remainingObligations, lemmaRequests: record.lemmaRequests, findingDigest: record.findingDigest, + leadDecisionRequested: record.leadDecisionRequested, mathematicalGap: record.mathematicalGap, mathematicalGapScope: record.mathematicalGapScope, checkOutcome: record.checkOutcome, checkOutcomeScope: record.checkOutcomeScope, sourceUses: record.sourceUses, searchCheckpoint: record.searchCheckpoint, diff --git a/src/solver/cooperationTaskProofs.ts b/src/solver/cooperationTaskProofs.ts index 8695204f..d94c431a 100644 --- a/src/solver/cooperationTaskProofs.ts +++ b/src/solver/cooperationTaskProofs.ts @@ -9,10 +9,10 @@ import { projectMathematicsRuntimeEnvironment } from '../math/mathRuntimeEnviron import { hashMathFormalSourceDeclaration, inspectLeanDeclarationRegions } from '../math/leanSource'; import { commitSolverSources, committedSource, git, withSolverWorktree } from './problem'; import { solverProofFeedback, solverSourceFeedback } from './feedback'; -import { independentFeasibilityWorker, type ResearchWorker } from './modules/organization'; +import { assessTaskResponsibility, independentFeasibilityWorker, type ResearchWorker } from './modules/organization'; import { proofReceiptsMatch, type ProofCheck } from './modules/evidence'; -import { routeAllowsTask, taskCanStart, selectedTaskRoute } from './modules/search'; -import { deliveryDetails, deliveryFinding, MAX_RESEARCH_NOTES_BYTES, parseMathResponse, type DeliveryRecord } from './deliveries'; +import { routeAllowsTask, taskCanStart, selectedTaskRoute, taskDependenciesReady } from './modules/search'; +import { deliveryDetails, deliveryFinding, MAX_RESEARCH_NOTES_BYTES, parseMathResponse, researchFindingRequestsDecision, type DeliveryRecord } from './deliveries'; import { checkTaskProof, createTaskSourceProjector, isAttributedTaskProof, ownedSourceDigest, projectedGoalInputs, taskChanges, trustedTaskProjectionReuse, type TaskProof } from './cooperativeProof'; import { proofReferencesUnchanged, type ProofReferences } from './proofReferences'; import { captureDeliveryArtifacts, diagnoseUnbackedLeanClaims, validateDeliveryArtifactClaims, type DeliveryArtifactManifest } from './deliveryArtifacts'; @@ -32,10 +32,12 @@ import { taskConnectionCheckCurrent, taskInputsMissingFromSeed } from './taskCon import { hasLeanResourceLimitFailure, hasLeanSourceDiagnostic } from './proofReuse'; import { assumableLemma, taskGroup, taskReferenceDependencies, assignmentDeliveryFile, markTaskReferences, markTaskAcceptance, hasTaskAcceptance, type CooperativeTask, type TaskAssignment, type TaskRecord, type CooperativeAction } from './tasks'; -import { digest, FailedTaskInput, bounded } from './cooperationShared'; +import { digest, FailedTaskInput, bounded, directDeliveryRejections, rejectionCode } from './cooperationShared'; import { CooperationStatements } from './cooperationStatements'; import { prepareResearchDelivery, ResearchAdmissionError, type ResearchSubmission } from './researchAdmission'; import { settleResearch } from './researchRecords'; +import { researchDecisionMatches } from './researchDecisions'; +import { leadResearchInputs } from './contextCompiler'; type ProofDeliveryRequest = { worker: ResearchWorker; action: Extract; @@ -67,10 +69,10 @@ export abstract class CooperationTaskProofs extends CooperationStatements { protected feasibilityInputDigest(task: CooperativeTask, workerId: string) { return feasibilityReviewInputDigest(this.feasibilityInput(task, workerId)); } - private checkpointInputDigest(task: CooperativeTask, workerId: string) { + private checkpointInputDigest(task: CooperativeTask, workerId: string, includeDeliveries = true) { return researchCheckpointInputDigest({ task, workerId, tasks: this.archive.tasks, deliveries: this.archive.deliveries ?? [], environmentDigest: this.input.state.environmentDigest, problemReceiptDigest: this.input.state.problem.receiptDigest, - problem: this.input.state.problem, worktree: this.lead.worktree, canonicalCommit: this.archive.canonicalCommit! }); + problem: this.input.state.problem, worktree: this.lead.worktree, canonicalCommit: this.archive.canonicalCommit!, includeDeliveries }); } private checkpointLocalInputDigest(task: CooperativeTask, workerId: string, legacyProgress = false) { return researchCheckpointLocalInputDigest({ task, workerId, tasks: this.archive.tasks, deliveries: this.archive.deliveries ?? [], @@ -273,7 +275,8 @@ export abstract class CooperationTaskProofs extends CooperationStatements { const finding = deliveryFinding(delivery); if (!finding || this.leanSourceDigest(this.lead.worktree, delivery.commit) !== candidate.sourceDigest) return false; const report = JSON.parse(finding); - return report.needsDecision === true && ['inconclusive', 'refuted'].includes(report.conclusion); + return (report.needsDecision === true || delivery.leadDecisionRequested) && + ['inconclusive', 'refuted'].includes(report.conclusion); }); } private repeatedTaskFeedback(record: FailedTaskInput) { @@ -376,8 +379,38 @@ export abstract class CooperationTaskProofs extends CooperationStatements { ...(isFeasibilityReview(action.task) ? { feasibilityInputDigest: assignment.feasibilityInputDigest } : {}) }; this.pin(commit); } + private pendingConnectionFinding(assignment: TaskAssignment, checkpointCommit: string) { + const key = assignmentDeliveryFile(assignment); + const candidates = (this.archive.deliveries ?? []).filter(record => record.kind === 'research' && + record.assignmentKey === key && record.producer === assignment.workerId && + record.taskId === assignment.taskId && record.taskDigest === assignment.taskDigest && + (record.submissionId !== undefined || record.commit === checkpointCommit)); + if (!candidates.length) return; + return leadResearchInputs(candidates, new Map(this.archive.tasks.map(node => [node.task.id, node])), + this.archive.researchDecisions)[0]; + } + private bindConnectionFinding(node: TaskRecord, assignment: TaskAssignment, outputDigest: string, deliveryId: string) { + const connection = assignment.connectionCheck; + if (!connection) return false; + const inputDigest = this.checkpointInputDigest(node.task, assignment.workerId, false); + const previous = node.connectionCheckpoint; + if (previous?.basisDigest === connection.basisDigest && previous.inputDigest === inputDigest && + previous.outputDigest === outputDigest && previous.leadDeliveryId === deliveryId) return false; + node.connectionCheckpoint = { basisDigest: connection.basisDigest, inputDigest, outputDigest, leadDeliveryId: deliveryId }; + return true; + } + protected restoreConnectionHandoff(node: TaskRecord) { + const assignment = node.assignment, draft = this.archive.researchDrafts?.[node.task.id]; + if (!assignment?.connectionCheck || node.connectionCheckpoint?.leadDeliveryId || !draft || draft.suspended || + draft.taskDigest !== assignment.taskDigest || draft.workerId !== assignment.workerId || + draft.assignmentId !== assignment.assignmentId || draft.seedCommit !== assignment.seedCommit || + draft.canonicalCommit !== assignment.canonicalCommit) return; + // Older saves could capture the accepted finding and draft before binding the wait. + const pending = this.pendingConnectionFinding(assignment, draft.commit); + if (pending) this.bindConnectionFinding(node, assignment, draft.outputDigest, pending.id); + } /** A scheduling handoff retains code without submitting an unfinished assigned declaration. */ - retainContextDraft(worker: ResearchWorker, action: Extract, commit: string, + async retainContextDraft(worker: ResearchWorker, action: Extract, commit: string, reason: 'context' | 'connection' = 'context') { if (!this.current(action)) return; const previous = this.archive.researchDrafts?.[action.task.id], assignment = action.assignment; @@ -388,10 +421,46 @@ export abstract class CooperationTaskProofs extends CooperationStatements { const artifacts = captureDeliveryArtifacts({ problem: this.input.state.problem, worktree: worker.worktree, commit, assignment: action.assignment }); this.preserveResearchDraft(worker, action, commit, artifacts); - const node = this.node(action.task.id), outputDigest = this.archive.researchDrafts![action.task.id].outputDigest; - node.connectionCheckpoint = reason === 'connection' && assignment.connectionCheck && previousOutput === outputDigest - ? { basisDigest: assignment.connectionCheck.basisDigest, - inputDigest: this.checkpointInputDigest(action.task, worker.id), outputDigest } : undefined; + const node = this.node(action.task.id), draft = this.archive.researchDrafts![action.task.id]; + const connection = reason === 'connection' ? assignment.connectionCheck : undefined; + const unchanged = previousOutput === draft.outputDigest; + const waiting = node.connectionCheckpoint; + const pending = assignment.connectionCheck && this.pendingConnectionFinding(assignment, commit); + const leadDeliveryId = pending?.id ?? (unchanged && waiting?.basisDigest === assignment.connectionCheck?.basisDigest + ? waiting?.leadDeliveryId : undefined); + if (leadDeliveryId) this.bindConnectionFinding(node, assignment, draft.outputDigest, leadDeliveryId); + else node.connectionCheckpoint = connection && unchanged + ? { basisDigest: connection.basisDigest, inputDigest: this.checkpointInputDigest(action.task, worker.id), + outputDigest: draft.outputDigest } : undefined; + if (draft.handoffNotesDigest) { + const notes = committedSource(worker.worktree, commit, 'RESEARCH.md'); + const finding = this.checkpointFinding(notes); + let report = finding?.checkOutcome === undefined && (finding?.conclusion === 'refuted' || finding?.needsDecision === true) + ? finding : undefined; + // Alert the Lead about stalled prose without interpreting it as a mathematical claim. + if (!finding && connection && unchanged && previous && + !this.dependencies(node.task).some(input => input.status === 'pending' && !advisory(input.task) && + assessTaskResponsibility(input, worker, this.responsibility).kind === 'matches' && + taskDependenciesReady(input.task, this.archive.tasks) && routeAllowsTask(input.task, this.archive.tasks, this.archive.groups)) && + !this.archive.deliveries?.some(record => record.kind === 'research' && record.status !== 'superseded' && + record.assignmentKey === assignmentDeliveryFile(assignment) && + record.sourceDigest === ownedSourceDigest(this.input.state.problem, worker.worktree, commit))) { + report = { conclusion: 'inconclusive', + summary: 'This proof checkpoint repeated with an unchanged draft. Inspect the saved RESEARCH.md and decide how to proceed.' }; + } + if (report) { + try { + taskChanges(this.input.state.problem, worker.worktree, commit, node.task, assignment); + await this.publishResearchFinding(worker, action, commit, { kind: 'event', value: { ...report, needsDecision: true } }, + { artifacts, checkpoint: true, connectionOutputDigest: assignment.connectionCheck && draft.outputDigest }); + } catch (error) { + if (!this.current(action)) return; + if (!(error instanceof Error) || !directDeliveryRejections.has(rejectionCode(error))) throw error; + this.rejectWorkerDelivery(worker, action, notes, error); + } + if (!this.current(action)) return; + } + } if (!artifacts.artifacts.length || this.archive.deliveries?.some(record => record.producer === worker.id && record.taskId === action.task.id && record.taskDigest === action.assignment.taskDigest && record.commit === commit)) return; this.record(worker, action.task, 'progress', 'advisory', @@ -407,7 +476,7 @@ export abstract class CooperationTaskProofs extends CooperationStatements { if (!worker || !assignment || checkpoint.basisDigest !== assignment.connectionCheck?.basisDigest || !taskConnectionCheckCurrent(node.task, assignment, this.archive.tasks, { environmentDigest: this.input.state.environmentDigest, problemReceiptDigest: this.input.state.problem.receiptDigest }) || - checkpoint.inputDigest !== this.checkpointInputDigest(node.task, worker.id) || + checkpoint.inputDigest !== this.checkpointInputDigest(node.task, worker.id, !checkpoint.leadDeliveryId) || this.checkpointOutputAdvanced(worker, node, { taskDigest: assignment.taskDigest, outputDigest: checkpoint.outputDigest })) node.connectionCheckpoint = undefined; } @@ -527,7 +596,7 @@ export abstract class CooperationTaskProofs extends CooperationStatements { this.input.save(); return true; } - protected async restoreResearchDraft(worker: ResearchWorker, node: TaskRecord): Promise { + protected async restoreResearchDraft(worker: ResearchWorker, node: TaskRecord, refreshDependencies = false): Promise { const draft = this.archive.researchDrafts?.[node.task.id], assignment = node.assignment!; if (!draft || assignment.workerId !== worker.id) return false; const problem = this.input.state.problem; @@ -544,7 +613,8 @@ export abstract class CooperationTaskProofs extends CooperationStatements { return false; } const saved = await this.inspectResearchDraft(node, assignment, draft); - if (!saved || !this.archive.tasks.includes(node) || node.assignment !== assignment || digest(node.task) !== draft.taskDigest || + if (!saved || !this.archive.tasks.includes(node) || node.assignment !== assignment || + this.archive.researchDrafts?.[node.task.id] !== draft || digest(node.task) !== draft.taskDigest || node.status !== 'pending' || assignment.workerId !== worker.id || node.task.ownerId && node.task.ownerId !== worker.id || !independentFeasibilityWorker(node, worker, this.archive.tasks, this.archive.groups) || !taskCanStart(node.task, this.archive.tasks, this.archive.groups) || !routeAllowsTask(node.task, this.archive.tasks, this.archive.groups)) return false; @@ -555,18 +625,18 @@ export abstract class CooperationTaskProofs extends CooperationStatements { return false; } const canonicalChanged = ownedSourceDigest(problem, this.lead.worktree, this.archive.canonicalCommit!) !== saved.canonicalSourceDigest; + const reseed = canonicalChanged || refreshDependencies; + const hasDraftSources = draft.artifacts.artifacts.some(artifact => artifact.kind === 'owned-source'); + let restoredAssignment = assignment; this.suspendResearchDrafts(worker, node.task.id); - if (canonicalChanged) { - if (draft.artifacts.artifacts.some(artifact => artifact.kind === 'owned-source')) - this.record(worker, node.task, 'progress', 'advisory', - 'Saved research source draft retained separately while the canonical proof advanced; it requires independent checking.', - { commit: draft.commit, artifacts: draft.artifacts, remainingObligations: [node.task.id] }); + if (reseed) { fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), ''); const seedCommit = this.seed(worker, this.archive.canonicalCommit!, node.task); // A connection permission binds the old seed and dispatch, so the normal // dispatcher must rebuild it for the restored sources and new identity. - node.assignment = { ...assignment, assignmentId: crypto.randomUUID(), seedCommit, + restoredAssignment = { ...assignment, assignmentId: crypto.randomUUID(), seedCommit, canonicalCommit: this.archive.canonicalCommit, connectionCheck: undefined, + ...(refreshDependencies ? { researchBasis: undefined, canonicalProbe: undefined } : {}), ...(feasibility ? { feasibilityInputDigest } : {}) }; } else { // Restore the validated snapshot so its frozen seed remains an ancestor. @@ -576,13 +646,22 @@ export abstract class CooperationTaskProofs extends CooperationStatements { const notesFile = path.join(worker.worktree, 'RESEARCH.md'); if (saved.notes === undefined) fs.rmSync(notesFile, { force: true }); else fs.writeFileSync(notesFile, saved.notes); - const commit = commitSolverSources(problem, worker.worktree); + const seed = commitSolverSources(problem, worker.worktree); // A rebased assignment starts with the restored notes too. Otherwise the host's restoration // looks like a fresh notes write relative to an empty seed and can attribute inherited text. - if (canonicalChanged) node.assignment = { ...node.assignment!, seedCommit: commit }; - this.preserveResearchDraft(worker, { kind: 'task', task: node.task, assignment: node.assignment! }, commit, - captureDeliveryArtifacts({ problem, worktree: worker.worktree, commit, assignment: node.assignment! }), - { handoffNotesDigest: saved.handoffNotesDigest }); + if (reseed) restoredAssignment.seedCommit = seed; + const replay = reseed && !advisory(node.task) + ? this.replayDraftSources(worker, node.task, restoredAssignment, draft.seedCommit, draft.commit) : undefined; + const commit = replay?.commit ?? seed; + const artifacts = replay?.artifacts ?? captureDeliveryArtifacts({ problem, worktree: worker.worktree, commit, assignment: restoredAssignment }); + node.assignment = restoredAssignment; + this.preserveResearchDraft(worker, { kind: 'task', task: node.task, assignment: restoredAssignment }, + commit, artifacts, { handoffNotesDigest: saved.handoffNotesDigest }); + if (reseed && !replay && hasDraftSources) { + this.record(worker, node.task, 'progress', 'advisory', + 'Saved research source draft retained separately while the canonical proof advanced. Inspect the retained commit to recover useful edits.', + { commit: draft.commit, artifacts: draft.artifacts, remainingObligations: [node.task.id] }); + } this.input.emit('research_draft_restored', { taskId: node.task.id, commit, canonicalChanged }); this.input.save(); return true; @@ -593,6 +672,26 @@ export abstract class CooperationTaskProofs extends CooperationStatements { return false; } } + private replayDraftSources(worker: ResearchWorker, task: CooperativeTask, assignment: TaskAssignment, oldSeed: string, draft: string) { + const problem = this.input.state.problem; + const files = problem.ownedFiles.filter(file => file.endsWith('.lean') && !Object.hasOwn(problem.frozenFiles ?? {}, file)) + .map(file => path.join(problem.projectRelative, file)); + if (oldSeed === draft || !files.length) return; + const options = { maxBuffer: 16 * 1024 * 1024 }; + const patch = mathGitResult(worker.worktree, ['--literal-pathspecs', 'diff', '--no-ext-diff', '--no-textconv', '--binary', + '--no-renames', '--src-prefix=a/', '--dst-prefix=b/', oldSeed, draft, '--', ...files], options); + if (patch.error || patch.status !== 0 || !patch.stdout.length) return; + const applied = mathGitResult(worker.worktree, ['apply', '--3way', '--whitespace=nowarn', '-'], + { ...options, input: patch.stdout }); + if (!applied.error && applied.status === 0) { + try { + const commit = commitSolverSources(problem, worker.worktree); + taskChanges(problem, worker.worktree, commit, task, assignment); + return { commit, artifacts: captureDeliveryArtifacts({ problem, worktree: worker.worktree, commit, assignment }) }; + } catch { /* An invalid draft can still be inspected at its original commit. */ } + } + git(worker.worktree, ['reset', '--hard', assignment.seedCommit]); + } protected async researchCheckpoint(worker: ResearchWorker, action: Extract, commit: string, countStagnation: boolean) { if (isFeasibilityReview(action.task) && !this.node(action.task.id).nextCheckId) { // A saved independent review is only a handoff, even if its notes contain a provisional result. @@ -632,12 +731,7 @@ export abstract class CooperationTaskProofs extends CooperationStatements { } // A checkpoint is a partial publication, not a completed investigation. Only // explicit control JSON is eligible; ordinary prose and unfinished JSON remain drafts. - let finding: any; - try { finding = parseMathResponse(notes, 'math-result'); } - catch (error) { - if (!(error instanceof SyntaxError) && !(error instanceof Error && - ['math_math-result_requires_one_block', 'math_response_invalid'].includes(error.message))) throw error; - } + const finding = this.checkpointFinding(notes); const inherited = git(worker.worktree, ['ls-tree', '--format=%(objectname)', action.assignment.seedCommit, '--', 'RESEARCH.md']); // Scoped checkOutcome has a separate completion protocol; never settle it merely // because the scheduler yielded its writer. @@ -654,9 +748,18 @@ export abstract class CooperationTaskProofs extends CooperationStatements { this.rejected(action, UNCHANGED_RESEARCH_CHECKPOINT, commit); } else this.interrupted(worker, action); } + private checkpointFinding(notes: string): Record | undefined { + try { return parseMathResponse(notes, 'math-result') as Record; } + catch (error) { + if (!(error instanceof SyntaxError) && !(error instanceof Error && + ['math_math-result_requires_one_block', 'math_response_invalid'].includes(error.message))) throw error; + } + } + protected async publishResearchFinding(worker: ResearchWorker, action: Extract, commit: string, - submission: ResearchSubmission, options: Partial & { checkpoint?: boolean } = {}, sources?: unknown, probes?: unknown) { - const { checkpoint = false, ...deliveryOptions } = options; + submission: ResearchSubmission, options: Partial & { checkpoint?: boolean; connectionOutputDigest?: string } = {}, + sources?: unknown, probes?: unknown) { + const { checkpoint = false, connectionOutputDigest, ...deliveryOptions } = options; // A publication belongs to the inputs dispatched to this writer, even if its live // assignment gains a newer context while the asynchronous checks are running. const assignment = structuredClone(action.assignment), basis = assignment.researchBasis; @@ -702,29 +805,89 @@ export abstract class CooperationTaskProofs extends CooperationStatements { worktree: fixedWorker.worktree, commit: fixedCommit, assignment }); artifacts = { ...artifacts, reportedChecks: validateDeliveryArtifactClaims(finding, artifacts) }; const sourceDigest = ownedSourceDigest(this.input.state.problem, fixedWorker.worktree, fixedCommit); - const findingKey = checkpoint ? canonicalMathJson(finding) : ''; - const artifactKey = checkpoint ? checkpointCandidate('', artifacts).digest : ''; - const basisKey = checkpoint ? canonicalMathJson(basis ?? assignmentKey) : ''; + const findingKey = canonicalMathJson(finding); + const checkpointFindingKey = canonicalMathJson({ ...finding, needsDecision: undefined }); + const evidenceKey = (manifest: DeliveryArtifactManifest) => canonicalMathJson([...new Set(manifest.artifacts + .map(artifact => canonicalMathJson([artifact.kind, artifact.file, artifact.sha256])))].sort()); + const artifactKey = evidenceKey(artifacts); + const basisKey = canonicalMathJson(basis ?? assignmentKey); // Compare immutable content and dispatch inputs, not Git metadata or note offsets. // The existing deliveries persist this identity across task switches and restarts. - const alreadyPublished = () => checkpoint && (this.archive.deliveries ?? []).some(record => { + const matchingPublication = () => (this.archive.deliveries ?? []).find(record => { if (record.kind !== 'research' || record.status === 'superseded' || record.producer !== worker.id || record.taskId !== action.task.id || record.taskDigest !== assignment.taskDigest || record.sourceDigest !== sourceDigest || + !checkpoint && record.assignmentKey !== assignmentKey || record.artifacts?.problemReceiptDigest !== problemReceiptDigest || canonicalMathJson(record.researchRecord?.basis ?? record.assignmentKey ?? null) !== basisKey || - checkpointCandidate('', record.artifacts).digest !== artifactKey) return false; + evidenceKey(record.artifacts) !== artifactKey) return false; const previous = deliveryFinding(record); - try { return previous !== undefined && canonicalMathJson(JSON.parse(previous)) === findingKey; } + try { + if (previous === undefined) return false; + const parsed = JSON.parse(previous); + if (canonicalMathJson(parsed) === findingKey) return true; + // Checkpoint intake can promote an identical finding to a decision request. + // Preserve the original bytes and any answer attached to them. + const addedByCheckpoint = checkpoint && finding.needsDecision === true && + (parsed.needsDecision === undefined || parsed.needsDecision === false); + const alreadyRequested = parsed.needsDecision === true && + (finding.needsDecision === undefined || finding.needsDecision === false); + return (addedByCheckpoint || alreadyRequested) && + canonicalMathJson({ ...parsed, needsDecision: undefined }) === checkpointFindingKey; + } catch { return false; } }); - if (alreadyPublished()) return; + const completeResearch = (record: DeliveryRecord) => { + node.finding = record.finding; this.moveTask(node, 'completed', 'research-completed'); node.feedback = undefined; + node.researchCompletion = record.researchRecord; + if (this.archive.unchangedResearch) delete this.archive.unchangedResearch[node.task.id]; + if (this.archive.researchCheckpoints) delete this.archive.researchCheckpoints[node.task.id]; + }; + const reusePublication = () => { + const record = matchingPublication(); + if (!record) return; + if (checkpoint) { + let changed = connectionOutputDigest !== undefined && + this.bindConnectionFinding(node, assignment, connectionOutputDigest, record.id); + if (finding.needsDecision === true && !researchFindingRequestsDecision(record) && + !this.archive.researchDecisions?.some(decision => researchDecisionMatches(record, decision))) { + const alreadyPending = record.lemmaRequests?.some(task => !this.node(task.id)); + record.leadDecisionRequested = true; + if (!alreadyPending) this.wakeLead('research-finding'); + changed = true; + } + if (changed) this.changed(); + } else { + const { submissionId } = deliveryOptions; + if (submissionId !== undefined) { + if (record.submissionId === undefined) record.submissionId = submissionId; + else if (record.submissionId !== submissionId && !record.submissionAliases?.includes(submissionId)) + record.submissionAliases = [...(record.submissionAliases ?? []), submissionId]; + } + if (complete) { + record.researchRecord = settleResearch({ id: record.id, assignment, basis, + commit: record.commit!, finding: deliveryFinding(record)!, complete }); + // An advisory challenge does not count as a final refutation until completion. + if (!finding.blockers && finding.conclusion === 'refuted') + this.reportBlockers(node.task, [{ mechanism: 'reported-local-refutation', + scope: 'assigned-local-inference', evidenceRefs: details.evidenceRefs }]); + completeResearch(record); + this.input.emit('research_delivered', { taskId: node.task.id, conclusion: finding.conclusion, complete }); + } + this.resolveDeliveryReceipts(worker, action, finding.replacesReceipt, complete); + this.changed(); + } + return record; + }; + const previous = reusePublication(); + if (previous) return previous; const artifactWarning = diagnoseUnbackedLeanClaims(finding, artifacts); const knowledge = this.captureKnowledgeUseCheck(fixedWorker, node.task, fixedCommit); const knowledgeUses = await checkKnowledgeApplications(knowledge.uses, knowledge.input); if (!this.current(action) || this.node(action.task.id) !== node || worker.id !== assignment.workerId || assignmentDeliveryFile(action.assignment) !== assignmentKey || environmentDigest !== this.input.state.environmentDigest || problemReceiptDigest !== this.input.state.problem.receiptDigest) return; - if (alreadyPublished()) return; + const concurrent = reusePublication(); + if (concurrent) return concurrent; if (details.mathematicalGap) bindMathematicalGap(details.mathematicalGap, node.task, this.archive, { problemReceiptDigest, environmentDigest }); const checkOutcomeScope = details.checkOutcome && bindCheckOutcome(details.checkOutcome, node.task, assignment, @@ -746,26 +909,26 @@ export abstract class CooperationTaskProofs extends CooperationStatements { mechanism: 'reported-local-refutation', scope: 'assigned-local-inference', evidenceRefs: details.evidenceRefs, }] : undefined)); (this.archive.deliveries ??= []).push(record); - if (complete) { - node.finding = text; this.moveTask(node, 'completed', 'research-completed'); node.feedback = undefined; - node.researchCompletion = record.researchRecord; - if (this.archive.unchangedResearch) delete this.archive.unchangedResearch[node.task.id]; - if (this.archive.researchCheckpoints) delete this.archive.researchCheckpoints[node.task.id]; + if (connectionOutputDigest !== undefined) + this.bindConnectionFinding(node, assignment, connectionOutputDigest, record.id); + if (complete) completeResearch(record); + if (finding.needsDecision === true || finding.conclusion === 'refuted' || lemmaRequests.length || artifactWarning) { + this.wakeLead('research-finding'); } - if (finding.needsDecision === true || finding.conclusion === 'refuted' || lemmaRequests.length || artifactWarning) this.wakeLead('research-finding'); this.resolveDeliveryReceipts(worker, action, finding.replacesReceipt, complete); this.publishDeliveryRecord(record); this.observeKnowledgeUses(node.task, fixedCommit, knowledgeUses, knowledge.rejected); this.input.emit('research_delivered', { taskId: node.task.id, conclusion: finding.conclusion, complete }); + return record; }; - if (submission.kind === 'notes') await publish(worker, commit); + if (checkpoint || submission.kind === 'notes') return publish(worker, commit); else { // Explicit events leave the writer's live files and Git index untouched. - await withSolverWorktree(worker.worktree, commit, async checkout => { + return withSolverWorktree(worker.worktree, commit, async checkout => { for (const [file, source] of sourceSnapshot ?? []) fs.writeFileSync(path.join(checkout, this.input.state.problem.projectRelative, file), source); fs.writeFileSync(path.join(checkout, 'RESEARCH.md'), researchPublicationNotes(finding, probes)); - await publish({ ...worker, worktree: checkout }, commitSolverSources(this.input.state.problem, checkout)); + return publish({ ...worker, worktree: checkout }, commitSolverSources(this.input.state.problem, checkout)); }); } } @@ -804,23 +967,31 @@ export abstract class CooperationTaskProofs extends CooperationStatements { protected assignmentConditions(task: CooperativeTask, assignment?: TaskAssignment, tasks: readonly TaskRecord[] = this.archive.tasks, worktree = this.lead.worktree): readonly CooperativeTask[] { const dependencies = this.dependencies(task, tasks); + const readInput = (commit: string) => (dependency: CooperativeTask) => + committedSource(worktree, commit, `${this.input.state.problem.projectRelative}/${dependency.proofPath}`); if (!assignment?.connectionCheck) { if (!task.conditional) return []; if (!assignment) return dependencies.filter(node => assumableLemma(node.task) && node.status !== 'integrated').map(node => node.task); if (assignment.taskId !== task.id || assignment.taskDigest !== digest(task)) throw new Error('math_task_condition_version_invalid'); // Explicit conditional contracts also authorize only their frozen, exact dispatch inputs. - return (assignment.dependencies ?? []).map(reference => { + const inputs = (assignment.dependencies ?? []).filter(reference => { const input = tasks.find(node => node.task.id === reference.taskId); if (!input || digest(input.task) !== reference.taskDigest) throw new Error('math_task_condition_version_invalid'); - return input.task; - }).filter(input => assumableLemma(input)); + return assumableLemma(input.task); + }); + // Read the frozen canonical base as well as the scoped seed so an unaccepted draft + // declaration alone does not remove an assumption. Older records may lack that base. + const canonical = assignment.canonicalCommit; + const unresolved = canonical ? inputs.filter(reference => + taskInputsMissingFromSeed([reference], tasks, readInput(canonical)).length || + taskInputsMissingFromSeed([reference], tasks, readInput(assignment.seedCommit)).length) : inputs; + return unresolved.map(reference => tasks.find(node => node.task.id === reference.taskId)!.task); } if (!taskConnectionCheckCurrent(task, assignment, tasks)) throw new Error('math_task_condition_version_invalid'); const check = assignment.connectionCheck; // Historical dispatches predate assumedInputs. Reconstruct only from their immutable seed, // never from a dependency's integration status at the time this delivery is checked. - const assumed = check.assumedInputs ?? taskInputsMissingFromSeed(check.inputs, tasks, dependency => - committedSource(worktree, assignment.seedCommit, `${this.input.state.problem.projectRelative}/${dependency.proofPath}`)); + const assumed = check.assumedInputs ?? taskInputsMissingFromSeed(check.inputs, tasks, readInput(assignment.seedCommit)); return assumed.map(reference => tasks.find(node => node.task.id === reference.taskId)!.task); } protected async check(task: CooperativeTask, assignment: TaskAssignment, worktree: string, commit: string, diff --git a/src/solver/deliveries.ts b/src/solver/deliveries.ts index f88955f1..b6271ebd 100644 --- a/src/solver/deliveries.ts +++ b/src/solver/deliveries.ts @@ -112,6 +112,8 @@ export function reviewVerdict(value: unknown, errorCode: string): 'accepted' | ' /** One versioned record for hints, conditional sketches, proofs, reviews and failures. */ export type DeliveryRecord = { id: string; submissionId?: string; assignmentKey?: string; statementReviewId?: string; producer: string; taskId?: string; taskDigest?: string; groupId?: string; + /** Additional submission IDs coalesced into this record within the same assignment. */ + submissionAliases?: readonly string[]; kind: 'progress' | 'research' | 'proof' | 'review' | 'backtranslation' | 'statement-review' | 'failure'; status: 'advisory' | 'conditional' | 'verified' | 'failed' | 'superseded' | 'accepted' | 'changes_requested'; statement: string; premises: readonly string[]; @@ -123,6 +125,8 @@ export type DeliveryRecord = { findingDigest?: string; /** Each publication retains its own complete finding, including during an active proof. */ finding?: string; + /** A later handoff requested a Lead decision on this same immutable finding. */ + leadDecisionRequested?: true; researchRecord?: ResearchRecord; knowledgeUses?: readonly KnowledgeUse[]; mathematicalGap?: MathematicalGap; @@ -145,6 +149,14 @@ export function deliveryFinding(record: DeliveryRecord, nodeFinding?: string): s ? finding : undefined; } +export function researchFindingRequestsDecision(record: DeliveryRecord, nodeFinding?: string): boolean { + if (record.leadDecisionRequested) return true; + try { + const finding = JSON.parse(deliveryFinding(record, nodeFinding) ?? 'null'); + return finding?.needsDecision === true || finding?.conclusion === 'refuted'; + } catch { return false; } +} + export function deliveryDetails(value: any): Pick & Partial> { const strings = (items: unknown) => Array.isArray(items) && items.every(item => typeof item === 'string'); diff --git a/src/solver/leadInbox.ts b/src/solver/leadInbox.ts index 10687289..2e7ec9b2 100644 --- a/src/solver/leadInbox.ts +++ b/src/solver/leadInbox.ts @@ -1,5 +1,5 @@ import type { SolverWorkerState } from './archive'; -import { deliveryFinding, type DeliveryRecord } from './deliveries'; +import { researchFindingRequestsDecision, type DeliveryRecord } from './deliveries'; import type { TaskRecord } from './tasks'; export type IdlePeerEpisode = { since: number; at: number; count: number }; @@ -69,11 +69,6 @@ export function idlePeersAwaitingLead(workers: readonly SolverWorkerState[], lea } return { due, dueAt }; } -const needsDecision = (record: DeliveryRecord) => { - try { const finding = JSON.parse(deliveryFinding(record) ?? 'null'); return finding?.needsDecision === true || finding?.conclusion === 'refuted'; } - catch { return false; } -}; - export const leadInboxBasis = (tasks: readonly TaskRecord[], planVersion: string | undefined, at = Date.now()): LeadInboxBasis => ({ at, planVersion, statuses: Object.fromEntries(tasks.map(node => [node.task.id, node.status])) }); @@ -108,7 +103,7 @@ export function leadInbox(basis: LeadInboxBasis | undefined, input: { tasks: rea producer: record.producer, ...(record.taskId ? { taskId: record.taskId } : {}), summary: Buffer.byteLength(record.summary) > SUMMARY_BYTES ? Buffer.from(record.summary).subarray(0, SUMMARY_BYTES).toString('utf8').replace(/�$/u, '') + '…' : record.summary, - ...(record.kind === 'research' && needsDecision(record) ? { needsDecision: true as const } : {}), + ...(record.kind === 'research' && researchFindingRequestsDecision(record) ? { needsDecision: true as const } : {}), ...(record.lemmaRequests?.length ? { lemmaRequests: record.lemmaRequests.length } : {}) })), omittedDeliveries: Math.max(0, fresh.length - MAX_DELIVERIES), statusChanges: changes.slice(0, MAX_STATUS_CHANGES), omittedStatusChanges: Math.max(0, changes.length - MAX_STATUS_CHANGES), diff --git a/src/solver/research.ts b/src/solver/research.ts index 309bb6c5..b312cb75 100644 --- a/src/solver/research.ts +++ b/src/solver/research.ts @@ -414,6 +414,9 @@ export async function runResearchWorkers(input: { 'Add needsDecision:true inside finding only when Lead must choose a route or resolve a blocker; ordinary progress does not need a decision. ' + 'Do not invent a finding to satisfy this reminder. Publication remains advisory and does not accept a proof. '; }; + const proofFindingInstruction = 'If a precise mathematical finding needs a Lead decision, publish it through the current assignment log, ' + + 'or save a JSON math-result code block in RESEARCH.md with summary, conclusion ("refuted" for an actual counterexample), ' + + 'needsDecision:true and the exact argument and assumptions. A saved finding is advisory and does not submit a proof. '; const contextCheckpointInstruction = (assignment?: CooperativeAction) => { const file = assignment?.kind === 'task' ? assignmentDeliveryFile(assignment.assignment) : assignment && leadPlanDeliveryFile(assignment); @@ -423,7 +426,7 @@ export async function runResearchWorkers(input: { return 'Before further searches or experiments, save the exact current argument, ' + 'attempted methods and negative search scope, useful declaration/file references, and any precise unresolved inference in RESEARCH.md. ' + (lead ? 'Save or publish any planning decision as the math-plan revision your instructions describe; a Lead publishes no findings. ' - : proof ? 'If blocked on a mathematical inference, use the current assignment protocol to publish a source-bound finding and the exact gap; request a Lead decision only when one is needed. ' + : proof ? proofFindingInstruction : researchFindingInstruction(assignment)) + 'Propose independently checkable, strictly smaller typed obligations when possible; do not rename the original hard theorem or ' + 'assume it in a wrapper. Scratch experiments and an activity report alone are not a durable handoff or an accepted proof. ' + @@ -809,7 +812,8 @@ export async function runResearchWorkers(input: { 'running it in this turn. This turn yields a scheduling checkpoint at ' + Math.round(checkpointAfterMs / 60_000) + ' minutes; the same thread and saved work remain available.' : 'Save the current mathematical argument, exact unresolved step and useful references in RESEARCH.md now. ' + - researchFindingInstruction(assignment) + + (assignment?.kind === 'task' && hasTaskConnectionCheck(assignment.task, assignment.assignment) + ? proofFindingInstruction : researchFindingInstruction(assignment)) + 'This advisory turn will yield a scheduling checkpoint shortly, including when no new notes are saved. ' + 'The same thread and saved work will remain available for continuation; this does not end the solving budget.'); }).then(() => { @@ -1831,7 +1835,7 @@ export async function runResearchWorkers(input: { const commit = commitSolverSources(state.problem, worker.worktree); const reason = softSliceCheckpoint || contextSchedulingCheckpoint ? 'context' : 'connection'; recordAdvisoryOutput(true); - cooperation.retainContextDraft(worker, assignment, commit, reason); + await cooperation.retainContextDraft(worker, assignment, commit, reason); cooperation.interrupted(worker, assignment); emit(reason === 'context' ? 'context_checkpoint_saved' : 'connection_checkpoint_saved', { threadId: turnSession.threadId, taskId: assignment.task.id, commit }); diff --git a/src/solver/researchCheckpoints.ts b/src/solver/researchCheckpoints.ts index 9e117a0c..7f3e6445 100644 --- a/src/solver/researchCheckpoints.ts +++ b/src/solver/researchCheckpoints.ts @@ -67,9 +67,10 @@ export function researchCheckpointLocalInputDigest(input: CheckpointInput, legac } export function researchCheckpointInputDigest(input: CheckpointInput & { - problem: SolverProblem; worktree: string; canonicalCommit: string; + problem: SolverProblem; worktree: string; canonicalCommit: string; includeDeliveries?: boolean; }) { - const deliveries = [...new Set(visibleDeliveries(input).map(record => canonicalMathJson(deliveryInputFields(record))))].sort(); + const deliveries = input.includeDeliveries === false ? undefined + : [...new Set(visibleDeliveries(input).map(record => canonicalMathJson(deliveryInputFields(record))))].sort(); return mathDigest(canonicalMathJson({ taskDigest: taskVersion(input.task), environmentDigest: input.environmentDigest, problemReceiptDigest: input.problemReceiptDigest, sourceDigest: ownedSourceDigest(input.problem, input.worktree, input.canonicalCommit), diff --git a/src/solver/taskConnections.ts b/src/solver/taskConnections.ts index afec0899..f3f80f9d 100644 --- a/src/solver/taskConnections.ts +++ b/src/solver/taskConnections.ts @@ -117,6 +117,20 @@ export function taskConnectionCheckCurrent(task: CooperativeTask, assignment: Ta }); } +/** An integrated exact input earns a new seed on redispatch, without revoking the live receipt. */ +export function taskConnectionNeedsRefresh(task: CooperativeTask, assignment: TaskAssignment, tasks: readonly TaskRecord[], + identity: ConnectionIdentity, readSeedSource: (task: CooperativeTask) => string, + readCanonicalSource: (task: CooperativeTask) => string): boolean { + const check = assignment.connectionCheck; + if (check ? !taskConnectionCheckCurrent(task, assignment, tasks, identity) : + !task.conditional || assignment.taskId !== task.id || assignment.taskDigest !== taskVersion(task)) return false; + const inputs = check ? check.assumedInputs ?? check.inputs : assignment.dependencies ?? []; + const candidates = inputs.filter(reference => tasks.some(node => node.task.id === reference.taskId && + node.status === 'integrated' && !node.pendingValidation && assumableLemma(node.task) && taskVersion(node.task) === reference.taskDigest)); + const assumed = check?.assumedInputs ? candidates : taskInputsMissingFromSeed(candidates, tasks, readSeedSource); + return assumed.length > taskInputsMissingFromSeed(assumed, tasks, readCanonicalSource).length; +} + /** Lifetime attempt counts include obsolete contracts and must not suppress their first application check. */ export function freshTaskConnection(node: TaskRecord, tasks: readonly TaskRecord[], groups?: readonly RouteRecord[]): boolean { return !node.proof && !node.assignment && (Boolean(node.task.conditional) || automaticTaskConnection(node.task, tasks, groups)); diff --git a/src/solver/tasks.ts b/src/solver/tasks.ts index a02c57bd..134c7691 100644 --- a/src/solver/tasks.ts +++ b/src/solver/tasks.ts @@ -61,7 +61,7 @@ export type TaskRecord = { task: CooperativeTask; readonly status: 'pending' | ' attempts: number; assignment?: TaskAssignment; proof?: TaskProof; integratedCheck?: TaskProof; feedback?: string; finding?: string; researchCompletion?: ResearchRecord; /** An unchanged conditional handoff yields to an executable input without abandoning its draft. */ - connectionCheckpoint?: { basisDigest: string; inputDigest: string; outputDigest: string }; + connectionCheckpoint?: { basisDigest: string; inputDigest: string; outputDigest: string; leadDeliveryId?: string; leadWake?: number }; /** One source-contract correction belongs to this assignment, not equivalent mathematical tasks. */ sourceRepair?: { taskDigest: string; workerId: string; assignmentId?: string; seedCommit: string; pending: boolean; startedAttempt?: number }; diff --git a/tests/consumerConnections.test.ts b/tests/consumerConnections.test.ts index 8a7fc1bc..4eea7661 100644 --- a/tests/consumerConnections.test.ts +++ b/tests/consumerConnections.test.ts @@ -12,7 +12,7 @@ import { readyResearchTasks, taskCanStart } from '../src/solver/modules/search'; import { committedSource, commitSolverSources, git, readSolverProblem, type SolverProblem } from '../src/solver/problem'; import { automaticTaskConnection, createTaskConnectionCheck, freshTaskConnection, hasTaskConnectionCheck, taskConnectionCheckCurrent } from '../src/solver/taskConnections'; -import { freshlyAccepted, taskVersion, type CooperativeAction, type CooperativeTask, type TaskAssignment, type TaskRecord } from '../src/solver/tasks'; +import { assignmentDeliveryFile, freshlyAccepted, taskVersion, type CooperativeAction, type CooperativeTask, type TaskAssignment, type TaskRecord } from '../src/solver/tasks'; import { cooperativeResearch } from './helpers/cooperation'; import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; import { verifiedBatch } from './helpers/verifier'; @@ -306,6 +306,101 @@ describe('host consumer connection lifecycle', () => { expect(checkedSources.every(source => conditionalPayloads(source).length === 0)).toBe(true); }); + it.each([ + ['automatic', 'compatible'], + ['explicit', 'compatible'], + ['automatic', 'conflicting'], + ] as const)('refreshes a saved %s connection with a %s draft when its exact input integrates', async (mode, draftKind) => { + const worker = mode === 'automatic' ? workers[2] : workers[3]; + if (mode === 'explicit') { + const tasks = state.cooperation!.tasks.map(item => item.task.id === 'goal_0' + ? { ...item.task, status: 'paused' as const } : item.task); + tasks.splice(tasks.findIndex(task => task.id === 'independent'), 1, { id: 'consumer', kind: 'lemma', conditional: true, + objective: 'Use the exact integrated prerequisite.', type: 'True', theoremName: 'Tutorial.consumer', + proofPath: 'Submission.lean', dependsOn: ['helper'], revision: 0, ownerId: worker.id }); + await (cooperative as any).acceptPlan(parseCooperationPlan(problem, { tasks })); + } + const parent = await assigned(worker), consumer = node(parent.task.id); + expect(consumer.task.id).toBe(mode === 'automatic' ? 'goal_0' : 'consumer'); + expect(Boolean(parent.assignment.connectionCheck)).toBe(mode === 'automatic'); + const threadId = 'saved-connection-thread'; + const record = { ...worker, phase: 'running' as const, turns: 1, threadId, sessionTaskId: parent.task.id, + sessionTaskVersion: parent.assignment.taskDigest, sessionAssignmentId: parent.assignment.assignmentId }; + state.workers = [...(state.workers ?? []).filter(item => item.id !== worker.id), record]; + const notes = 'Saved connection draft before the exact input integrated.\n'; + fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), notes); + const conflicting = draftKind === 'conflicting'; + const draftAnchor = conflicting ? 'theorem add_zero' : 'end Tutorial'; + const draftLemma = conflicting ? 'lemma helper : True := by exact True.intro' : 'lemma old_draft_support : True := by trivial'; + fs.writeFileSync(sourcePath(worker), fs.readFileSync(sourcePath(worker), 'utf8') + .replace(draftAnchor, `${draftLemma}\n${draftAnchor}`)); + const previousCommit = commitSolverSources(problem, worker.worktree); + await cooperative.retainContextDraft(worker, parent, previousCommit, 'connection'); + cooperative.interrupted(worker, parent); + const unchanged = await assigned(worker); + expect(unchanged.assignment).toBe(parent.assignment); + cooperative.interrupted(worker, unchanged); + + await deliverInput(await assigned(workers[1])); + expect(node('helper').status).toBe('integrated'); + expect(cooperative.current(parent)).toBe(true); + const current = await assigned(worker); + expect(current.assignment).toMatchObject({ workerId: worker.id, taskDigest: parent.assignment.taskDigest, + canonicalCommit: state.cooperation!.canonicalCommit }); + expect(current.assignment.connectionCheck).toBeUndefined(); + expect(assignmentDeliveryFile(current.assignment)).not.toBe(assignmentDeliveryFile(parent.assignment)); + expect(committedSource(workspace, current.assignment.seedCommit, 'RESEARCH.md')).toBe(notes); + const proofPath = `${problem.projectRelative}/Submission.lean`; + const seedSource = committedSource(workspace, current.assignment.seedCommit, proofPath); + expect(seedSource).toContain('lemma helper : True := by trivial'); + expect(seedSource).not.toContain(draftLemma); + const resumedSource = conflicting ? seedSource : seedSource.replace(draftAnchor, `${draftLemma}\n${draftAnchor}`); + expect(fs.readFileSync(sourcePath(worker), 'utf8')).toBe(resumedSource); + const restored = state.cooperation!.researchDrafts![parent.task.id]; + expect(restored).toMatchObject({ assignmentId: current.assignment.assignmentId, + seedCommit: current.assignment.seedCommit, workerId: worker.id }); + expect(committedSource(workspace, restored.commit, proofPath)).toBe(resumedSource); + if (conflicting) { + expect(committedSource(workspace, previousCommit, proofPath)).toContain(draftLemma); + expect(state.cooperation!.deliveries).toContainEqual(expect.objectContaining({ commit: previousCommit, status: 'advisory', + artifacts: expect.objectContaining({ artifacts: expect.arrayContaining([expect.objectContaining({ kind: 'owned-source' })]) }) })); + } + expect(state.workers.find(item => item.id === worker.id)?.threadId).toBe(threadId); + expect(cooperative.current(parent)).toBe(false); + const checkedBefore = checkedSources.length; + await cooperative.deliver(worker, parent, previousCommit); + expect(checkedSources).toHaveLength(checkedBefore); + expect(consumer).toMatchObject({ status: 'running', assignment: current.assignment }); + expect(state.cooperation!.deliveries).toContainEqual(expect.objectContaining({ commit: previousCommit, status: 'superseded' })); + + const source = fs.readFileSync(sourcePath(worker), 'utf8'); + fs.writeFileSync(sourcePath(worker), mode === 'automatic' + ? source.replace('n + 0 = n := by sorry', 'n + 0 = n := by\n have h : True := Tutorial.helper\n rfl') + : source.replace('theorem add_zero', 'lemma consumer : True := by exact Tutorial.helper\ntheorem add_zero')); + await cooperative.deliver(worker, current, commitSolverSources(problem, worker.worktree)); + expect(consumer.status).toBe('integrated'); + expect(consumer.proof!.conditions).toBeUndefined(); + expect(checkedSources.slice(checkedBefore).every(source => conditionalPayloads(source).length === 0)).toBe(true); + }); + + it('rebuilds a connection receipt with only the input still unproved', async () => { + const tasks = state.cooperation!.tasks.map(item => item.task.id === 'goal_0' + ? { ...item.task, dependsOn: ['helper', 'remaining_input'] } : item.task); + tasks.push({ id: 'remaining_input', kind: 'lemma', objective: 'Prove the other premise.', type: 'True', + theoremName: 'Tutorial.remaining_input', proofPath: 'Submission.lean', dependsOn: [], revision: 0, ownerId: 'observer' }); + await (cooperative as any).acceptPlan(parseCooperationPlan(problem, { tasks })); + const worker = workers[2], first = await assigned(worker); + expect(first.assignment.connectionCheck?.assumedInputs?.map(input => input.taskId)).toEqual(['helper', 'remaining_input']); + cooperative.interrupted(worker, first); + await deliverInput(await assigned(workers[1])); + const current = await assigned(worker); + expect(current.assignment.connectionCheck?.assumedInputs).toEqual([ + { taskId: 'remaining_input', taskDigest: taskVersion(node('remaining_input').task) }, + ]); + expect(current.assignment.assignmentId).not.toBe(first.assignment.assignmentId); + expect(cooperative.current(current)).toBe(true); + }); + it.each(['goal', 'lemma'] as const)('discharges a conditional %s after a later input declaration and preserves added helper order', async kind => { rejectForwardInputReferences(); const tasks = state.cooperation!.tasks.map(item => item.task); diff --git a/tests/solverCooperativeCheckpoints.test.ts b/tests/solverCooperativeCheckpoints.test.ts index 8a5732ef..a3577894 100644 --- a/tests/solverCooperativeCheckpoints.test.ts +++ b/tests/solverCooperativeCheckpoints.test.ts @@ -1757,6 +1757,137 @@ describe('cooperative advisory scheduling checkpoints', () => { return run; } + it.each(['refuted', 'prose', 'jsonl', 'jsonl-context', 'restart', 'legacy-restart'] as const)( + 'waits for Lead to decide the proof checkpoint (%s)', async report => { + const { state: initialState, workers, problem, check, controller } = connectionChain(); + let state = initialState; + const producer = peerWorker({ directory, problem, workspace: workers[0].worktree }, 'producer', { role: 'prover' }); + workers.push(producer); + state.workers!.push({ ...producer, phase: 'prepared', turns: 0 }); + const bridge = state.cooperation!.tasks.find(node => node.task.id === 'connection_bridge')!; + bridge.task = { ...bridge.task, ownerId: producer.id, dependsOn: [] }; + state.cooperation!.tasks = state.cooperation!.tasks.filter(node => node.task.id !== 'connection_leaf'); + + const [lead, worker] = workers; + const restart = report === 'restart' || report === 'legacy-restart'; + const saved = path.join(directory, 'connection-wait.json'); + const create = (save?: () => void) => cooperativeResearch({ state, workers, retrievalRoot: directory, + signal: controller.signal, save, + modules: { ...directSolverModules, M2: { ...directSolverModules.M2, check, checkTask: check, closeTask: undefined } } }); + let cooperation = create(() => { + if (restart && !fs.existsSync(saved) && state.cooperation!.deliveries?.some(record => record.kind === 'research')) + writeSolverRunState(saved, state); + }); + const budget = { maxTurns: Infinity, remainingMs: Infinity }; + const consumer = async () => { + const action = await cooperation.next(worker, budget); + if (action?.kind !== 'task' || action.task.id !== 'connection_consumer') + throw new Error('fixture_expected_connection_consumer'); + expect(cooperation.started(worker, action)).toBe(true); + return action; + }; + const checkpoint = async (action: Awaited>, laterFindings = 0) => { + await cooperation.retainContextDraft(worker, action, commitSolverSources(problem, worker.worktree), + report === 'jsonl-context' ? 'context' : 'connection'); + if (laterFindings) { + cooperation.activate(worker, action, async () => {}, async () => {}); + const log = path.join(worker.worktree, assignmentDeliveryFile(action.assignment)); + for (let index = 0; index < laterFindings; index++) { + fs.appendFileSync(log, JSON.stringify({ kind: 'research', finding: { conclusion: 'inconclusive', + needsDecision: true, summary: 'A later advisory finding on the connection, ' + index } }) + '\n'); + } + await cooperation.pulse(worker.id); + cooperation.deactivate(worker); + } + cooperation.interrupted(worker, action); + }; + const inbox = () => leadResearchInputs(state.cooperation!.deliveries ?? [], + new Map(state.cooperation!.tasks.map(node => [node.task.id, node])), state.cooperation!.researchDecisions); + + const first = await consumer(); + const jsonl = report === 'jsonl' || report === 'jsonl-context'; + const laterCount = report === 'refuted' ? 8 : 0; + const value = { conclusion: 'refuted', summary: 'A witness refutes the proposed inference from the recorded premises.' }; + const notes = report === 'prose' ? 'The exact proposed inference and a candidate witness are saved here for review.\n' + : '\x60\x60\x60math-result\n' + JSON.stringify(value) + '\n\x60\x60\x60\n'; + if (jsonl) { + cooperation.activate(worker, first, async () => {}, async () => {}); + fs.appendFileSync(path.join(worker.worktree, assignmentDeliveryFile(first.assignment)), + JSON.stringify({ kind: 'research', finding: { ...value, needsDecision: true } }) + '\n'); + await cooperation.pulse(worker.id); + cooperation.deactivate(worker); + expect(inbox()).toHaveLength(1); + } else fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), notes); + // Fill the Lead inbox's eight-entry view with newer findings from the same + // assignment. They do not change the paused worker's mathematical inputs. + await checkpoint(first, laterCount); + if (report === 'prose') { + expect(inbox()).toHaveLength(0); + await checkpoint(await consumer()); + } + const [finding, ...laterFindings] = inbox(); + expect(laterFindings).toHaveLength(laterCount); + expect(finding.taskId).toBe('connection_consumer'); + expect(JSON.parse(finding.finding!)).toMatchObject({ conclusion: report === 'prose' ? 'inconclusive' : 'refuted', needsDecision: true }); + if (!jsonl) expect(committedSource(lead.worktree, finding.commit!, 'RESEARCH.md')).toBe(notes); + if (!restart) writeSolverRunState(saved, state); + const savedState = readSolverRunState(saved); + const savedConsumer = savedState.cooperation!.tasks.find(node => node.task.id === finding.taskId)!; + expect(savedConsumer.connectionCheckpoint?.leadDeliveryId).toBe(finding.id); + if (restart) { + expect(savedConsumer.status).toBe('running'); + // Reproduce the archive written by earlier versions before the wait was bound. + if (report === 'legacy-restart') delete savedConsumer.connectionCheckpoint; + await cooperation.stop(); + state = savedState; cooperation = create(() => {}); + await cooperation.restore(); + expect(inbox().map(record => record.id)).toEqual([finding.id]); + } + + let redispatched = false; + const resumed = consumer().then(action => { redispatched = true; return action; }); + void resumed.catch(() => {}); + const leadTurn = async () => { + const decision = await cooperation.next(lead, budget); + if (decision?.kind !== 'lead') throw new Error('fixture_expected_lead_decision'); + expect(cooperation.started(lead, decision)).toBe(true); + return decision; + }; + const answer = async (decision: Awaited>, deliveryIds: string[]) => { + fs.writeFileSync(path.join(lead.worktree, 'RESEARCH.md'), '\x60\x60\x60math-plan\n' + JSON.stringify({ + baseVersion: decision.planVersion, upsert: [], summary: 'Reviewed the presented findings.', + researchDecisions: deliveryIds.map(deliveryId => ({ deliveryId, outcome: 'decline', + reason: 'The proposed inference is not needed for the test route.' })), + }) + '\n\x60\x60\x60\n'); + await cooperation.deliver(lead, decision, commitSolverSources(problem, lead.worktree)); + }; + const firstDecision = await leadTurn(); + if (laterCount) { + const shown = laterFindings.map(item => item.id); + expect(cooperation.contextState(firstDecision, lead).leadResearchInputIds).toEqual(shown); + await answer(firstDecision, shown); + expect(state.cooperation!.error).toBeUndefined(); + } else { + fs.writeFileSync(path.join(lead.worktree, 'RESEARCH.md'), 'The checkpoint still needs a decision.\n'); + await cooperation.deliver(lead, firstDecision, commitSolverSources(problem, lead.worktree), true, 'scheduling-checkpoint'); + } + await vi.advanceTimersByTimeAsync(0); + expect(inbox().map(item => item.id)).toEqual([finding.id]); + expect(redispatched).toBe(false); + const decision = await leadTurn(); + expect(cooperation.contextState(decision, lead).leadResearchInputIds).toEqual([finding.id]); + await answer(decision, [finding.id]); + expect(state.cooperation!.error).toBeUndefined(); + const next = await resumed; + expect(next.assignment.assignmentId).toBe(first.assignment.assignmentId); + expect(inbox()).toEqual([]); + await checkpoint(next); + expect(state.cooperation!.deliveries!.filter(record => record.kind === 'research')).toHaveLength(1 + laterFindings.length); + expect(check).not.toHaveBeenCalled(); + expect(state.cooperation!.tasks.find(node => node.task.id === finding.taskId)?.proof).toBeUndefined(); + await cooperation.stop(); + }); + it('lets an unchanged connection checkpoint dispatch its owned transitive leaf with the consumer draft retained', async () => { const { state, workers, problem, check, controller, events, run } = connectionChain(); const held = heldAdvisoryTurns(3, ['connection_consumer', 'connection_leaf']); diff --git a/tests/solverResearchDrafts.test.ts b/tests/solverResearchDrafts.test.ts index b783a8b5..d9569e9c 100644 --- a/tests/solverResearchDrafts.test.ts +++ b/tests/solverResearchDrafts.test.ts @@ -1,7 +1,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { readSolverRunState, type SolverRunState } from '../src/solver/archive'; +import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; import { leadResearchInputs } from '../src/solver/contextCompiler'; import type { CooperativeResearch } from '../src/solver/cooperation'; import { leadWakePending } from '../src/solver/leadWakes'; @@ -10,7 +10,7 @@ import { directSolverModules } from '../src/solver/modules'; import type { ResearchWorker } from '../src/solver/modules/organization'; import { committedSource, commitSolverSources, git, type SolverProblem } from '../src/solver/problem'; import * as problemSource from '../src/solver/problem'; -import { taskVersion, type CooperativeTask } from '../src/solver/tasks'; +import { assignmentDeliveryFile, taskVersion, type CooperativeTask } from '../src/solver/tasks'; import { taskConnectionCheckCurrent } from '../src/solver/taskConnections'; import { TaskTypePreflightCache } from '../src/solver/taskTypePreflight'; import { captureResearchBasis, researchSourceDigest } from '../src/solver/researchRecords'; @@ -36,9 +36,11 @@ describe('isolated advisory research drafts', () => { leanChecks: [{ status: 'passed', path: 'RESEARCH.md', declarations: ['Candidate.probe'] }], lemmaRequests: [{ id: 'bridge', kind: 'lemma', objective: 'Prove the proposed bridge', theoremName: 'Candidate.bridge', type: 'True', proofPath: 'Submission.lean' }] }); - const saveFinding = () => write(peer, finding(), '```lean\nnamespace Candidate\nlemma probe : True := by trivial\nend Candidate\n```\n'); - const create = (current = state) => { + const leanProbe = '```lean\nnamespace Candidate\nlemma probe : True := by trivial\nend Candidate\n```\n'; + const saveFinding = () => write(peer, finding(), leanProbe); + const create = (current = state, save?: (state: SolverRunState) => void) => { const instance = cooperativeResearch({ state: current, workers: [lead, peer, ...inputWorkers], retrievalRoot: directory, + save: () => save?.(current), modules: { ...directSolverModules, M2: { ...directSolverModules.M2, check: async () => { throw new Error('fixture_unexpected_verifier'); }, checkTask: async () => { throw new Error('fixture_unexpected_verifier'); } } } }); @@ -260,7 +262,7 @@ describe('isolated advisory research drafts', () => { const wakes = state.cooperation!.leadWakes!.requested; const resumed = await task(); const reversed = Object.fromEntries(Object.entries(finding()).reverse()); - write(peer, reversed, '```lean\nnamespace Candidate\nlemma probe : True := by trivial\nend Candidate\n```\n'); + write(peer, reversed, leanProbe); fs.writeFileSync(notes(), '# Expanded explanation before the same finding.\n\n' + fs.readFileSync(notes(), 'utf8')); await cooperative.deliver(peer, resumed, commitSolverSources(problem, peer.worktree), true); expect(state.cooperation!.deliveries!.filter(record => record.kind === 'research')).toEqual(previous); @@ -268,6 +270,125 @@ describe('isolated advisory research drafts', () => { expect(node('first_route').status).toBe('pending'); }); + it('ignores a merged research submission ID on replay after restart', async () => { + const snapshot = path.join(directory, 'before-delivery-cursor.json'); + let replay: { key: string; offset: number } | undefined; + cooperative = create(state, current => { + if (replay && current.cooperation?.cursors?.[replay.key] === replay.offset) + writeSolverRunState(snapshot, current); + }); + const action = await task(); + cooperative.activate(peer, action, async () => {}, async () => {}); + const file = assignmentDeliveryFile(action.assignment), log = path.join(peer.worktree, file); + const value = { kind: 'research', finding: { conclusion: 'inconclusive', needsDecision: true, + summary: 'The same boundary finding delivered twice.' } }; + const append = (id: string, finding = value.finding) => fs.appendFileSync(log, JSON.stringify({ ...value, id, finding }) + '\n'); + const published = () => state.cooperation!.deliveries!.filter(record => record.kind === 'research'); + append('first_submission'); + await cooperative.pulse(peer.id); + expect(published()).toHaveLength(1); + const [delivery] = published(); + replay = { key: `${peer.id}/${file}`, offset: fs.statSync(log).size }; + append('merged_submission'); + await cooperative.pulse(peer.id); + expect(published().map(record => record.id)).toEqual([delivery.id]); + + // Recover from the save that preceded advancing past the second JSONL entry. + state = readSolverRunState(snapshot); + expect(state.cooperation!.cursors![replay.key]).toBe(replay.offset); + cooperative = create(); await cooperative.restore(); + const resumed = await task(); + expect(assignmentDeliveryFile(resumed.assignment)).toBe(file); + cooperative.activate(peer, resumed, async () => {}, async () => {}); + const freeze = vi.spyOn(problemSource, 'withSolverWorktree'); + await cooperative.pulse(peer.id); + expect(state.cooperation!.cursors![replay.key]).toBe(fs.statSync(log).size); + + append('merged_submission', { ...value.finding, summary: 'Changed text under the same submission ID.' }); + await cooperative.pulse(peer.id); + expect.soft(freeze).not.toHaveBeenCalled(); + expect(published().map(record => [record.id, record.summary])).toEqual([[delivery.id, value.finding.summary]]); + }); + + it.each([{ needsDecision: true }, {}])('deduplicates a checkpoint finding across both submission paths after restart (%j)', async decision => { + const value = { ...finding(), ...decision }; + const action = await task(); + action.assignment.researchBasis = captureResearchBasis(action.task, { problemReceiptDigest: problem.receiptDigest, + environmentDigest: state.environmentDigest, tasks: state.cooperation!.tasks, + sourceDigest: researchSourceDigest(Object.fromEntries(problem.ownedFiles.map(file => [file, + committedSource(peer.worktree, action.assignment.seedCommit, `${problem.projectRelative}/${file}`)]))) }); + write(peer, value, leanProbe); + const checkpointCommit = commitSolverSources(problem, peer.worktree); + await cooperative.deliver(peer, action, checkpointCommit, true, 'scheduling-checkpoint'); + const published = () => state.cooperation!.deliveries!.filter(record => record.kind === 'research' && record.status !== 'superseded'); + const inbox = () => leadResearchInputs(published(), new Map(state.cooperation!.tasks.map(node => [node.task.id, node])), + state.cooperation!.researchDecisions); + const [checkpoint] = published(); + expect(checkpoint.researchRecord?.complete).toBe(false); + expect(inbox()).toEqual([checkpoint]); + + await restart(); + const resumed = await task(); + expect(resumed.assignment.assignmentId).toBe(action.assignment.assignmentId); + const wakes = state.cooperation!.leadWakes!.requested; + cooperative.activate(peer, resumed, async () => {}, async () => {}); + fs.appendFileSync(path.join(peer.worktree, assignmentDeliveryFile(resumed.assignment)), + JSON.stringify({ kind: 'research', finding: value, commit: checkpointCommit }) + '\n'); + await cooperative.pulse(peer.id); + expect(state.cooperation!.deliveryReceipts ?? []).toEqual([]); + expect(published()).toHaveLength(1); + expect(inbox().map(record => record.id)).toEqual([checkpoint.id]); + expect(state.cooperation!.leadWakes!.requested).toBe(wakes); + expect(node('first_route').status).toBe('running'); + + await cooperative.deliver(peer, resumed, commitSolverSources(problem, peer.worktree)); + expect(node('first_route')).toMatchObject({ status: 'completed', researchCompletion: { complete: true } }); + expect(published()).toHaveLength(1); + expect(published()[0]).toMatchObject({ id: checkpoint.id, findingDigest: checkpoint.findingDigest }); + expect(published()[0].researchRecord).toEqual(node('first_route').researchCompletion); + expect(inbox()).toHaveLength(1); + expect(state.cooperation!.leadWakes!.requested).toBe(wakes); + }); + + it.each(['refuted', 'supporting'] as const)('reuses the explicit %s finding when a later checkpoint requests Lead review', async conclusion => { + const value = { conclusion, summary: 'The exact local case and its probe.', + leanChecks: [{ status: 'passed', path: 'RESEARCH.md', declarations: ['Candidate.probe'] }] }; + const action = await task(); + write(peer, value, leanProbe); + const commit = commitSolverSources(problem, peer.worktree); + const archive = () => state.cooperation!; + const published = () => (archive().deliveries ?? []).filter(record => record.kind === 'research' && record.status !== 'superseded'); + const inbox = () => leadResearchInputs(published(), new Map(archive().tasks.map(node => [node.task.id, node])), + archive().researchDecisions).map(record => record.id); + + cooperative.activate(peer, action, async () => {}, async () => {}); + fs.appendFileSync(path.join(peer.worktree, assignmentDeliveryFile(action.assignment)), + JSON.stringify({ kind: 'research', finding: value, commit }) + '\n'); + await cooperative.pulse(peer.id); + expect(archive().deliveryReceipts ?? []).toEqual([]); + expect(published()).toHaveLength(1); + const { id, finding, findingDigest, commit: publicationCommit } = published()[0]; + expect(inbox()).toEqual(conclusion === 'refuted' ? [id] : []); + const wakes = archive().leadWakes!.requested; + cooperative.deactivate(peer); + + await cooperative.deliver(peer, action, commit, true, 'scheduling-checkpoint'); + expect(published()).toHaveLength(1); + expect(published()[0]).toMatchObject({ id, finding, findingDigest, commit: publicationCommit }); + expect(inbox()).toEqual([id]); + expect(archive().leadWakes!.requested).toBe(wakes + (conclusion === 'supporting' ? 1 : 0)); + expect(node('first_route').status).toBe('pending'); + + await restart(); + expect(inbox()).toEqual([id]); + const resumed = await task(); + const resumedWakes = archive().leadWakes!.requested; + await cooperative.deliver(peer, resumed, commitSolverSources(problem, peer.worktree), true, 'scheduling-checkpoint'); + expect(published()).toHaveLength(1); + expect(inbox()).toEqual([id]); + expect(archive().leadWakes!.requested).toBe(resumedWakes); + }); + it('keeps checkpoint publications scoped and deduplicated through task switches and process recovery', async () => { const value = { summary: 'Exact boundary established; uniform inference remains open.', conclusion: 'inconclusive', remainingObligations: ['Prove the uniform implication or request a narrower typed helper.'] };