diff --git a/docs/usage.md b/docs/usage.md index 1dd55a8b..2ac1b933 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -271,11 +271,11 @@ flowchart LR C -. 诊断反馈 .-> R C -. 诊断反馈 .-> P C -. 诊断反馈 .-> E - C --> V[完整候选的独立审阅] + C --> V[完整候选的只读审阅] V --> A[原题重检与独立评测] ``` -Lead 计入 `--workers` 的总人数。默认配置中,Engineer 持续负责原题,Researcher 处理辅助引理、替代路线和关键猜想;超过四人时增加 Prover,专门领取已明确完整 Lean 类型的辅助引理。完整候选交给符合条件的同伴切换为只读 Reviewer。 +Lead 计入 `--workers` 的总人数。默认配置中,Engineer 持续负责原题,Researcher 处理辅助引理、替代路线和关键猜想;超过四人时增加 Prover,专门领取已明确完整 Lean 类型的辅助引理。 | `--workers` | 角色配置 | | --- | --- | @@ -303,6 +303,8 @@ Lead 的普通规划和初始规划执行 90 秒后收到保存提醒,120 秒 每次普通 Lead 调度都可通过本次上下文提供的专用 JSONL 文件提前发布一个完整计划。后续计划需携带准确的 `dispatchNonce` 和 `baseVersion`;宿主在同一 checkpoint 保存图、交接决策与发布收据,再唤醒等待者。每个 dispatch 只接纳第一条有效完整事件,过期或重复事件不能覆盖人工修改,普通笔记也不会隐式发布计划。最终明确修改的计划仍走正常校验与交付。 +研究交付与在途任务的 `consumerGoalIds` 或直接依赖匹配时,通知会附上简短的发现摘要和剩余义务,供该任务核实和使用。通知沿用交付可见范围,完整内容见 `COOPERATION.json`。 + ### 辅助引理与条件性检查 条件性检查在临时源码投影中将待证引理转换为显式参数,保留未完成义务;依赖闭合后再组合并检查普通证明。局部引理、研究笔记和审阅意见分别记录,最终验收检查全部原题目标。 @@ -321,7 +323,7 @@ Lead 的普通规划和初始规划执行 90 秒后收到保存提醒,120 秒 | Lean-Eval | 执行独立官方比较器,记录比较结果与对应题目身份 | | `--evaluator-command` | 使用指定命令作为最终评测,记录 `official: false`;它会覆盖默认评测器 | -完整候选的模型审阅与 Lean 证据分别保存。局部编译、条件性证明和模型审阅提供各自范围的反馈。 +完整候选进入终审后,宿主优先安排未参与该候选证明的同伴,在新会话中做只读审阅。若存活的同伴都参与了证明,宿主使用新会话审阅并标记 `independent: false`。终审期间暂停派发普通研究,在途研究会保存草稿并让出执行位置。候选失效或终审要求修改时,普通研究可继续派发。模型审阅和 Lean 验收分别保存。 | 输出 | 内容 | | --- | --- | diff --git a/src/solver/archive.ts b/src/solver/archive.ts index 6c1e9876..8d7efaa4 100644 --- a/src/solver/archive.ts +++ b/src/solver/archive.ts @@ -34,7 +34,7 @@ export type DispatchWaitObservation = { endedAt?: number; planVersion?: string; stage: 'm3-no-ready' | 'host-filtered' | 'm5-no-selection' | 'budget-gated' | 'lead-unavailable' | - 'dependency-blocked' | 'dependency-running' | 'route-paused' | 'integration-queue' | 'synchronizing' | 'plan-approval'; + 'dependency-blocked' | 'dependency-running' | 'route-paused' | 'integration-queue' | 'synchronizing' | 'plan-approval' | 'final-review'; gate?: 'time-limit' | 'turn-limit' | 'model-disabled'; candidateCount: number; omittedCandidates: number; @@ -166,7 +166,7 @@ const record = z.record(z.unknown()); const safeCount = count.max(Number.MAX_SAFE_INTEGER); const dispatchWaitObservation = z.object({ observedAt: safeCount, endedAt: safeCount.optional(), planVersion: z.string().optional(), stage: z.enum(['m3-no-ready', 'host-filtered', 'm5-no-selection', 'budget-gated', 'lead-unavailable', - 'dependency-blocked', 'dependency-running', 'route-paused', 'integration-queue', 'synchronizing', 'plan-approval']), + 'dependency-blocked', 'dependency-running', 'route-paused', 'integration-queue', 'synchronizing', 'plan-approval', 'final-review']), gate: z.enum(['time-limit', 'turn-limit', 'model-disabled']).optional(), candidateCount: safeCount, omittedCandidates: safeCount, candidates: z.array(z.object({ taskId: z.string(), taskDigest: z.string(), @@ -412,7 +412,8 @@ const runState = research.extend({ schema: z.literal('deepscientist.math.solver. retiredRoutes: z.array(retiredRouteSchema).optional(), retiredRouteTasks: z.record(z.string()).optional(), proofReadyRecords: z.array(proofReadyRecordSchema).optional(), proofImports: z.array(proofImportRecordSchema).optional(), - landedHelpers: z.array(z.object({ qualifiedName: z.string(), file: z.string(), commit: z.string(), type: z.string() })).optional(), + landedHelpers: z.array(z.object({ qualifiedName: z.string(), file: z.string(), commit: z.string(), type: z.string(), + kind: z.literal('definition').optional(), producer: z.string().optional() })).optional(), proofSearchRecords: z.record(proofSearchRecordSchema).optional(), initialPlanPublication: planPublication.optional(), planPublication: planPublication.optional(), lastLeadPauseInputDigest: z.string().regex(/^[a-f0-9]{64}$/u).optional(), diff --git a/src/solver/automaticExplanations.ts b/src/solver/automaticExplanations.ts index 1002a416..085edc57 100644 --- a/src/solver/automaticExplanations.ts +++ b/src/solver/automaticExplanations.ts @@ -66,6 +66,7 @@ export async function generateSolverExplanations(input: Input, options: Options proofId: `proof_${mathDigest(target.target).slice(0, 32)}`, target: target.target, proofFile: path.join(project, target.proofPath), projectRoot: project, environment, statement: input.problem.contract.informalStatement || null, language: input.language, + outputDelivery: 'file', writer: input.writer, auditors: [1, 2].map(index => ({ ...input.writer, id: `auditor-${index}` })), alignment: INFORMALIZATION_ALIGNMENT, explanationPolicy: INFORMALIZATION_EXPLANATION_POLICY, outlinePolicy: INFORMALIZATION_OUTLINE_POLICY, batching: { maxUnits: 12, maxSourceBytes: 60_000 }, diff --git a/src/solver/cooperation.ts b/src/solver/cooperation.ts index c5957f84..4ac74c4a 100644 --- a/src/solver/cooperation.ts +++ b/src/solver/cooperation.ts @@ -33,7 +33,7 @@ import { TACTIC_BATTERY_TIMEOUT_MS } from './tacticBattery'; import { LIBRARY_APPLICATION_TIMEOUT_MS } from './libraryApplication'; import { knowledgeReferenceCoverage } from './knowledgeUsage'; import { taskTypePreflightEnvironmentIdentity, typeDiagnosticExcerpt, type TaskTypePreflight } from './taskTypePreflight'; -import { assignmentDeliveryFile, isDefinitionTask, isFeasibilityReview, taskGroup, type CooperativeTask, type CooperativeAction, type RouteRecord, type TaskAssignment, type TaskRecord } from './tasks'; +import { assignmentDeliveryFile, isDefinitionTask, isFeasibilityReview, isFinalCandidateReview, taskGroup, type CooperativeTask, type CooperativeAction, type RouteRecord, type TaskAssignment, type TaskRecord } from './tasks'; import { consumeLeadWakes, dropLeadWakes, LEAD_MAX_BACKOFF, leadWakePending, settleLeadWakes } from './leadWakes'; import { idlePeerEpisode, idlePeersAwaitingLead, IDLE_PEER_WAKE_MS, leadInbox, leadInboxBasis, NO_WORK_STAGES, type LeadInboxBasis } from './leadInbox'; import { restoreResidue } from './stateInvariants'; @@ -48,6 +48,7 @@ export { readCooperationPlan } from './cooperationShared'; export type { ReviewRecord, HumanEditRecord, InitialPlanPublication, CooperationState } from './cooperationShared'; const PREEMPTION_MISMATCH_COOLDOWN_MS = 10 * 60_000; +const ordinaryAdvisoryTask = (task: CooperativeTask) => advisory(task) && !isFeasibilityReview(task) && !isFinalCandidateReview(task); /** Lead plans; workers claim distinct ready obligations; only checked source enters the canonical proof. */ export class CooperativeResearch extends CooperationInputs { @@ -165,6 +166,7 @@ export class CooperativeResearch extends CooperationInputs { /** Preview the normal dispatch after releasing this assignment and its route slot. */ proofHandoffTarget(worker: ResearchWorker, action: CooperativeAction): { taskId: string; taskDigest: string; capacity: boolean } | undefined { if (action.kind !== 'task' || action.assignment.workerId !== worker.id || !advisory(action.task) || + this.finalReviewCommit() || Date.now() < (this.preemptionCooldowns.get(worker.id) ?? 0) || !this.current(action) || this.stopping || this.failure || this.input.signal.aborted || !this.liveWorkers.has(this.lead.id) || !this.liveWorkers.has(worker.id) || this.planApprovalPending() || @@ -473,7 +475,8 @@ export class CooperativeResearch extends CooperationInputs { this.statementReviewAllowed(this.node(review.taskId).task, true))); if (this.dispatchBudgetExhausted(budget, modelAllowed)) return this.exhaustedDispatch(budget, modelAllowed, running); if (!running && !this.livePeers.length) return; - if (this.archive.review && ['pending', 'running'].includes(this.archive.review.status)) return this.waitForDispatch(); + if (this.archive.review && ['pending', 'running'].includes(this.archive.review.status) && + (!this.fixedReviewScope || this.finalReviewCommit())) return this.waitForDispatch(); if (this.pendingLeadGuidance().length) return this.leadDecision(worker, head, this.planningInputDigest()); this.wakeForIdlePeers(); const wakes = this.archive.leadWakes!, through = wakes.requested; @@ -742,24 +745,42 @@ export class CooperativeResearch extends CooperationInputs { candidateCount: ranked.length, omittedCandidates: ranked.length - candidates.length, candidates }); } private peerTaskCandidates(tasks: readonly TaskRecord[], groups?: readonly RouteRecord[]) { + const finalReview = this.finalReviewCommit(); const ranked = this.input.modules.M3.ready(tasks, groups); - const ready = ranked.filter(node => this.nextCheckDispatchable(node) && !this.taskDispatchBlock(node)); + const ready = ranked.filter(node => (!finalReview || !ordinaryAdvisoryTask(node.task)) && + this.nextCheckDispatchable(node) && !this.taskDispatchBlock(node)); return { ranked, ready }; } + private finalReviewCommit(): string | undefined { + const review = this.archive.review; + // The persisted record can outlive a changed candidate. The fixed scope binds it to the current source. + return review && review.status !== 'changes_requested' && this.fixedStatementReviewTasks() ? review.commit : undefined; + } + protected override wake() { + super.wake(); + const commit = this.finalReviewCommit(); + if (!commit || this.stopping || this.failure || this.input.signal.aborted) return; + for (const active of this.active.values()) { + const action = active.action; + if (active.requestAdvisoryCheckpoint && !active.cancelled && action.kind === 'task' && + ordinaryAdvisoryTask(action.task) && this.current(action)) active.requestAdvisoryCheckpoint(commit); + } + } private assignPeerTask(ready: readonly TaskRecord[], worker: ResearchWorker, tasks: readonly TaskRecord[], groups?: readonly RouteRecord[], peers = this.allocationPeers, stopped = this.stoppedWorkers) { return this.input.modules.M5.assign(ready, worker, peers, groups, tasks, stopped); } private peerReview(worker: ResearchWorker, release?: { outgoing: TaskRecord; tasks: readonly TaskRecord[]; groups?: readonly RouteRecord[] }) { - if (this.reviewer(release?.outgoing)?.id !== worker.id) return; const statement = this.archive.statementReviews?.find(item => ['pending', 'translated'].includes(item.status) && this.statementReviewAllowed(this.node(item.taskId).task, true, release?.tasks, release?.groups) && ![...this.active.values()].some(active => isStatementAction(active.action) && active.action.reviewId === item.id)); - if (statement) return { statement }; + if (statement && this.reviewer(release?.outgoing)?.id === worker.id) return { statement }; const review = this.archive.review; - if (review?.status === 'pending' && !this.candidateSynchronizationBlocked()) return { review }; + if (review?.status === 'pending' && (!this.fixedReviewScope || this.fixedStatementReviewTasks()) && + !this.candidateSynchronizationBlocked() && + this.reviewer(release?.outgoing, review.producerIds)?.id === worker.id) return { review }; } private async nextPeer(worker: ResearchWorker, budget: DispatchBudget, modelAllowed: boolean): Promise { if (budget.remainingMs <= 0 || !modelAllowed || this.input.state.turns >= budget.maxTurns) { @@ -790,9 +811,10 @@ export class CooperativeResearch extends CooperationInputs { const notes = path.join(worker.worktree, 'RESEARCH.md'); if (fs.existsSync(notes)) fs.writeFileSync(notes, fs.readFileSync(notes, 'utf8').replace(/```(?:math|math-review)\s*\n[\s\S]*?\n```/gu, '')); review.workerId = worker.id; review.status = 'running'; review.assignmentId = crypto.randomUUID(); - this.input.emit('review_assigned', { workerId: worker.id, commit: review.commit, role: 'reviewer' }); + review.independent = !review.producerIds?.includes(worker.id); + this.input.emit('review_assigned', { workerId: worker.id, commit: review.commit, role: 'reviewer', independent: review.independent }); this.changed(); return { kind: 'review', seedCommit: review.commit, sourceDigest: review.sourceDigest, - assignmentId: review.assignmentId }; + assignmentId: review.assignmentId, ...(review.independent ? {} : { independent: false }) }; } this.refreshConnectionCheckpoints(); const { ranked, ready } = this.peerTaskCandidates(this.archive.tasks, this.archive.groups); @@ -814,6 +836,10 @@ export class CooperativeResearch extends CooperationInputs { this.wake(); } } + if (this.finalReviewCommit()) { + this.recordDispatchWait(worker, { stage: 'final-review', candidateCount: 0, omittedCandidates: 0, candidates: [] }); + return this.waitForDispatch(); + } this.recordTaskWait(worker, ranked, ready); const observedRevision = this.dispatchRevision; if (await this.requestCapacityExploration(worker, budget, ready)) return RETRY_DISPATCH; @@ -836,6 +862,7 @@ export class CooperativeResearch extends CooperationInputs { const previousAssignment = node.assignment; const restored = await this.restoreResearchDraft(worker, node); if (this.synchronizationBlocked(node.task) || !this.archive.tasks.includes(node) || node.status !== 'pending' || + this.finalReviewCommit() && ordinaryAdvisoryTask(node.task) || !restored && node.assignment !== previousAssignment || assessTaskResponsibility(node, worker, this.responsibility).kind !== 'matches' || !taskCanStart(node.task, this.archive.tasks, this.archive.groups) || !routeAllowsTask(node.task, this.archive.tasks, this.archive.groups)) return RETRY_DISPATCH; @@ -1222,6 +1249,7 @@ export class CooperativeResearch extends CooperationInputs { this.input.emit('review_requested', { commit: check.commit }); } const configured = this.archive.tasks.filter(node => node.task.statementReview), used = new Set(); + const referencedDeclarations = new Set(); const problem = this.input.state.problem; let complete = hasFreshSolverCheck(check) && proofReceiptsMatch(check.verification, check.commit, problem.targets.map(target => ({ proofPath: target.proofPath, theoremName: target.theoremName, @@ -1233,7 +1261,15 @@ export class CooperativeResearch extends CooperationInputs { { name: target.theoremName, file: target.proofPath }, receipt.declarationReferences, this.input.state.environmentDigest); if (!references) { complete = false; break; } for (const reference of attributeTaskReferences(references, this.archive.tasks)) used.add(reference.taskId); + for (const reference of [...references.statement, ...references.proof]) + referencedDeclarations.add(reference.file + '\0' + reference.name); } + const producers = new Set(this.archive.tasks.flatMap(node => node.status === 'integrated' && node.assignment && + (node.task.kind === 'goal' || used.has(node.task.id) || !complete && node.task.kind === 'lemma') + ? [node.assignment.workerId] : [])); + for (const helper of this.archive.landedHelpers ?? []) if (helper.producer && + (!complete || referencedDeclarations.has(helper.file + '\0' + helper.qualifiedName))) producers.add(helper.producer); + this.archive.review.producerIds = [...producers].sort(); const required = new Map(configured.filter(node => !complete || node.task.kind === 'goal' || used.has(node.task.id)) .map(node => [node.task.id, digest(node.task)])); this.fixedReviewScope = { review: this.archive.review, commit: check.commit, sourceDigest: check.sourceDigest, @@ -1482,7 +1518,7 @@ export class CooperativeResearch extends CooperationInputs { await this.retainGuidanceDecisions(worker, action, decisions); } async deliver(worker: ResearchWorker, action: CooperativeAction, commit: string, recovering = false, - recoveryKind: 'checkpoint' | 'request-failure' | 'scheduling-checkpoint' | 'proof-handoff' = 'checkpoint'): Promise<{ check?: ProofCheck; checkWhole: boolean; savedPlan?: boolean }> { + recoveryKind: 'checkpoint' | 'request-failure' | 'scheduling-checkpoint' | 'proof-handoff' | 'final-review-handoff' = 'checkpoint'): Promise<{ check?: ProofCheck; checkWhole: boolean; savedPlan?: boolean }> { if (isStatementAction(action)) return this.deliverStatement(worker, action); // Optional handling decisions are metadata; malformed/forged ones cannot change mathematical delivery acceptance. let response: any; @@ -1506,7 +1542,7 @@ export class CooperativeResearch extends CooperationInputs { const details = deliveryDetails(result); review.status = status; review.summary = details.summary; evidenceRefs = details.evidenceRefs; - this.input.emit('review_completed', { commit: review.commit, verdict: review.status, workerId: worker.id }); + this.input.emit('review_completed', { commit: review.commit, verdict: review.status, workerId: worker.id, independent: review.independent }); } catch (error) { review.status = 'changes_requested'; review.summary = error instanceof Error ? error.message : 'math_review_failed'; } @@ -1521,7 +1557,8 @@ export class CooperativeResearch extends CooperationInputs { return { checkWhole: true }; } if (action.kind !== 'task') { - const pending = this.deliverLead(worker, action, commit, recovering, recoveryKind === 'proof-handoff' ? 'checkpoint' : recoveryKind); + const pending = this.deliverLead(worker, action, commit, recovering, + recoveryKind === 'proof-handoff' || recoveryKind === 'final-review-handoff' ? 'checkpoint' : recoveryKind); this.leadDeliveries.add(pending); this.refreshPlanApproval(); try { return await pending; } finally { this.leadDeliveries.delete(pending); this.wake(); } @@ -1540,8 +1577,9 @@ export class CooperativeResearch extends CooperationInputs { if (advisory(node.task)) { if (recovering) { this.preserveResearchDraft(worker, action, commit, artifacts); - if (recoveryKind === 'checkpoint' || recoveryKind === 'scheduling-checkpoint' || recoveryKind === 'proof-handoff') - await this.researchCheckpoint(worker, action, commit, recoveryKind !== 'proof-handoff'); + if (recoveryKind !== 'request-failure') + await this.researchCheckpoint(worker, action, commit, + recoveryKind !== 'proof-handoff' && recoveryKind !== 'final-review-handoff'); else this.interrupted(worker, action); return { checkWhole: false }; } @@ -1688,10 +1726,13 @@ export class CooperativeResearch extends CooperationInputs { this.changed(); } else this.interrupted(worker, action); } - private reviewer(releasing?: TaskRecord): ResearchWorker | undefined { + private reviewer(releasing?: TaskRecord, producerIds?: readonly string[]): ResearchWorker | undefined { const preparing = new Set([...this.preparingTaskTypes.values()].map(item => item.workerId)); for (const publication of this.proofPublications.values()) preparing.add(publication.workerId); - const available = this.livePeers.filter(worker => (!this.active.has(worker.id) || releasing?.assignment?.workerId === worker.id) && + const peers = this.livePeers; + const independent = peers.filter(worker => !producerIds?.includes(worker.id)); + // Wait for an independent peer to finish its current work. A team without one can still review in a fresh session. + const available = (independent.length ? independent : peers).filter(worker => (!this.active.has(worker.id) || releasing?.assignment?.workerId === worker.id) && !this.workerCoolingDown(worker.id) && !preparing.has(worker.id) && !(this.archive.review?.status === 'running' && this.archive.review.workerId === worker.id) && @@ -1706,6 +1747,8 @@ export class CooperativeResearch extends CooperationInputs { if (this.failure || this.stopping || !this.liveWorkers.has(worker.id) || !this.liveWorkers.has(this.lead.id)) return false; if (this.refreshFeasibilityAssignments()) this.changed(); if (!this.current(action)) return false; + if (action.kind === 'task' && ordinaryAdvisoryTask(action.task) && this.finalReviewCommit()) return false; + if (action.kind === 'review' && this.fixedReviewScope && !this.fixedStatementReviewTasks()) return false; if (action.kind === 'task' && action.assignment.workerId !== worker.id) throw new Error('math_task_assignment_invalid'); if (action.kind === 'review' && this.archive.review?.workerId !== worker.id) throw new Error('math_review_assignment_invalid'); const inboxBasis = action.kind === 'lead' ? this.pendingLeadInboxBases.get(action) : undefined; diff --git a/src/solver/cooperationCore.ts b/src/solver/cooperationCore.ts index 4b818e83..d2091dcd 100644 --- a/src/solver/cooperationCore.ts +++ b/src/solver/cooperationCore.ts @@ -88,7 +88,7 @@ export abstract class CooperationCore { protected planSynchronizations = new Set>(); protected leadDeliveries = new Set>(); protected active = new Map Promise; notify: (message: string, options?: { requireTurn?: boolean; mode?: 'advisory' }) => Promise; - requestReady?: () => Promise; cancelled?: boolean }>(); + requestReady?: () => Promise; requestAdvisoryCheckpoint?: (commit: string) => void; cancelled?: boolean }>(); private freshProofReady = new WeakMap(); protected notifications = new Set>(); private deliveryReceiptNotifications = new Set(); @@ -952,8 +952,8 @@ export abstract class CooperationCore { this.freshProofReady.delete(action); this.changed(); } activate(worker: ResearchWorker, action: CooperativeAction, interrupt: () => Promise, notify: (message: string, options?: { requireTurn?: boolean; mode?: 'advisory' }) => Promise, - requestReady?: () => Promise) { - this.active.set(worker.id, { action, interrupt, notify, requestReady }); this.changed(); + requestReady?: () => Promise, requestAdvisoryCheckpoint?: (commit: string) => void) { + this.active.set(worker.id, { action, interrupt, notify, requestReady, requestAdvisoryCheckpoint }); this.changed(); } deactivate(worker: ResearchWorker) { this.active.delete(worker.id); this.changed(); } protected nextCheckDispatchable(node: TaskRecord) { @@ -1013,7 +1013,14 @@ export abstract class CooperationCore { if (isStatementAction(active.action)) continue; const task = active.action.kind === 'task' ? active.action.task : undefined; if (task && record.taskId && !this.deliveryVisible(record, task, versions)) continue; - const notice = `Cooperation update: ${record.kind} ${record.id}, task ${record.taskId ?? 'original'}, status ${record.status}. Read COOPERATION.json for peer state and current-version references; use M4 to choose relevant material. This notification grants no proof acceptance.`; + const source = record.taskId && versions.get(record.taskId)?.task; + const forConsumer = task && source && !active.cancelled && record.kind === 'research' && + (record.status === 'advisory' || record.status === 'conditional') && record.summary.trim() && + (source.consumerGoalIds?.includes(task.id) || task.dependsOn.includes(source.id)) && this.current(active.action); + const update = `Cooperation update: ${record.kind} ${record.id}, task ${record.taskId ?? 'original'}, status ${record.status}. Read COOPERATION.json for peer state and current-version references; use M4 to choose relevant material. This notification grants no proof acceptance.`; + const notice = forConsumer ? update + '\nAdvisory finding for your current task (verify before using): ' + + JSON.stringify({ summary: bounded(record.summary, 1800), remainingObligations: record.remainingObligations.slice(0, 3) + .map(obligation => bounded(obligation, 280)) }) : update; const pending = active.notify(notice, { mode: 'advisory' }).catch(() => { this.input.emit('notification_deferred', { workerId: id, deliveryId: record.id }); }); this.notifications.add(pending); void pending.finally(() => this.notifications.delete(pending)); } diff --git a/src/solver/cooperationIntegration.ts b/src/solver/cooperationIntegration.ts index ce8dbd6f..29994747 100644 --- a/src/solver/cooperationIntegration.ts +++ b/src/solver/cooperationIntegration.ts @@ -65,7 +65,7 @@ export abstract class CooperationIntegration extends CooperationTaskProofs { if (!result.helpers.length || !result.helpers.every(helper => eligible({ file: helper.file, name: helper.qualifiedName }))) return; this.pin(result.commit); this.archive.canonicalCommit = result.commit; - (this.archive.landedHelpers ??= []).push(...result.helpers); + (this.archive.landedHelpers ??= []).push(...result.helpers.map(helper => ({ ...helper, producer: worker.id }))); this.changed(); this.input.emit('incremental_helpers_landed', { workerId: worker.id, taskId: action.task.id, commit: result.commit, declarations: result.helpers.map(helper => helper.qualifiedName), summary }); diff --git a/src/solver/cooperationShared.ts b/src/solver/cooperationShared.ts index 1c4f45cb..d7f84f81 100644 --- a/src/solver/cooperationShared.ts +++ b/src/solver/cooperationShared.ts @@ -63,7 +63,7 @@ export function isTaskSourceRepairFeedback(feedback: string): boolean { } export type ReviewRecord = { commit: string; sourceDigest: string; status: 'pending' | 'running' | 'accepted' | 'changes_requested'; - workerId?: string; assignmentId?: string; summary?: string }; + producerIds?: string[]; independent?: boolean; workerId?: string; assignmentId?: string; summary?: string }; export type HumanEditRecord = { id: string; status: 'received' | 'applied' | 'rejected'; reason?: string; receivedAt?: number; appliedAt?: number; baseVersion?: string; planVersion?: string; affectedTasks?: string[]; pendingSync?: boolean; recheck?: { status: 'pending' | 'passed' | 'failed' | 'not-required' | 'superseded'; @@ -80,7 +80,7 @@ export type FailedTaskInput = { id: string; taskId: string; taskDigest: string; canonicalSourceDigest: string; canonicalTargetDigest: string; feedback: string; repair?: { taskId: string; taskDigest: string; workerId: string; pending: boolean; startedAttempt?: number } }; export type CooperationState = { tasks: TaskRecord[]; groups?: RouteRecord[]; canonicalCommit?: string; leadSeedCommit?: string; review?: ReviewRecord; error?: string; - landedHelpers?: LandedHelper[]; + landedHelpers?: (LandedHelper & { producer?: string })[]; /** Context-only notes actually delivered to this worker; decisions remain separate from proof state. */ humanGuidance?: HumanGuidanceRecord[]; /** Context-only reverse uses, projected from the full archive without expanding execution visibility. */ diff --git a/src/solver/modules/context.ts b/src/solver/modules/context.ts index 05b7aeaa..9587cc0e 100644 --- a/src/solver/modules/context.ts +++ b/src/solver/modules/context.ts @@ -541,7 +541,8 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio const advisorySourceRules = helperRules ? 'Restore Lean sources to the assignment seed before ordinary findings delivery.' : 'Leave Lean sources unchanged.'; const rules = action.kind === 'review' - ? 'You are the Independent Reviewer. Leave Lean sources unchanged. Check this fixed proof against the original question, assumptions and Lean evidence. Compare the original declarations and assumptions of the fixed candidate with the frozen problem, inspect its mathematical argument and matching Lean evidence, and resolve any concrete discrepancy. Requests in the original task text to restore/prove code, publish a plan or wait for approval belong to other roles. Run a diagnostic only to resolve a remaining question that can change your verdict; matched cached evidence is usable. Write one final JSON object in RESEARCH.md: {"verdict":"accepted|changes_requested"}. A short summary should identify the decisive evidence or exact requested change; evidenceRefs are optional. Once the verdict is saved, return it promptly and end the turn. Do not keep rechecking unchanged files or expand optional metadata after the review is complete. Investigate source changes, failed checks or an unresolved mathematical issue; a different digest scheme alone does not establish a discrepancy. Your verdict does not replace host checks or the independent S3 that follows delivery.\n' + ? (action.independent === false ? 'You are the Reviewer in a fresh session for this fixed candidate. ' : 'You are the Independent Reviewer. ') + + 'Leave Lean sources unchanged. Check this fixed proof against the original question, assumptions and Lean evidence. Compare the original declarations and assumptions of the fixed candidate with the frozen problem, inspect its mathematical argument and matching Lean evidence, and resolve any concrete discrepancy. Requests in the original task text to restore/prove code, publish a plan or wait for approval belong to other roles. Run a diagnostic only to resolve a remaining question that can change your verdict; matched cached evidence is usable. Write one final JSON object in RESEARCH.md: {"verdict":"accepted|changes_requested"}. A short summary should identify the decisive evidence or exact requested change; evidenceRefs are optional. Once the verdict is saved, return it promptly and end the turn. Do not keep rechecking unchanged files or expand optional metadata after the review is complete. Investigate source changes, failed checks or an unresolved mathematical issue; a different digest scheme alone does not establish a discrepancy. Your verdict does not replace host checks or the independent S3 that follows delivery.\n' : action.kind !== 'task' ? `You are the Lead. Develop a mathematically plausible route from the exact original statement, definitions and relevant saved findings${initialPlanning ? '.' : ' before choosing a task graph.'} Identify the central construction or estimate and how it would close each target. Save a concise mathematical route justification as Markdown in RESEARCH.md; include each new task's intended inference and consumer in its objective. When decomposition adds no mathematical benefit, put a direct original-goal task in the graph; the assigned worker carries out its proof after any required host approval. Delegate a specific uncertain inference as research instead of inventing a helper proposition. Return the plan without running Lean diagnostics; leave Lean sources unchanged during planning. Use this plan schema for the delivery-log event, or for a math-plan JSON fence in RESEARCH.md when returning without publication: {"tasks":[{"id":"helper","kind":"lemma","objective":"...","proofPath":${JSON.stringify(proofFiles[0])},"theoremName":"Namespace.helper","type":"∀ (P : Prop), P → P"},{"id":"goal","kind":"goal","objective":"...","theoremName":"Original.target","dependsOn":["helper"]}]}. Include every original target once. This example shows the task graph schema only; include every decision field required by current Lead decision requirements in that same JSON object. Replace its names, objectives and sample type with actual tasks and full closed Lean types, including all parameters and hypotheses. Never copy placeholder types. If no exact helper proposition is known, use an untyped research/sketch task. Choose proofPath from ${JSON.stringify(proofFiles)}${proofFiles.length < leanFiles.length ? '; workers generate Submission/Certificates modules and import them from these files' : ''}${theoryPlanning}; goals infer it from theoremName, and lemmas may omit it only when one Lean file is owned. Use lemma tasks whenever workers should save proofs; research/sketch tasks without an exact typed target only return advisory findings and restore temporary probes. Typed research tasks are normalized to lemma tasks. dependsOn defaults to []; revision to 0. Keep accepted task definitions stable; record progress in notes rather than rewriting objectives, which invalidates their checked deliveries. Revise a mathematical contract to change a route; changing only prose or revision does not resolve a recorded blocker. conditional:true allows fixed typed lemma premises. statementReview:true with informalStatement requests meaning review. Optional blueprint fields informalProof (the intended argument in at most 2000 characters) and citations (up to 8 short source references such as "Bhargava–Hanke 2005, Thm 2") guide the assigned worker; they never change the task contract or act as premises. A new concept is a lemma task with declaration:"definition" and its Lean type (e.g. "ℕ → ℕ → Prop"); put its intended meaning in objective, and list it in the dependsOn of lemmas whose types mention it. Consumers wait for its checked body. Pair each definition with a typed sanity lemma in the same proofPath that pins its intended meaning on a characterizing or small case, so a vacuous or mistaken body fails before consumers rely on it. Optional groups set ownership, sharing and budgets.\n` : ['research', 'sketch'].includes(action.task.kind) diff --git a/src/solver/modules/moduleIdentity.ts b/src/solver/modules/moduleIdentity.ts index 7d5da1e6..0d9f2015 100644 --- a/src/solver/modules/moduleIdentity.ts +++ b/src/solver/modules/moduleIdentity.ts @@ -7,11 +7,11 @@ export type SolverModuleIdentity = { id: string; versions: Record boolean) | undefined; let softSliceAtModelBoundary: (() => boolean) | undefined; let softSliceCheckpoint = false; @@ -461,12 +462,13 @@ export async function runResearchWorkers(input: { if (!advisoryTurn || previous?.scope !== advisoryTurn.scope) return; const contentDigest = advisoryContentDigest(); const progress = contentDigest !== undefined && contentDigest !== advisoryTurn.contentDigest; - const noProgressStreak = completed || progress ? 0 : checkpoint && !proofHandoffCheckpoint + const noProgressStreak = completed || progress ? 0 : checkpoint && !proofHandoffCheckpoint && !finalReviewHandoffCheckpoint ? Math.min(Number.MAX_SAFE_INTEGER, previous.noProgressStreak + 1) : previous.noProgressStreak; rememberAdvisoryCheckpoint({ scope: previous.scope, noProgressStreak, contentDigest: contentDigest ?? previous.contentDigest, inputDigest: advisoryTurn.inputDigest }); if (checkpoint) emit('cooperative_checkpoint_saved', { noProgressStreak, progress, - protected: false, ...(proofHandoffCheckpoint ? { reason: 'proof-handoff' } : {}) }); + protected: false, ...(proofHandoffCheckpoint ? { reason: 'proof-handoff' } : + finalReviewHandoffCheckpoint ? { reason: 'final-review-handoff' } : {}) }); save(); }; const modelTurn = async (run: (started: (turnId: string) => void) => Promise, @@ -486,6 +488,7 @@ export async function runResearchWorkers(input: { planningCheckpoint = false; cooperativeCheckpoint = false; proofHandoffCheckpoint = false; + finalReviewHandoffCheckpoint = false; contextSchedulingCheckpoint = false; softSliceCheckpoint = false; advisoryTurn = undefined; @@ -533,6 +536,7 @@ export async function runResearchWorkers(input: { let noticeDelivery: 'unavailable' | 'pending' | 'delivered' | 'failed' = 'unavailable'; let planningCommands = 0; let requestedProof: (NonNullable> & { turnId: string }) | undefined; + let requestedFinalReview: string | undefined; let proofNoticeDelivered = false, handoffAtBoundary = false; let afterNotice: ((delivered: boolean) => void) | undefined; const live = () => !finished && !signal.aborted && session === activeSession; @@ -704,7 +708,12 @@ export async function runResearchWorkers(input: { interruptTimer ??= setTimeout(closeStalledTurn, advisoryInterruptGraceMs); interruptTimer.unref(); try { await activeSession.interrupt(); } catch { closeStalledTurn(); } - }); + }, + researchAssignment && (commit => { + if (requestedFinalReview || !current() || checkpointRequested || readyRequested || stopRequested) return; + requestedFinalReview = commit; + scheduleSlice?.(); + })); const started = (turnId: string) => { usage.turnStarted(turnId); onStarted(turnId); @@ -821,8 +830,10 @@ export async function runResearchWorkers(input: { if (researchAssignment && !researchHandoffNotes() && current() && !checkpointRequested && !readyRequested) emit('research_checkpoint_missing_notes', { taskId: researchAssignment.task.id, assignmentId: researchAssignment.assignment.assignmentId }); - interruptForCheckpoint('cooperative_checkpoint_interrupted', - { turnId, checkpointAfterMs, noProgressStreak, protected: false }); + if (interruptForCheckpoint('cooperative_checkpoint_interrupted', + { turnId, checkpointAfterMs, noProgressStreak, protected: false })) { + finalReviewHandoffCheckpoint = requestedFinalReview !== undefined; + } }; // Interrupting a streaming request discards its unfinished reasoning and tool call, and research whose every // cut lands mid-request saves nothing and is parked as unchanged. A slice cut (initial plan, revision or @@ -931,6 +942,12 @@ export async function runResearchWorkers(input: { }; scheduleSlice = () => { if (!current() || compactionStartedAt !== undefined || checkpointRequested || readyRequested) return; + if (requestedFinalReview) { + clearTimeout(noticeTimer); clearTimeout(checkpointTimer); clearTimeout(firstActivityTimer); + sendNotice(); + endSlice(); + return; + } // The advisory clock measures mathematical work, not provider latency. Until the model // produces its first item the turn is held open, bounded only by the silent-turn cap. if (!clockArmed) { @@ -1107,6 +1124,7 @@ export async function runResearchWorkers(input: { const beginTurn = async (currentContext: ContextBundle, assignment?: CooperativeAction, operation: ResearchOperation = 'direct') => { access.assertHarnessCurrent?.(); usage.resetTurn(); planningCheckpoint = false; cooperativeCheckpoint = false; proofHandoffCheckpoint = false; + finalReviewHandoffCheckpoint = false; rebuildContext = false; while ((pendingTurn = waitForTurn())) await pendingTurn; if (assignment && !cooperation!.current(assignment)) return false; @@ -1472,8 +1490,10 @@ export async function runResearchWorkers(input: { const versionChanged = assignment.kind === 'task' && record.sessionTaskId === assignment.task.id && record.sessionTaskVersion && record.sessionTaskVersion !== assignment.assignment.taskDigest; const sessionAssignmentId = assignment.kind === 'task' - ? assignment.assignment.assignmentId ?? `legacy-task:${assignment.assignment.seedCommit}` : undefined; - const reviewAssignmentChanged = taskReview && record.sessionAssignmentId !== sessionAssignmentId; + ? assignment.assignment.assignmentId ?? `legacy-task:${assignment.assignment.seedCommit}` + : assignment.kind === 'review' ? assignment.assignmentId ?? `legacy-review:${assignment.seedCommit}` : undefined; + const reviewAssignmentChanged = (taskReview || assignment.kind === 'review' && record.sessionRole === 'reviewer') && + record.sessionAssignmentId !== sessionAssignmentId; const reviewTargetChanged = (taskReview || record.sessionRole === 'reviewer') && (record.sessionTaskId !== (assignment.kind === 'task' ? assignment.task.id : undefined) || versionChanged); const taskChanged = assignment.kind === 'task' && record.sessionTaskId && @@ -1748,6 +1768,7 @@ export async function runResearchWorkers(input: { softSliceCheckpoint ? { reason: 'math_soft_slice_checkpoint' } : contextSchedulingCheckpoint ? { reason: 'math_context_scheduling_checkpoint' } : proofHandoffCheckpoint ? { reason: 'math_proof_handoff_checkpoint' } : + finalReviewHandoffCheckpoint ? { reason: 'math_final_review_handoff_checkpoint' } : cooperativeCheckpoint ? { reason: 'math_cooperative_scheduling_checkpoint' } : {}) }); if (turn === 'failed') emit('turn_failed', { reason: researchFailureReason(turnError), ...(diagnostic ? { diagnostic } : {}) }); const sourceError = sourceFeedback(); @@ -1823,6 +1844,7 @@ export async function runResearchWorkers(input: { recordAdvisoryOutput(turn === 'checkpoint'); const deliver = () => cooperation.deliver(worker, assignment, commit, turn !== 'completed', turn === 'failed' ? 'request-failure' : proofHandoffCheckpoint ? 'proof-handoff' : + finalReviewHandoffCheckpoint ? 'final-review-handoff' : cooperativeCheckpoint ? 'scheduling-checkpoint' : 'checkpoint'); const delivery = assignment.kind === 'task' || assignment.kind === 'lead' ? await deliver() : await exclusiveCheck(deliver); if (assignment.kind === 'lead' && turn === 'checkpoint') await cooperation.startInitialTasks(); diff --git a/src/solver/run.ts b/src/solver/run.ts index c05017c5..137c8628 100644 --- a/src/solver/run.ts +++ b/src/solver/run.ts @@ -376,7 +376,8 @@ export async function runSolver(args: string[], root: string, customModules?: So try { await disposeProofEnvironment(); await generateSolverExplanations({ problem: state.problem, worktree, directory, root, buildManifest: buildFile, - language, writer: { model: state.model, effort: state.effort, profile, executable, + language, writer: { model: state.model, effort: state.effort, + profile: agentHarness?.profile ?? profile, executable: agentHarness?.executable ?? executable, ...(agentHarness ? { agentHarness } : {}) }, env: explanationEnv, signal, onEvent: emit, onUpdate: summary => { lease.assertOwned(); result.explanations = summary; writeMathJsonDurable(output, result); } }); diff --git a/src/solver/tasks.ts b/src/solver/tasks.ts index 489a389a..a02c57bd 100644 --- a/src/solver/tasks.ts +++ b/src/solver/tasks.ts @@ -73,7 +73,8 @@ export type CooperativeAction = { kind: 'lead' | 'assemble'; seedCommit: string; planNonce?: string; /** Stable mathematical responsibility, independent of graph presentation. */ responsibilityDigest?: string; } | - { kind: 'review'; seedCommit: string; sourceDigest: string; assignmentId?: string } | { kind: 'task'; assignment: TaskAssignment; task: CooperativeTask } | StatementAction; + { kind: 'review'; seedCommit: string; sourceDigest: string; assignmentId?: string; independent?: false } | + { kind: 'task'; assignment: TaskAssignment; task: CooperativeTask } | StatementAction; export const taskVersion = (task: CooperativeTask) => { const { status: _status, ownerId: _owner, preferredOwnerId: _preferredOwner, statementReview: _review, informalStatement: _intent, diff --git a/tests/solver.test.ts b/tests/solver.test.ts index 1f6eeb3a..99ec9e0c 100644 --- a/tests/solver.test.ts +++ b/tests/solver.test.ts @@ -229,7 +229,9 @@ describe('isolated solver and host acceptance', () => { if (id === 'codex') { const profile = path.join(directory, 'codex-profile'); fs.mkdirSync(profile); fs.writeFileSync(path.join(profile, 'config.toml'), 'model="fixture"\n'); - flags = ['--harness', id, '--harness-profile', profile, '--harness-executable', '/usr/bin/true', '--model', 'fixture']; + const executable = path.join(directory, 'codex'); + fs.symlinkSync('/usr/bin/true', executable); + flags = ['--harness', id, '--harness-profile', profile, '--harness-executable', executable, '--model', 'fixture']; } else flags = workflowHarnessFixture(directory, id).flags; const modules = { ...directSolverModules, M1: { ...directSolverModules.M1, open: async (options: MathAgentOptions) => host.createSession(options) } }; @@ -245,7 +247,9 @@ describe('isolated solver and host acceptance', () => { host.createSession.mockClear(); host.explain.mockClear(); expect(await runSolver([...selected, '--resume'], directory, modules)).toBe(0); expect(host.createSession).not.toHaveBeenCalled(); - expect(host.explain.mock.calls[0][0].writer.agentHarness).toEqual(binding); + expect(host.explain.mock.calls[0][0].writer).toMatchObject({ + profile: binding.profile, executable: binding.executable, agentHarness: binding, + }); }); it('keeps proof acceptance when explanation generation fails and resumes only explanation work', async () => { diff --git a/tests/solverAutomaticExplanations.test.ts b/tests/solverAutomaticExplanations.test.ts index c8f28710..008b3e9f 100644 --- a/tests/solverAutomaticExplanations.test.ts +++ b/tests/solverAutomaticExplanations.test.ts @@ -3,7 +3,8 @@ import path from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { getLeanTaskEnvironment } from '../src/math/leanTaskEnvironment'; import { INFORMALIZATION_ALIGNMENT, INFORMALIZATION_EXPLANATION_POLICY, INFORMALIZATION_OUTLINE_POLICY, - readInformalizationRequest } from '../src/math/informalization'; + prepareInformalization, readInformalizationRequest } from '../src/math/informalization'; +import { mathDigest } from '../src/math/mathRuntimeIo'; import { generateSolverExplanations, type SolverExplanations } from '../src/solver/automaticExplanations'; import type { SolverProblem } from '../src/solver/problem'; import { informalizationFixture, PROOF_SOURCE, presetAuthor } from './helpers/informalizationFixture'; @@ -42,7 +43,7 @@ describe('automatic solver explanations', () => { expect(f.run).toHaveBeenCalledTimes(2); for (const item of result.targets) { const { request, sources } = readInformalizationRequest(item.directory); - expect(request).toMatchObject({ target: item.target, language: 'zh', environment: 'standard', writer: presetAuthor, + expect(request).toMatchObject({ target: item.target, language: 'zh', environment: 'standard', writer: presetAuthor, outputDelivery: 'file', alignment: INFORMALIZATION_ALIGNMENT, explanationPolicy: INFORMALIZATION_EXPLANATION_POLICY, outlinePolicy: INFORMALIZATION_OUTLINE_POLICY, auditors: [{ id: 'auditor-1' }, { id: 'auditor-2' }] }); expect(sources.map(source => source.module)).toEqual(['Lib', 'Proof']); @@ -63,10 +64,17 @@ describe('automatic solver explanations', () => { expect(JSON.stringify(result)).not.toContain('secret'); }); - it('reuses each frozen request on resume and keeps the same explanation directories', async () => { + it('reuses frozen requests on resume, including requests with the previous native delivery', async () => { const f = fixture(); - f.run.mockResolvedValueOnce({ status: 'stopped' } as never); + const directory = path.join(f.input.directory, 'explanations', 'zh'); + const previousTarget = f.input.problem.targets[0]!; + const previous = path.join(directory, mathDigest(`${previousTarget.proofPath}\n${previousTarget.theoremName}`)); + fs.mkdirSync(directory, { recursive: true }); + prepareInformalization(previous, { ...f.preparation, target: previousTarget.theoremName, + statement: f.input.problem.contract.informalStatement, outputDelivery: 'native-schema' }); const first = await generateSolverExplanations(f.input, { run: f.run }); + expect(first.status).toBe('approved'); + expect(first.targets.map(item => readInformalizationRequest(item.directory).request.outputDelivery)).toEqual(['native-schema', 'file']); const requests = first.targets.map(item => fs.statSync(path.join(item.directory, 'request.json')).mtimeMs); const second = await generateSolverExplanations(f.input, { run: f.run }); expect(second.status).toBe('approved'); diff --git a/tests/solverCooperativeCheckpoints.test.ts b/tests/solverCooperativeCheckpoints.test.ts index 49e862ba..8a5732ef 100644 --- a/tests/solverCooperativeCheckpoints.test.ts +++ b/tests/solverCooperativeCheckpoints.test.ts @@ -8,6 +8,7 @@ import { compileContextSections, leadResearchInputs } from '../src/solver/contex import { observeGoalProgress } from '../src/solver/goalProgress'; import { mathDigest } from '../src/math/mathRuntimeIo'; import { directSolverModules, type SolverModules } from '../src/solver/modules'; +import { solverSourceDigest, type ProofCheck } from '../src/solver/modules/evidence'; import { captureObligationSnapshot } from '../src/solver/obligationProgress'; import { committedSource, commitSolverSources, git } from '../src/solver/problem'; import { runResearchWorkers } from '../src/solver/research'; @@ -121,7 +122,8 @@ describe('cooperative advisory scheduling checkpoints', () => { }; return { state, workers, problem, check, events, controller, run, contextSettings, pulse: (workerId: string) => cooperation!.pulse(workerId), - wake: () => cooperation!.modelBudgetChanged() }; + wake: () => cooperation!.modelBudgetChanged(), + requireReview: (candidate: ProofCheck) => cooperation!.requireReview(candidate) }; } function heldAdvisoryTurns(count: number, taskIds = ['investigate'], lastInputTokens?: number) { @@ -159,6 +161,65 @@ describe('cooperative advisory scheduling checkpoints', () => { } } + it('settles and preserves a running advisory draft for the fixed candidate review', async () => { + const { state, workers, problem, events, run, requireReview } = fixture(); + const held = heldAdvisoryTurns(1), handoff = deferred(); + const reviewStarted = deferred(), reviewDone = deferred(); + let activity: MathAgentOptions['onActivity']; + const open = vi.fn(async (options: MathAgentOptions): Promise => { + const advisory = await held.open(options); + let reviewing = false; + return { + ...advisory, + run: async (message, messageId, workspace, onStarted) => { + const assignment = JSON.parse(message) as CooperativeAction; + if (assignment.kind === 'task') { + activity = options.onActivity; + return advisory.run(message, messageId, workspace, onStarted); + } + if (assignment.kind !== 'review') throw new Error('fixture_unexpected_assignment:' + assignment.kind); + reviewing = true; + onStarted?.('review-turn'); reviewStarted.resolve(); + return reviewDone.promise; + }, + close: async () => { await advisory.close(); if (reviewing) reviewDone.resolve('interrupted'); }, + }; + }); + const completion = run(open, 2, (event, details) => { + if (event === 'turn_checkpoint' && details?.workerId === 'researcher') handoff.resolve(); + }); + void completion.catch(() => {}); + await held.wait(0, completion); + const canonical = state.cooperation!.canonicalCommit!; + requireReview({ passed: true, commit: canonical, sourceDigest: solverSourceDigest(problem, workers[0].worktree), + verification: { schema: 'deepscientist.mathematics.verification-batch/v1', sessionId: 'fixture-review', + targetCommit: canonical, status: 'kernel_verified', results: [], events: [], startedAt: 0, checkedAt: 0, durationMs: 0 } }); + await vi.advanceTimersByTimeAsync(5); + expect(held.notify).toHaveBeenCalledOnce(); + expect(held.interrupt).not.toHaveBeenCalled(); + const notes = 'A saved alternative construction and its remaining gap.'; + fs.writeFileSync(path.join(workers[1].worktree, 'RESEARCH.md'), notes); + await vi.advanceTimersByTimeAsync(30_000); + expect(held.interrupt).not.toHaveBeenCalled(); + activity?.({ event: 'item_completed', itemType: 'commandExecution' }); + await vi.advanceTimersByTimeAsync(1); + await Promise.race([handoff.promise, completion.then(() => { throw new Error('fixture_finished_before_advisory_handoff'); })]); + await Promise.race([reviewStarted.promise, completion.then(() => { throw new Error('fixture_finished_before_review'); })]); + expect(held.interrupt).toHaveBeenCalledOnce(); + expect(state.cooperation!.tasks.find(node => node.task.id === 'investigate')?.status).toBe('pending'); + const draft = state.cooperation!.researchDrafts?.investigate; + expect(draft).toBeDefined(); + expect(committedSource(workers[1].worktree, draft!.commit, 'RESEARCH.md')).toBe(notes); + expect(events).toContainEqual({ event: 'turn_checkpoint', details: { + workerId: 'researcher', turn: 1, reason: 'math_final_review_handoff_checkpoint', + } }); + expect(state.workers![1].advisoryCheckpoint?.noProgressStreak ?? 0).toBe(0); + fs.writeFileSync(path.join(workers[1].worktree, 'RESEARCH.md'), JSON.stringify({ commit: canonical, verdict: 'changes_requested' })); + reviewDone.resolve('completed'); + await completion; + expect(state.cooperation!.review?.status).toBe('changes_requested'); + }); + it.each([true, false])('routes ordinary peer updates through native advisory only when the session supports it (%s)', async nativeAdvisory => { const { workers, controller, run } = fixture(); const held = heldAdvisoryTurns(1), notify = vi.fn(async (_message: string, _options?: { waitForRequest?: boolean; mode?: 'advisory' }) => {}); diff --git a/tests/solverFinalReviewScope.test.ts b/tests/solverFinalReviewScope.test.ts index 3876e6ef..6fb9b83a 100644 --- a/tests/solverFinalReviewScope.test.ts +++ b/tests/solverFinalReviewScope.test.ts @@ -127,6 +127,42 @@ describe('fixed-candidate statement review scope', () => { expect(state.cooperation!.statementReviews!.every(item => item.status === 'pending')).toBe(true); }); + it('waits for the nonauthor to be available before assigning review of the fixed proof', async () => { + const example = { directory, workspace, problem }; + const canonical = check.commit; + const author = peerWorker(example, 'engineer', { role: 'engineer', commit: canonical }); + const secondAuthor = peerWorker(example, 'prover', { role: 'prover', commit: canonical }); + workers.push(author, secondAuthor); + task('goal_0').assignment = { workerId: author.id, taskId: 'goal_0', taskDigest: taskVersion(task('goal_0').task), seedCommit: canonical }; + state.cooperation!.landedHelpers = [{ producer: secondAuthor.id, file: 'Submission.lean', qualifiedName: 'Tutorial.used', + type: 'True', commit: canonical }]; + reports.set(problem.targets[0]!.theoremName, { statement: [], proof: [{ name: 'Tutorial.used', file: 'Submission.lean' }] }); + await freshCheck(); + cooperative = create(); + const nonauthor = workers[1]!; + const occupied = { kind: 'lead' as const, seedCommit: canonical }; + cooperative.activate(nonauthor, occupied, async () => {}, async () => {}); + cooperative.requireReview(check); + track(cooperative.next(author, budget)); + track(cooperative.next(secondAuthor, budget)); + await Promise.resolve(); + expect(events.filter(event => event.event === 'review_assigned')).toEqual([]); + cooperative.deactivate(nonauthor); + await completeFinalReview(); + expect(events.find(event => event.event === 'review_assigned')?.details) + .toMatchObject({ workerId: nonauthor.id, independent: true }); + expect(state.cooperation!.review!.producerIds).toEqual([author.id, secondAuthor.id].sort()); + }); + + it('labels a fresh-session review by the only available author as non-independent', async () => { + const author = workers[1]!; + task('goal_0').assignment = { workerId: author.id, taskId: 'goal_0', taskDigest: taskVersion(task('goal_0').task), seedCommit: check.commit }; + cooperative.requireReview(check); + const action = await cooperative.next(author, budget); + expect(action).toMatchObject({ kind: 'review', independent: false }); + expect(events.find(event => event.event === 'review_assigned')?.details).toMatchObject({ workerId: author.id, independent: false }); + }); + it.each(['paused', 'stopped', 'parked', 'group-paused', 'group-exhausted'] as const) ('dispatches both necessary review stages for a %s helper without reopening its proof work', async control => { reports.set(problem.targets[0]!.theoremName, { statement: [], proof: [{ name: 'Tutorial.used', file: 'Submission.lean' }] }); @@ -209,6 +245,45 @@ describe('fixed-candidate statement review scope', () => { if (!used) await completeFinalReview(); }); + it.each(['changes-requested', 'candidate-source'] as const)('resumes waiting advisory work after %s', async reason => { + const idle = peerWorker({ directory, workspace, problem }, 'engineer', { role: 'engineer', commit: check.commit }); + workers.push(idle); + state.workers = workers.map(worker => ({ ...worker, phase: 'running', turns: 0 })); + state.cooperation!.tasks.push({ task: { id: 'investigate', kind: 'research', objective: 'Investigate another construction.', + dependsOn: [], revision: 0, ownerId: idle.id }, status: 'pending', attempts: 0 }); + cooperative = create(); + cooperative.requireReview(check); + const reviewer = workers[1]!; + const reviewAction = await cooperative.next(reviewer, budget); + expect(reviewAction).toMatchObject({ kind: 'review' }); + if (reviewAction?.kind !== 'review') throw new Error('missing_final_review'); + expect(cooperative.started(reviewer, reviewAction)).toBe(true); + const waiting = track(cooperative.next(idle, budget)); + expect(events).toContainEqual({ event: 'dispatch_wait', + details: expect.objectContaining({ workerId: idle.id, stage: 'final-review' }) }); + expect(task('investigate')).toMatchObject({ status: 'pending', attempts: 0 }); + if (reason === 'changes-requested') { + fs.writeFileSync(path.join(reviewer.worktree, 'RESEARCH.md'), + JSON.stringify({ commit: check.commit, verdict: 'changes_requested' })); + await cooperative.deliver(reviewer, reviewAction, commitSolverSources(problem, reviewer.worktree)); + expect(state.cooperation!.review?.status).toBe('changes_requested'); + } else { + state.cooperation!.canonicalCommit = problem.baseCommit; + cooperative.workerAvailabilityChanged(); + } + expect(await waiting).toMatchObject({ kind: 'task', task: { id: 'investigate' } }); + }); + + it('does not start a reserved review after its candidate changes', async () => { + cooperative.requireReview(check); + const reviewer = workers[1]!; + const action = await cooperative.next(reviewer, budget); + expect(action).toMatchObject({ kind: 'review' }); + state.cooperation!.canonicalCommit = problem.baseCommit; + expect(cooperative.started(reviewer, action!)).toBe(false); + expect(state.turns).toBe(0); + }); + it.each(['environment', 'task-contract', 'candidate-source'] as const)('invalidates selective review scope after a changed %s', async change => { cooperative.requireReview(check); state.cooperation!.review!.status = 'accepted'; expect(cooperative.reviewed(check)).toBe(true); diff --git a/tests/solverResearchDrafts.test.ts b/tests/solverResearchDrafts.test.ts index 581fa3c8..b783a8b5 100644 --- a/tests/solverResearchDrafts.test.ts +++ b/tests/solverResearchDrafts.test.ts @@ -202,6 +202,42 @@ describe('isolated advisory research drafts', () => { expect(fs.readFileSync(notes(), 'utf8')).toBe(fullNotes); }); + it('includes a scoped checkpoint finding in live notices to its consumers', async () => { + const example = { directory, workspace: lead.worktree, problem }; + const consumer = peerWorker(example, 'consumer', { role: 'engineer' }); + const other = peerWorker(example, 'other'); + inputWorkers.push(consumer, other); + state.workers!.push(...inputWorkers.map(worker => ({ ...worker, phase: 'running' as const, turns: 0 }))); + const goal = node('goal_1'), research = node('first_route'), unrelated = node('second_route'); + research.task = { ...research.task, consumerGoalIds: [goal.task.id], ownerId: peer.id }; + goal.task = { ...goal.task, dependsOn: [], ownerId: consumer.id }; + unrelated.task = { ...unrelated.task, status: 'active', ownerId: other.id }; + cooperative = create(); + const action = await task(); + const activate = async (worker: ResearchWorker, taskId: string) => { + const work = await cooperative.next(worker, budget); + expect(work).toMatchObject({ kind: 'task', task: { id: taskId } }); + expect(cooperative.started(worker, work!)).toBe(true); + const notify = vi.fn(async () => {}); + cooperative.activate(worker, work!, async () => {}, notify); + return notify; + }; + const consumerNotice = await activate(consumer, goal.task.id); + const otherNotice = await activate(other, unrelated.task.id); + write(peer, { summary: 'FIRST_ROUTE_FINDING', conclusion: 'supporting', remainingObligations: ['Exact missing inequality'] }); + await cooperative.deliver(peer, action, commitSolverSources(problem, peer.worktree), true, 'scheduling-checkpoint'); + + const delivery = state.cooperation!.deliveries?.find(record => record.kind === 'research'); + expect(delivery, JSON.stringify(state.cooperation!.deliveryReceipts)).toMatchObject({ + taskId: 'first_route', status: 'conditional', summary: 'FIRST_ROUTE_FINDING', + }); + const notice = `Cooperation update: research ${delivery!.id}, task first_route, status conditional.`; + expect(consumerNotice).toHaveBeenCalledWith(expect.stringContaining( + '{"summary":"FIRST_ROUTE_FINDING","remainingObligations":["Exact missing inequality"]}'), { mode: 'advisory' }); + expect(otherNotice).toHaveBeenCalledWith(expect.stringContaining(notice), { mode: 'advisory' }); + expect(otherNotice.mock.calls.flat().join(' ')).not.toContain('FIRST_ROUTE_FINDING'); + }); + it.each([ 'The local boundary case is proved; the uniform inference is still unknown.', 'Illustrative graph only.\n```json\n{"nodes":["boundary","uniform"]}\n```\n',