From 4d124714a373492752eba2e751c838e021eeb06f Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:35:07 +0800 Subject: [PATCH 1/2] fix(solver): improve harness scheduling and recovery --- docs/usage.md | 2 +- docs/web-operations.md | 4 + src/math/leanSource.ts | 7 +- src/math/mathRuntimeIo.ts | 73 +++++++- src/solver/archive.ts | 7 +- src/solver/contextCompiler.ts | 21 ++- src/solver/continuationSeed.ts | 37 ++-- src/solver/cooperation.ts | 112 ++++++------- src/solver/cooperationCore.ts | 29 +++- src/solver/cooperationPlanning.ts | 33 +++- src/solver/cooperationTaskProofs.ts | 50 +++--- src/solver/modules/context.ts | 38 ++++- src/solver/modules/organization.ts | 7 +- src/solver/research.ts | 61 ++++--- src/solver/researchCheckpoints.ts | 91 ++++++++-- src/solver/run.ts | 11 +- tests/contextDispatchBudget.test.ts | 24 ++- tests/continuationSeed.test.ts | 50 +++++- tests/nextChecks.test.ts | 102 ++++++++++- tests/researchArchive.test.ts | 24 +++ tests/runContinuationSeed.test.ts | 49 ++++-- tests/runLeaseSafety.test.ts | 26 ++- tests/solverCooperativeCheckpoints.test.ts | 37 +++- tests/solverLivenessRecovery.test.ts | 50 +++++- tests/solverResearchDrafts.test.ts | 31 ++++ tests/solverRoutePreflightScheduling.test.ts | 168 +++++++++++++++++++ tests/solverWorkerExitDispatch.test.ts | 107 ++++++++++++ 27 files changed, 1037 insertions(+), 214 deletions(-) create mode 100644 tests/solverRoutePreflightScheduling.test.ts create mode 100644 tests/solverWorkerExitDispatch.test.ts diff --git a/docs/usage.md b/docs/usage.md index e237f953..1dd55a8b 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -161,7 +161,7 @@ bun run math run \ 普通 research/sketch 的交付记录保存本次实际上下文的输入身份,包括任务、传递依赖的 finding 与证明状态、环境、检索/知识库和可见源码。续跑只比较并沿用这份原记录;输入变化会重开调查并保留旧 finding 的历史,重新调查即使结论文字相同也保留新的交付身份。新 Lean 收据编号不构成输入变化,独立重检失败的依赖则会使研究重开。无法从存档确认原分工的源码可见范围时,也会保守地重新调查。该状态只结束研究,不授予任何证明验收。旧快照缺少真实交付输入身份时按待办恢复,原始 finding 仍保存在历史附件中。 -该入口只支持至少两个工人的协作运行,不能与 `--continuation-manifest` 同用。新团队无法承担的任务负责人(`ownerId`)会被释放,任务版本不变,由当前成员重新领取。加 `--startup-only` 可以停在已初始化的零轮 checkpoint;开始求解前,初始化、快照读取、工人附件分发或启动结果发布失败都保留可恢复的 `prepared` 状态,在原参数上加 `--resume` 重试,继续使用首次冻结的材料。开始过求解后,恢复时省略 `--continuation-source-run`,按普通 `--resume` 流程重新验证存档证明。 +该入口只支持至少两个工人的协作运行,不能与 `--continuation-manifest` 同用。新团队无法承担的任务负责人(`ownerId`)会被释放,任务版本不变,由当前成员重新领取。加 `--startup-only` 会冻结续跑材料并保存零轮 checkpoint。待核验的辅助证明在移除 `--startup-only` 并加 `--resume` 后检查一次,随后直接在同一进程中开始求解。开始求解前,初始化、快照读取、工人附件分发或启动结果发布失败都保留可恢复的 `prepared` 状态,在原参数上加 `--resume` 可继续使用首次冻结的材料。开始过求解后,恢复时省略 `--continuation-source-run`,按普通 `--resume` 流程重新验证存档证明。 也可以保留分步流程:先用新构建执行 `run --startup-only`,再运行独立初始化命令: diff --git a/docs/web-operations.md b/docs/web-operations.md index fcc5e8a6..cf10450a 100644 --- a/docs/web-operations.md +++ b/docs/web-operations.md @@ -2,6 +2,10 @@ 本文针对独立 Linux 宿主机上的 Compose 部署。所有路径、域名和镜像名在执行前换成实际值;下面命令不调用付费模型、不发送邮件。`scripts/web-operations.ts` 输出 JSON 摘要,不输出邮箱、题目、密码、Cookie 或 API Key。 +条件熵一类的独立长跑可以走 Web 服务的标准求证入口。宿主在 Docker 输出流断开后会等待 worker 停止,再读回磁盘上的最新候选和终验回执。 + +直接调用 worker 镜像做离线实验时,将输入 JSON 的 `observationSourceRefs` 设为 `true`,由采集器按内容哈希复用重复的 Lean 源码。为每次运行使用独立的命名卷挂载到 `/var/theoremos-proof`,并设置 `THEOREMOS_WORKER_JOURNAL=/var/theoremos-proof`。如需保留求证检查点和工作树,再将另一个命名卷挂载到 `/work`,取代该路径的 tmpfs。保留容器直到读回日志卷中的 `terminal.json` 和 `artifact.json`,可对停止的容器使用 `docker cp`。结果以匹配运行 ID 的终验回执为准。 + ## 发布镜像 `Verify TheoremOS` 在面向 `main` 的 pull request 和 `main` 推送上运行,也可手动运行。它以只读仓库权限执行 TypeScript 检查、运行时与网页构建、离线浏览器回归,以及 Lean 4.33.0 和 4.34.1 上的求解器回归。验证和镜像发布均使用 Ubuntu 24.04。 diff --git a/src/math/leanSource.ts b/src/math/leanSource.ts index 01b104d7..f0ed252d 100644 --- a/src/math/leanSource.ts +++ b/src/math/leanSource.ts @@ -45,7 +45,8 @@ const isLeanNameCharacter = (value: string | undefined): boolean => // A structure initializer may place fields in the declaration's column. // Command tokens, rather than indentation alone, delimit an empty field list. -const leanWhereCommand = /^(?:@\[|#|(?:theorem|lemma|def|abbrev|opaque|instance|example|class|structure|inductive|coinductive|axiom|constant|constants|variable|variables|universe|universes|namespace|section|end|mutual|open|export|include|omit|set_option|attribute|local|scoped|noncomputable|private|protected|public|unsafe|partial|nonrec|meta|syntax|macro|elab|notation|infix|infixl|infixr|prefix|postfix|initialize|builtin_initialize|import)(?![\p{L}\p{M}\p{N}_'.?!]))/u; +export const startsLeanSourceCommand = (text: string): boolean => + /^(?:@\[|#|(?:theorem|lemma|def|abbrev|opaque|instance|example|class|structure|inductive|coinductive|axiom|constant|constants|variable|variables|universe|universes|namespace|section|end|mutual|open|export|include|omit|set_option|attribute|local|scoped|noncomputable|private|protected|public|unsafe|partial|nonrec|meta|syntax|macro|elab|notation|infix|infixl|infixr|prefix|postfix|initialize|builtin_initialize|import)(?![\p{L}\p{M}\p{N}_'.?!]))/u.test(text); /** `instance` inside `@[…]` or `attribute […]`, or after `deriving`, names an attribute or a derive handler. * Read as a declaration, `attribute [instance 1001] a` swallowed the next command up to its `:=`. */ @@ -189,7 +190,7 @@ function* leanSourceDeclarations(source: string, mode: LeanDeclarationIndex = 'n if (nextToken === source.length) return true; const nextLine = source.lastIndexOf('\n', nextToken - 1) + 1; if (nextLine <= whereStart) return false; - return leanWhereCommand.test(source.slice(nextToken)); + return startsLeanSourceCommand(source.slice(nextToken)); }; const hasEquationArrow = (start: number): boolean => { @@ -600,7 +601,7 @@ function leanSourceDeclarationRegion(source: string, declaration: LeanSourceDecl const boundaryLine = declaration.whereBody ? cleanedSource!.slice(start, end < 0 ? undefined : end) : line; if (boundaryLine.trim() && !boundaryLine.trimStart().startsWith('--') && (line.match(/^\s*/u)?.[0].length ?? 0) <= indentation && - (!declaration.whereBody || leanWhereCommand.test(boundaryLine.trimStart()))) { + (!declaration.whereBody || startsLeanSourceCommand(boundaryLine.trimStart()))) { endOffset = start; break; } diff --git a/src/math/mathRuntimeIo.ts b/src/math/mathRuntimeIo.ts index 23b1be67..8515e225 100644 --- a/src/math/mathRuntimeIo.ts +++ b/src/math/mathRuntimeIo.ts @@ -26,10 +26,49 @@ const normalizeJson = (item: unknown, compare: (a: string, b: string) => number) throw new Error('math_runtime_invalid_json'); }; -export function canonicalMathJson(value: unknown, compare: (a: string, b: string) => number = (a, b) => a < b ? -1 : a > b ? 1 : 0): string { +const compareJsonKeys = (a: string, b: string): number => a < b ? -1 : a > b ? 1 : 0; + +export function canonicalMathJson(value: unknown, compare: (a: string, b: string) => number = compareJsonKeys): string { return JSON.stringify(normalizeJson(value, compare)); } +/** Normalize current data, sharing only detached previous subtrees whose values still match. */ +function checkpointJson(item: unknown, previous: unknown): unknown { + if (previous !== undefined && item === previous) return previous; + if (Array.isArray(item)) { + const prior = Array.isArray(previous) ? previous : undefined; + let unchanged = prior?.length === item.length; + const values = item.map((entry, index) => { + const current = checkpointJson(entry, prior?.[index]); + if (current !== prior?.[index]) unchanged = false; + return current; + }); + // For a sparse array, a removed value is not visited by map. + return unchanged && prior!.every((_, index) => index in values) ? prior : values; + } + if (item && typeof item === 'object') { + const prototype = Object.getPrototypeOf(item); + if (prototype !== Object.prototype && prototype !== null) throw new Error('math_runtime_invalid_json'); + const prior = previous && typeof previous === 'object' && !Array.isArray(previous) + ? previous as Record : undefined; + const entries = Object.entries(item); + let length = 0; + let unchanged = prior !== undefined; + for (const pair of entries) { + if (pair[1] === undefined) continue; + const saved = prior && Object.hasOwn(prior, pair[0]) ? prior[pair[0]] : undefined; + const current = checkpointJson(pair[1], saved); + if (current !== saved) unchanged = false; + pair[1] = current; + entries[length++] = pair; + } + if (unchanged && Object.keys(prior!).length === length) return prior; + entries.length = length; + return Object.fromEntries(entries.sort(([a], [b]) => compareJsonKeys(a, b))); + } + return normalizeJson(item, compareJsonKeys); +} + export const mathDigest = (value: string | Uint8Array): string => crypto.createHash('sha256').update(value).digest('hex'); @@ -53,15 +92,33 @@ export function writeMathJsonDurable(file: string, value: unknown, mode: 0o600 | writeMathTextDurable(file, canonicalMathJson(value), mode); } +/** Keep one detached checkpoint for frequently saved mutable state. The cached bytes still need the same file identity. */ +export function createMathJsonCheckpointWriter(): (file: string, value: unknown) => void { + let last: { file: string; snapshot: unknown; identity: string } | undefined; + return (file, value) => { + const previous = last?.file === file ? last : undefined; + const snapshot = checkpointJson(value, previous?.snapshot); + if (previous && snapshot === previous.snapshot && durableFileMatches(file, previous.identity)) return; + const identity = replaceMathTextDurable(file, JSON.stringify(snapshot), 0o600); + last = { file, snapshot, identity }; + }; +} + +function durableFileMatches(file: string, identity: string): boolean { + try { return mathFileIdentity(fs.lstatSync(file, { bigint: true })) === identity; } + catch { return false; } // Missing or replaced output must be written again. +} + /** Atomically replace `file` with `contents`; an unchanged, unreplaced output is not rewritten. */ export function writeMathTextDurable(file: string, contents: string, mode: 0o600 | 0o400 = 0o600): void { + replaceMathTextDurable(file, contents, mode); +} + +function replaceMathTextDurable(file: string, contents: string, mode: 0o600 | 0o400): string { const digest = mathDigest(contents); const previous = durableWrites.get(file); - if (previous?.digest === digest && previous.mode === mode) { - try { - if (mathFileIdentity(fs.lstatSync(file, { bigint: true })) === previous.identity) return; - } catch { /* Missing or replaced output must be written again. */ } - } + if (previous?.digest === digest && previous.mode === mode && durableFileMatches(file, previous.identity)) + return previous.identity; const temporary = `${file}.${crypto.randomUUID()}.tmp`; const descriptor = fs.openSync( temporary, @@ -79,7 +136,9 @@ export function writeMathTextDurable(file: string, contents: string, mode: 0o600 fs.renameSync(temporary, file); syncMathDirectory(path.dirname(file)); if (durableWrites.size >= 128) durableWrites.delete(durableWrites.keys().next().value!); - durableWrites.set(file, { digest, mode, identity: mathFileIdentity(fs.lstatSync(file, { bigint: true })) }); + const identity = mathFileIdentity(fs.lstatSync(file, { bigint: true })); + durableWrites.set(file, { digest, mode, identity }); + return identity; } export function readMathFile(file: string, maxBytes = Infinity, options: { headOnly?: boolean } = {}) { diff --git a/src/solver/archive.ts b/src/solver/archive.ts index e875da95..6c1e9876 100644 --- a/src/solver/archive.ts +++ b/src/solver/archive.ts @@ -1,4 +1,4 @@ -import { readMathJson, writeMathJsonDurable } from '../math/mathRuntimeIo'; +import { createMathJsonCheckpointWriter, readMathJson } from '../math/mathRuntimeIo'; import { personalExpertSetSchema, type PersonalExpertSet } from './personalExperts'; import { agentTeamStateSchema, writerProcessSchema, type AgentTeamState } from './agentTeamState'; import type { SolverProblem } from './problem'; @@ -107,6 +107,7 @@ export type SolverRunState = { knowledgeDigest?: string; libraryCatalogDigest?: string; continuationDigest?: string; + pendingContinuationSource?: string; knowledgeRetrievals?: { dropped: number; observations: KnowledgeRetrievalObservation[] }; knowledgeUses?: (KnowledgeUse & { workerId: string; commit: string })[]; model: string; @@ -328,6 +329,7 @@ const runState = research.extend({ schema: z.literal('deepscientist.math.solver. problem: z.object({ workspace: z.string(), receiptDigest: z.string() }).passthrough(), taskDigest: z.string(), buildDigest: z.string(), environmentDigest: z.string(), evaluatorDigest: z.string(), continuationDigest: z.string().regex(/^[a-f0-9]{64}$/u).optional(), + pendingContinuationSource: z.string().min(1).optional(), providerProfile: z.string().optional(), providerProfileDigest: z.string().regex(/^[a-f0-9]{64}$/u).optional(), agentHarness: z.object({ id: z.enum(['codex', 'claude-code', 'opencode', 'cli']), executable: z.string().min(1), executableDigest: z.string().regex(/^[a-f0-9]{64}$/u), profile: z.string().min(1), @@ -450,9 +452,10 @@ export const readSolverRunState = (file: string): SolverRunState => { if (!parsed.success) throw new Error(`math_resume_state_invalid:${parsed.error.issues[0]?.path.join('.')}`); return parsed.data as unknown as SolverRunState; }; +const writeRunCheckpoint = createMathJsonCheckpointWriter(); export const writeSolverRunState = (file: string, state: SolverRunState): void => { const safeResearch = >(research: T): T => research.lastFailure ? { ...research, lastFailure: { ...research.lastFailure, diagnostic: safeFailureDiagnostic(research.lastFailure.diagnostic) } } : research; - writeMathJsonDurable(file, { ...safeResearch(state), workers: state.workers?.map(safeResearch) }); + writeRunCheckpoint(file, { ...safeResearch(state), workers: state.workers?.map(safeResearch) }); }; diff --git a/src/solver/contextCompiler.ts b/src/solver/contextCompiler.ts index b42cdf68..d869bc78 100644 --- a/src/solver/contextCompiler.ts +++ b/src/solver/contextCompiler.ts @@ -19,6 +19,7 @@ import { portfolioPhase2Guidance } from './portfolioExploration'; export const DEFAULT_TASK_CONTEXT_BYTES = 512 * 1024; export const DEFAULT_OPTIONAL_TASK_CONTEXT_BYTES = 64 * 1024; +const COMPACT_OPTIONAL_TASK_CONTEXT_BYTES = 8 * 1024; /** Above this size a source is shown compactly: definition bodies are omitted and the statement is cited, not repeated. */ export const COMPACT_CONTEXT_SOURCE_BYTES = 64 * 1024; /** A compact source keeps definition bodies up to this size inline. */ @@ -50,6 +51,8 @@ export type TaskContextInput = Readonly<{ optional?: readonly ContextSection[]; /** The same thread already has this frozen problem; still send the new task's exact interfaces. */ taskSwitch?: boolean; + /** The active assignment survived compaction, but its exact inputs must be sent again. */ + compactedResume?: boolean; }>; export class TaskContextError extends Error { constructor(readonly code: 'math_context_missing_required' | 'math_context_stale_required' | @@ -140,7 +143,7 @@ export function frozenSourceContext(problem: SolverProblem, file: string, source function originalProblemSection(input: TaskContextInput): ContextSection { const { problem } = input, statement = problem.contract.formalStatement, bytes = Buffer.byteLength(statement); const title = `${input.taskText}\n\nOriginal problem:`, digest = mathDigest(statement); - const file = bytes > (compactArchive(input.cooperation) ? 4 * 1024 : COMPACT_CONTEXT_SOURCE_BYTES) && present(problem.baseCommit) + const file = bytes > (input.compactedResume || compactArchive(input.cooperation) ? 4 * 1024 : COMPACT_CONTEXT_SOURCE_BYTES) && present(problem.baseCommit) ? Object.keys(problem.trustedFiles ?? {}).sort().find(file => problem.trustedFiles[file] === digest) : undefined; if (!file) return section('original-problem', 'problem', title, statement); return section('original-problem', 'problem', title, { commit: problem.baseCommit, path: sourcePath(problem, file), bytes, sha256: digest, @@ -357,7 +360,7 @@ function sourceReferences(input: TaskContextInput) { retrieval: 'Read full proofs and namespace/section/instance context with git show COMMIT:PATH in this isolated worktree. Source references identify immutable content; they grant no proof acceptance.', files: files.map(file => { const context = input.frozenContexts![file], declarations = problem.declarations[file] ?? []; - if ((input.taskSwitch || compactArchive(input.cooperation)) && Buffer.byteLength(context) > 4 * 1024) { + if ((input.compactedResume || compactArchive(input.cooperation)) && Buffer.byteLength(context) > 4 * 1024) { return { commit: problem.baseCommit, path: sourcePath(problem, file), contextDigest: problem.sourceStructure?.[file], imports: problem.sourceImports?.[file], declarationCount: declarations.length, contextByReference: true }; } @@ -386,7 +389,7 @@ function frozenDeclarationOrder(input: TaskContextInput) { .map(([file, declarations]) => { const names = declarations.map(declaration => declaration.name), context = input.frozenContexts?.[file]; const byReference = context && Buffer.byteLength(context) > - (input.taskSwitch || compactArchive(input.cooperation) ? 4 * 1024 : COMPACT_CONTEXT_SOURCE_BYTES); + (input.compactedResume || compactArchive(input.cooperation) ? 4 * 1024 : COMPACT_CONTEXT_SOURCE_BYTES); return [file, byReference ? { encoding: 'frozen-declaration-order-v1', commit: input.problem.baseCommit, path: sourcePath(input.problem, file), declarationCount: names.length, orderDigest: mathDigest(canonicalMathJson(names)), @@ -514,7 +517,7 @@ function optionalDeliveries(input: TaskContextInput, required: ReadonlySet { // Interfaces and receipts live in mandatory sections. A delivery summary is advisory prose. const current = record.taskId ? byId.get(record.taskId) : undefined; - if ((compactArchive(input.cooperation) || input.taskSwitch) && !(record.taskId && required.has(record.taskId))) { + if ((compactArchive(input.cooperation) || input.taskSwitch || input.compactedResume) && !(record.taskId && required.has(record.taskId))) { omitted.push({ id: `delivery:${record.id}:details`, kind: 'delivery', reason: 'advisory-details-by-reference' }); const file = current?.task.proofPath && sourcePath(input.problem, current.task.proofPath); return [{ ...section(`delivery:${record.id}`, 'delivery', @@ -558,11 +561,13 @@ function optionalDeliveries(input: TaskContextInput, required: ReadonlySet; export type ContinuationSeedReport = { schema: 'theorem-os.continuation-seed.v1'; sourceRunId: string; runId: string; sourceStateFile: string; stateFile: string; sourceDigest: string; snapshotDigest?: string; canonicalCommit?: string; - stage: 'frozen' | 'installing' | 'checking' | 'complete' | 'interrupted'; sourcesInstalled?: boolean; + stage: 'frozen' | 'installing' | 'awaiting-checks' | 'checking' | 'complete' | 'interrupted'; sourcesInstalled?: boolean; candidates: string[]; checked: string[]; failed: string[]; error?: string; evidence: 'advisory-sources-require-recheck' | 'fresh-helper-receipts'; }; @@ -559,19 +559,19 @@ function taskDraftAssignment(draft: SavedTaskDraft, task: CooperativeTask, function restorableTaskDraft(draft: SavedTaskDraft, node: TaskRecord, state: SolverRunState) { const worker = state.workers!.find(worker => worker.id === draft.workerId); - if (isFeasibilityReview(node.task) && (!draft.feasibilityInputDigest || - draft.feasibilityInputDigest !== feasibilityReviewInputDigest({ task: node.task, workerId: draft.workerId, - tasks: state.cooperation!.tasks, deliveries: state.cooperation!.deliveries ?? [], - problem: state.problem, worktree: state.worktree, canonicalCommit: state.cooperation!.canonicalCommit!, - environmentDigest: state.environmentDigest, problemReceiptDigest: state.problem.receiptDigest, - retrievalDigest: state.retrievalDigest, knowledgeDigest: state.knowledgeDigest }))) return false; - return !draft.archived && (node.status === 'pending' || + const eligible = !draft.archived && (node.status === 'pending' || pausedResearchCheckpoint(node, state.cooperation!.researchCheckpoints?.[node.task.id])) && !node.alternativeRoutes?.length && draft.taskId === node.task.id && draft.taskDigest === taskVersion(node.task) && draft.source.environmentDigest === state.environmentDigest && draft.source.problemReceiptDigest === state.problem.receiptDigest && draft.source.sourcePolicyDigest === policyDigest(state.problem) && worker && assessTaskResponsibility({ ...node, assignment: undefined }, worker, { tasks: state.cooperation!.tasks, groups: state.cooperation!.groups }).kind === 'matches'; + if (!eligible) return false; + return !isFeasibilityReview(node.task) || Boolean(resumableFeasibilityReviewInput({ task: node.task, workerId: draft.workerId, + tasks: state.cooperation!.tasks, deliveries: state.cooperation!.deliveries ?? [], + problem: state.problem, worktree: state.worktree, canonicalCommit: state.cooperation!.canonicalCommit!, + environmentDigest: state.environmentDigest, problemReceiptDigest: state.problem.receiptDigest, + retrievalDigest: state.retrievalDigest, knowledgeDigest: state.knowledgeDigest }, draft)); } function frozenTaskAssignment(candidate: z.infer, task: CooperativeTask, @@ -885,7 +885,7 @@ function freezeSource(source: SeedSource, directory: string) { export async function seedSolverContinuation(options: { sourceRun: string; run: string; root: string; buildManifest: string; signal: AbortSignal; timeoutMs?: number; onProgress?: (event: string, details: Record) => void; - lease?: MathLease; preparedEnvironment?: NodeJS.ProcessEnv; + lease?: MathLease; preparedEnvironment?: NodeJS.ProcessEnv; deferChecks?: boolean; onSeeded?: (state: SolverRunState, freshChecks: TaskProof[]) => void; }): Promise { const target = readRunInspection(options.run), sourceStateFile = path.basename(path.resolve(options.sourceRun)) === 'state.json' @@ -1000,6 +1000,11 @@ export async function seedSolverContinuation(options: { } lease.assertHeld(); if (!seeded) writeMathJsonDurable(sourceFile, source, 0o400); + const deferChecks = options.deferChecks && candidateIds.length > 0; + if (deferChecks && !state.pendingContinuationSource) { + state.pendingContinuationSource = sourceStateFile; + writeSolverRunState(stateFile, state); + } const report: ContinuationSeedReport = { schema: 'theorem-os.continuation-seed.v1', sourceRunId: source.source.runId, runId: state.runId, sourceStateFile, stateFile, sourceDigest: mathDigest(canonicalMathJson(source)), stage: 'frozen', candidates: candidateIds, checked: [], failed: [], evidence: 'advisory-sources-require-recheck' }; @@ -1060,6 +1065,11 @@ export async function seedSolverContinuation(options: { report.sourcesInstalled = true; saveReport(); emit('continuation_seed_installed', { sourceRunId: source.source.runId, runId: state.runId, tasks: tasks.length, candidates: candidateIds.length, snapshotDigest: snapshot.digest }); + if (deferChecks) { + report.stage = 'awaiting-checks'; saveReport(); + options.onSeeded?.(state, []); + return report; + } const environmentFile = path.join(directory, 'environment-solver.json'); assertMathCanonicalPath(environmentFile); if ((fs.lstatSync(environmentFile).mode & 0o777) !== 0o400) throw new Error('math_continuation_seed_environment_not_frozen'); @@ -1322,7 +1332,8 @@ export async function seedSolverContinuation(options: { } state.cooperation.deliveries = restoredResearchDeliveries(source, state); const completedResearch = currentCompletedResearch(source, state, plan.tasks, tasks, state.cooperation.deliveries); - for (const node of tasks.filter(node => isAdvisoryTask(node.task) && !node.capacityExploration)) { + // Host next checks restore their lifecycle and finding with their own records. + for (const node of tasks.filter(node => isAdvisoryTask(node.task) && !node.capacityExploration && !node.nextCheckId)) { const completion = completedResearch.get(node.task.id); setTaskStatus(node, completion ? 'completed' : 'pending', 'reconstructed'); node.finding = completion?.finding; node.researchCompletion = completion?.record; @@ -1416,6 +1427,10 @@ export async function seedSolverContinuation(options: { } writeSolverRunState(stateFile, state); report.stage = 'complete'; saveReport(); + if (state.pendingContinuationSource) { + delete state.pendingContinuationSource; + writeSolverRunState(stateFile, state); + } options.onSeeded?.(state, freshChecks); return report; } catch (error) { diff --git a/src/solver/cooperation.ts b/src/solver/cooperation.ts index 60fcd4f0..92c6f80f 100644 --- a/src/solver/cooperation.ts +++ b/src/solver/cooperation.ts @@ -4,7 +4,7 @@ import fs from 'node:fs'; import path from 'node:path'; import crypto from 'node:crypto'; import { VerificationCheckpointError } from './verificationCheckpoint'; -import { canonicalMathJson, mathDigest, readMathText, writeMathJsonDurable } from '../math/mathRuntimeIo'; +import { canonicalMathJson, mathDigest, writeMathJsonDurable } from '../math/mathRuntimeIo'; import { inspectLeanDeclarationRegions, inspectLeanSource, inspectScopedLeanDeclarations } from '../math/leanSource'; import { committedSource, git, originalDeclarationRegions, solverSourceConstraints } from './problem'; import { solverProofFeedback, solverSourceFeedback } from './feedback'; @@ -15,7 +15,7 @@ import { CAPACITY_EXPLORATION_FOCUSES, capacityExplorationInput, createCapacityE TIMED_EXPLORATION_UNANSWERED_WAKES, timedExplorationTargets } from './capacityExploration'; import { hasFreshSolverCheck, proofReceiptsMatch, type ProofCheck } from './modules/evidence'; import { originalGoalTaskFocus, readyResearchTasks, researchCanAdvance, routeAllowsTask, taskCanStart, taskDependenciesReady, selectedTaskRoute, runningTaskDependencies } from './modules/search'; -import { deliveryDetails, reviewVerdict, readMathResponse as block, MAX_RESEARCH_NOTES_BYTES } from './deliveries'; +import { deliveryDetails, reviewVerdict, readMathResponse as block } from './deliveries'; import { checkTaskProof, ownedSourceDigest, taskChanges } from './cooperativeProof'; import { assertStatementSnapshot, isStatementAction, resetStatementReview } from './statementReview'; import { captureProofReferences } from './proofReferences'; @@ -421,6 +421,7 @@ export class CooperativeResearch extends CooperationInputs { this.recordDispatchWait(worker, { stage: 'lead-unavailable', candidates: [], candidateCount: 0, omittedCandidates: 0 }); return; } + if (!this.liveWorkers.has(worker.id)) return; const modelAllowed = this.input.modelDispatchAllowed?.() !== false; const result = await (worker.id === this.lead.id ? this.nextLead(worker, budget, modelAllowed) : this.nextPeer(worker, budget, modelAllowed)); @@ -743,7 +744,7 @@ export class CooperativeResearch extends CooperationInputs { } private peerTaskCandidates(tasks: readonly TaskRecord[], groups?: readonly RouteRecord[]) { const ranked = this.input.modules.M3.ready(tasks, groups); - const ready = ranked.filter(node => !this.taskDispatchBlock(node)); + const ready = ranked.filter(node => this.nextCheckDispatchable(node) && !this.taskDispatchBlock(node)); return { ranked, ready }; } private assignPeerTask(ready: readonly TaskRecord[], worker: ResearchWorker, tasks: readonly TaskRecord[], @@ -796,7 +797,6 @@ export class CooperativeResearch extends CooperationInputs { } this.refreshConnectionCheckpoints(); const { ranked, ready } = this.peerTaskCandidates(this.archive.tasks, this.archive.groups); - this.releaseStoppedAssignments(ready, worker); const node = this.assignPeerTask(ready, worker, this.archive.tasks, this.archive.groups); if (!node) { const movable = ready.find(candidate => this.transferableResearch(candidate, worker)); @@ -805,14 +805,20 @@ export class CooperativeResearch extends CooperationInputs { const proposal = movable && { ...movable, assignment: undefined }; if (movable && proposal && this.input.modules.M5.assign([proposal], worker, this.allocationPeers, this.archive.groups, this.archive.tasks.map(candidate => candidate === movable ? proposal : candidate), this.stoppedWorkers) === proposal) { + const observedRevision = this.dispatchRevision; this.transferringResearch.add(movable); try { if (await this.transferResearchDraft(worker, movable, () => this.transferableResearch(movable, worker))) return RETRY_DISPATCH; - } finally { this.transferringResearch.delete(movable); this.wake(); } + if (observedRevision !== this.dispatchRevision) return RETRY_DISPATCH; + } finally { + this.transferringResearch.delete(movable); + this.wake(); + } } this.recordTaskWait(worker, ranked, ready); + const observedRevision = this.dispatchRevision; if (await this.requestCapacityExploration(worker, budget, ready)) return RETRY_DISPATCH; - return this.liveWorkers.has(worker.id) ? this.waitForDispatch() : undefined; + return this.liveWorkers.has(worker.id) ? this.waitForDispatch(observedRevision) : undefined; } if (!ready.includes(node) || !this.archive.tasks.includes(node) || node.status !== 'pending' || !taskCanStart(node.task, this.archive.tasks, this.archive.groups) || @@ -820,7 +826,9 @@ export class CooperativeResearch extends CooperationInputs { assessTaskResponsibility(node, worker, this.responsibility).kind !== 'matches') throw new Error('math_task_assignment_invalid'); this.clearDispatchWait(worker, 'selected'); const selectedRoute = selectedTaskRoute(node, this.archive.tasks); - if (node.assignment && node.alternativeRoutes?.length && node.assignment.routeId !== selectedRoute?.id) + // A stopped worker's pin is ignored for selection but survives until a peer actually takes its task. + const stoppedAssignment = node.assignment?.workerId !== worker.id ? node.assignment : undefined; + if (!stoppedAssignment && node.assignment && node.alternativeRoutes?.length && node.assignment.routeId !== selectedRoute?.id) node.assignment = undefined; const resumedAssignment = node.assignment; let resuming = resumedAssignment?.workerId === worker.id; @@ -846,12 +854,17 @@ export class CooperativeResearch extends CooperationInputs { // 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 dispatchAssignment: TaskAssignment = node.assignment ?? { taskId: node.task.id, taskDigest: digest(node.task), workerId: worker.id, + 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, ...(isFeasibilityReview(node.task) ? { feasibilityInputDigest: this.feasibilityInputDigest(node.task, worker.id) } : {}), dependencies: this.dependencies(node.task).map(item => ({ taskId: item.task.id, taskDigest: digest(item.task) })) }; - const canonicalGoal = node.task.kind === 'goal' && this.canonicalTaskCandidate(node, worker, scopedSeed); + const claimAssignment = () => { + node.assignment = dispatchAssignment; + if (stoppedAssignment) this.input.emit('task_assignment_released', { taskId: node.task.id, + workerId: stoppedAssignment.workerId, takenBy: worker.id, reason: 'worker-stopped' }); + }; + const canonicalGoal = !resuming && node.task.kind === 'goal' && this.canonicalTaskCandidate(node, worker, scopedSeed); if (node.task.kind === 'lemma' || node.task.kind === 'goal' && (canonicalGoal || this.input.access.get(worker.id)?.installedLibrary)) { const task = node.task, taskDigest = digest(task), environment = this.input.state.environmentDigest; const dependencies = this.typePreflightDependencies(task), head = git(worker.worktree, ['rev-parse', 'HEAD']); @@ -861,12 +874,14 @@ export class CooperativeResearch extends CooperationInputs { const problemReceipt = this.input.state.problem.receiptDigest; const controller = new AbortController(), signal = AbortSignal.any([this.input.signal, controller.signal]); const preparationGroups = () => { - const publishing = [...this.proofPublications.values()].some(publication => publication.action.assignment === dispatchAssignment); - // Publication already occupies this worker's group slot. Test whether the - // preparation can keep that slot, without charging itself a second one. - return publishing ? this.archive.groups?.map(route => route.group.id === taskGroup(task) + const reserved = this.preparingTaskTypes.get(node)?.workerId === worker.id || + [...this.proofPublications.values()].some(publication => publication.action.assignment === dispatchAssignment); + // Preflight and publication share one slot. Ignore that slot when rechecking admission. + return reserved ? this.archive.groups?.map(route => route.group.id === taskGroup(task) ? { ...route, busy: Math.max(0, (route.busy ?? 0) - 1) } : route) : this.archive.groups; }; + const stillSelected = () => this.input.modules.M5.assign([node], worker, this.allocationPeers, + preparationGroups(), this.archive.tasks, this.stoppedWorkers) === node; const current = () => !signal.aborted && !this.stopping && !this.failure && this.liveWorkers.has(this.lead.id) && this.archive.canonicalCommit === seed && this.archive.tasks.includes(node) && digest(node.task) === taskDigest && this.typePreflightDependencies(task) === dependencies && this.input.access.get(worker.id) === workerAccess && @@ -881,18 +896,17 @@ export class CooperativeResearch extends CooperationInputs { // Cancellation keeps the worker occupied until the Lean check has cleaned up. let finishPreparation!: () => void; const settled = new Promise(resolve => { finishPreparation = resolve; }); - this.preparingTaskTypes.set(node, { workerId: worker.id, controller, current, settled }); + this.preparingTaskTypes.set(node, { workerId: worker.id, groupId: taskGroup(task), controller, current, settled }); this.changed(); try { const checker = this.input.modules.M2.checkTask ?? checkTaskProof; const retainedGoals = () => this.retainedTaskGoals(task, this.archive.tasks, worker.worktree, head); const publishable = () => current() && taskDependenciesReady(task, this.archive.tasks) && - git(worker.worktree, ['rev-parse', 'HEAD']) === head && - this.input.modules.M5.assign([node], worker, this.allocationPeers, this.archive.groups, this.archive.tasks, this.stoppedWorkers) === node; + git(worker.worktree, ['rev-parse', 'HEAD']) === head && stillSelected(); const claim = () => { // Publication owns cleanup from here; changing the assignment must not cancel its own preparation. this.preparingTaskTypes.delete(node); - node.assignment = dispatchAssignment; + claimAssignment(); }; const probeCanonical = async (publishable: () => boolean): Promise => { // A failed probe is not a model delivery. Keep it outside failure memory and archive acceptance. @@ -928,7 +942,7 @@ export class CooperativeResearch extends CooperationInputs { if (canonicalGoal && leadAccess && workerAccess && await probeCanonical(publishable)) return RETRY_DISPATCH; const applyLibrary = this.input.modules.M2.applyLibrary, library = workerAccess?.installedLibrary; const libraryKey = canonicalMathJson([taskDigest, scopedSeed, environment, library?.digest ?? null]); - if (applyLibrary && library && leadAccess && workerAccess && !node.assignment && !isDefinitionTask(task) && + if (applyLibrary && library && leadAccess && workerAccess && !resuming && !isDefinitionTask(task) && !task.conditional && !automaticTaskConnection(task, this.archive.tasks, this.archive.groups) && taskDependenciesReady(task, this.archive.tasks) && !this.libraryApplicationAttempts.has(libraryKey)) { this.libraryApplicationAttempts.add(libraryKey); @@ -982,7 +996,7 @@ export class CooperativeResearch extends CooperationInputs { current: () => !this.input.signal.aborted, }; if (!current() || !checked.current() || git(worker.worktree, ['rev-parse', 'HEAD']) !== head || - this.input.modules.M5.assign([node], worker, this.allocationPeers, this.archive.groups, this.archive.tasks, this.stoppedWorkers) !== node) + !stillSelected()) return RETRY_DISPATCH; node.typePreflight = checked.result; this.input.emit('task_type_preflight', { taskId: node.task.id, workerId: worker.id, ...checked.result }); @@ -997,11 +1011,10 @@ export class CooperativeResearch extends CooperationInputs { this.wakeLead('task-type-invalid'); this.changed(); return RETRY_DISPATCH; } const publishable = () => current() && checked.current() && taskDependenciesReady(task, this.archive.tasks) && - git(worker.worktree, ['rev-parse', 'HEAD']) === head && - this.input.modules.M5.assign([node], worker, this.allocationPeers, this.archive.groups, this.archive.tasks, this.stoppedWorkers) === node; + git(worker.worktree, ['rev-parse', 'HEAD']) === head && stillSelected(); const assembleFamily = this.input.modules.M2.assembleFamily; const familyKey = canonicalMathJson([taskDigest, dependencies, environment]); - if (assembleFamily && task.family && !node.assignment && leadAccess && workerAccess && checked.result.status === 'elaborated' && + if (assembleFamily && task.family && !resuming && leadAccess && workerAccess && checked.result.status === 'elaborated' && checked.result.context && !this.familyAssemblyAttempts.has(familyKey)) { // One host assembly per exact family contract in this process; a failure falls through to a model. this.familyAssemblyAttempts.add(familyKey); @@ -1028,8 +1041,7 @@ export class CooperativeResearch extends CooperationInputs { ...(assembly.commit ? { commit: assembly.commit } : {}), ...(proof ? { passed: proof.passed, verificationStatus: proof.verification.status, receiptIds: proof.verification.results.map(result => result.receiptId) } : {}) }); // A conditional family starts before its members are checked, so this omits the dependency-readiness gate. - const assembled = () => current() && checked.current() && git(worker.worktree, ['rev-parse', 'HEAD']) === head && - this.input.modules.M5.assign([node], worker, this.allocationPeers, this.archive.groups, this.archive.tasks, this.stoppedWorkers) === node; + const assembled = () => current() && checked.current() && git(worker.worktree, ['rev-parse', 'HEAD']) === head && stillSelected(); if (proof?.passed) { if (!assembled()) return RETRY_DISPATCH; await this.publishTaskProof(worker, { kind: 'task', task, assignment: dispatchAssignment }, assembly.commit!, @@ -1040,11 +1052,11 @@ export class CooperativeResearch extends CooperationInputs { } if (!assembled()) return RETRY_DISPATCH; } - const canonicalCandidate = leadAccess && workerAccess && this.canonicalTaskCandidate(node, worker, scopedSeed); + const canonicalCandidate = !resuming && leadAccess && workerAccess && this.canonicalTaskCandidate(node, worker, scopedSeed); if (canonicalCandidate && await probeCanonical(publishable)) return RETRY_DISPATCH; const closeTask = this.input.modules.M2.closeTask; const batteryKey = canonicalMathJson([taskDigest, dependencies, environment, checked.result.inputDigest]); - if (closeTask && !canonicalCandidate && leadAccess && workerAccess && checked.result.status === 'elaborated' && + if (closeTask && !resuming && !canonicalCandidate && leadAccess && workerAccess && checked.result.status === 'elaborated' && checked.result.context && !isDefinitionTask(task) && this.tacticBatteryCandidate(node) && !this.tacticBatteryAttempts.has(batteryKey)) { // One host attempt per exact helper contract in this process; a failure is not model feedback. this.tacticBatteryAttempts.add(batteryKey); @@ -1090,7 +1102,7 @@ export class CooperativeResearch extends CooperationInputs { this.preparingTaskTypes.delete(node); finishPreparation(); this.changed(); } } - node.assignment ??= dispatchAssignment; + claimAssignment(); if (!node.assignment.connectionCheck && automaticTaskConnection(node.task, this.archive.tasks, this.archive.groups)) { // Upgrading an idle historical assignment keeps its saved draft but supersedes late publications. if (resuming && node.assignment === resumedAssignment) node.assignment = { ...node.assignment, assignmentId: crypto.randomUUID() }; @@ -1132,7 +1144,7 @@ export class CooperativeResearch extends CooperationInputs { /** Host proof attempts start only from a fresh, unconditional typed helper whose dependencies are checked. */ private tacticBatteryCandidate(node: TaskRecord): boolean { const task = node.task; - return !node.assignment && !task.conditional && Boolean(task.type?.trim()) && taskDependenciesReady(task, this.archive.tasks) && + return !task.conditional && Boolean(task.type?.trim()) && taskDependenciesReady(task, this.archive.tasks) && !automaticTaskConnection(task, this.archive.tasks, this.archive.groups); } /** Declaration scanning only selects complete candidates; the checker still establishes proof and exact type. */ @@ -1140,7 +1152,7 @@ export class CooperativeResearch extends CooperationInputs { const task = node.task; let kind: 'theorem' | 'definition' | 'instance'; if (task.kind === 'goal') { - if (node.assignment || task.conditional || !taskDependenciesReady(task, this.archive.tasks) || + if (task.conditional || !taskDependenciesReady(task, this.archive.tasks) || automaticTaskConnection(task, this.archive.tasks, this.archive.groups) || !this.input.state.problem.targets.some(target => target.proofPath === task.proofPath && target.theoremName === task.theoremName)) return false; const original = committedSource(worker.worktree, this.input.state.problem.baseCommit, @@ -1345,26 +1357,25 @@ export class CooperativeResearch extends CooperationInputs { try { const schedulingDraft = recovering && recoveryKind === 'scheduling-checkpoint' && !action.initialPlanNonce && !publishedPlan && this.archive.tasks.length > 0; - const notesFile = path.join(worker.worktree, 'RESEARCH.md'); - const savedNotes = (publishedPlan || schedulingDraft) && fs.existsSync(notesFile) - ? readMathText(notesFile, MAX_RESEARCH_NOTES_BYTES) : ''; + const savedNotes = publishedPlan || schedulingDraft ? this.leadNotes().text : ''; let unchangedCheckpoint = false, changedNotes = false; - if (schedulingDraft) { + if (schedulingDraft && savedNotes !== undefined) { try { - const seedNotes = git(worker.worktree, ['ls-tree', '--name-only', action.seedCommit, '--', 'RESEARCH.md']) - ? committedSource(worker.worktree, action.seedCommit, 'RESEARCH.md') : ''; - unchangedCheckpoint = this.proposedPlanDigest(seedNotes) === this.proposedPlanDigest(savedNotes); - changedNotes = seedNotes.trim() !== savedNotes.trim(); + const seedNotes = this.leadNotes(action.seedCommit).text; + unchangedCheckpoint = seedNotes !== undefined && + this.proposedPlanDigest(seedNotes) === this.proposedPlanDigest(savedNotes); + changedNotes = seedNotes?.trim() !== savedNotes.trim(); } catch { /* Without a readable dispatch baseline, validate the saved response normally. */ } } - const notes = savedNotes.trimStart(); + const notes = savedNotes?.trimStart() ?? ''; const hasPlanResponse = notes.startsWith('{') || /```(?:math|json|math-[a-z-]+)\b/u.test(notes); const hasFinalPlan = hasPlanResponse && this.publishedPlans.get(action)?.responseDigest !== this.proposedPlanDigest(); - if (schedulingDraft && changedNotes && notes.trim() && !hasPlanResponse) { + if (schedulingDraft && (savedNotes === undefined || changedNotes && notes.trim() && !hasPlanResponse)) { // A scheduled yield can save fresh mathematical notes before Lead has a decision to submit. this.pin(commit); if (requiredDecision) this.wakeLead('lead-checkpoint-unchanged'); - this.input.emit('lead_checkpoint_saved', { commit, seedCommit: action.seedCommit, reason: 'notes-only-draft' }); + this.input.emit('lead_checkpoint_saved', { commit, seedCommit: action.seedCommit, + reason: savedNotes === undefined ? 'oversized-notes-draft' : 'notes-only-draft' }); } else if (unchangedCheckpoint && !requiredDecision) { // Inherited control notes are a draft, not a fresh response to this dispatch. // Continue below so saved Lean source changes still take the ordinary merge path. @@ -1676,25 +1687,12 @@ export class CooperativeResearch extends CooperationInputs { this.changed(); } else this.interrupted(worker, action); } - /** - * A stopped worker never returns in this process, so its saved assignment would block every peer. - * The record stays durable until a responsible live peer actually takes the task: a restart resumes the - * original worker's draft and repair chain instead. - */ - private releaseStoppedAssignments(ready: readonly TaskRecord[], worker: ResearchWorker) { - for (const node of ready) { - const assignment = node.assignment; - if (!assignment || assignment.workerId === worker.id || this.liveWorkers.has(assignment.workerId) || - !this.input.workers.some(item => item.id === assignment.workerId)) continue; - node.assignment = undefined; - if (assessTaskResponsibility(node, worker, this.responsibility).kind !== 'matches') { node.assignment = assignment; continue; } - this.input.emit('task_assignment_released', { taskId: node.task.id, workerId: assignment.workerId, - takenBy: worker.id, reason: 'worker-stopped' }); - this.changed(); - } - } private reviewer(releasing?: TaskRecord): 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) && + !this.workerCoolingDown(worker.id) && + !preparing.has(worker.id) && !(this.archive.review?.status === 'running' && this.archive.review.workerId === worker.id) && !this.archive.tasks.some(node => node !== releasing && node.status === 'running' && node.assignment?.workerId === worker.id) && !this.archive.statementReviews?.some(review => review.workerId === worker.id && ['translating', 'reviewing'].includes(review.status))); diff --git a/src/solver/cooperationCore.ts b/src/solver/cooperationCore.ts index 453d7edb..0ffcbb26 100644 --- a/src/solver/cooperationCore.ts +++ b/src/solver/cooperationCore.ts @@ -60,6 +60,7 @@ export abstract class CooperationCore { protected lastAssembly?: string; private assemblyYieldedLeads = new WeakSet(); private waiters = new Set<() => void>(); + protected dispatchRevision = 0; protected reservedTurns = new Set(); protected liveWorkers: Set; protected checkedDeliveries = new WeakSet(); @@ -67,7 +68,7 @@ export abstract class CooperationCore { protected readonly rejectedIntegrationBatches = new Set(); protected readonly taskTypePreflight = new TaskTypePreflightCache(); protected preparingTaskTypes = new Map boolean; settled: Promise; + workerId: string; groupId: string; controller: AbortController; current: () => boolean; settled: Promise; }>(); /** Exact helper contracts already tried by the host tactic battery in this process. */ protected readonly tacticBatteryAttempts = new Set(); @@ -381,13 +382,15 @@ export abstract class CooperationCore { protected get responsibility() { return { tasks: this.archive.tasks, groups: this.archive.groups, stopped: this.stoppedWorkers }; } + protected workerCoolingDown(workerId: string) { + return this.input.state.workers?.some(worker => worker.id === workerId && worker.recovery?.phase === 'cooling-down') === true; + } protected get allocationPeers() { const occupied = new Set([...this.active].filter(([, active]) => active.action.kind !== 'task').map(([id]) => id)); if (this.archive.review?.status === 'running' && this.archive.review.workerId) occupied.add(this.archive.review.workerId); for (const review of this.archive.statementReviews ?? []) if (review.workerId && ['translating', 'reviewing'].includes(review.status)) occupied.add(review.workerId); - for (const worker of this.input.state.workers ?? []) if (worker.recovery?.phase === 'cooling-down') occupied.add(worker.id); - return this.livePeers.filter(worker => !occupied.has(worker.id)); + return this.livePeers.filter(worker => !occupied.has(worker.id) && !this.workerCoolingDown(worker.id)); } protected get explorationIdentity() { return { environmentDigest: this.input.state.environmentDigest, @@ -442,6 +445,10 @@ export abstract class CooperationCore { this.input.emit('next_check_outcome', { checkId: record.id, outcomeDeliveryId: outcome.id, conclusion: outcome.checkOutcome.conclusion }); } } + // Older continuation seeds could leave a settled check's task in the work queue. + if (node && (record.status === 'awaiting-decision' || record.status === 'decided') && + (node.status === 'pending' || node.status === 'running')) + this.moveTask(node, 'completed', 'research-completed'); if (record.status !== 'pending' && node?.assignment) { const active = this.active.get(node.assignment.workerId); if (active?.action.kind === 'task' && active.action.assignment === node.assignment && !active.cancelled) { @@ -626,6 +633,7 @@ export abstract class CooperationCore { !this.actionRouteRetired(active.action)) occupy(taskGroup(active.action.task), id); for (const publication of this.proofPublications.values()) if (!this.actionRouteRetired(publication.action)) occupy(taskGroup(publication.action.task), publication.workerId); + for (const preparation of this.preparingTaskTypes.values()) occupy(preparation.groupId, preparation.workerId); for (const review of this.archive.statementReviews ?? []) { const node = nodes.get(review.taskId); if (node && ['translating', 'reviewing'].includes(review.status)) occupy(taskGroup(node.task), review.workerId); @@ -769,6 +777,7 @@ export abstract class CooperationCore { if (!pending.controller.signal.aborted && !pending.current()) pending.controller.abort(); } protected wake() { + this.dispatchRevision++; this.cancelStaleTaskTypes(); this.refreshPlanApproval(); const lead = this.active.get(this.lead.id), canonical = this.archive.canonicalCommit; @@ -786,6 +795,7 @@ export abstract class CooperationCore { this.waiters.clear(); } modelBudgetChanged() { this.refreshGoalProgress(); this.input.save(); this.wake(); } + workerAvailabilityChanged() { this.wake(); } protected rejectWorkerDelivery(worker: ResearchWorker, action: Extract, submission: string, error: Error): DeliveryReceipt { const receipt = rejectedDeliveryReceipt({ assignment: action.assignment, workerId: worker.id, @@ -934,6 +944,10 @@ export abstract class CooperationCore { this.active.set(worker.id, { action, interrupt, notify, requestReady }); this.changed(); } deactivate(worker: ResearchWorker) { this.active.delete(worker.id); this.changed(); } + protected nextCheckDispatchable(node: TaskRecord) { + return !node.nextCheckId || this.archive.nextChecks?.some(record => record.id === node.nextCheckId && + record.status === 'pending' && currentNextCheck(record, this.archive, this.explorationIdentity)) === true; + } current(action: CooperativeAction) { if (action.kind === 'assemble') return !this.failure && !this.stopping && this.liveWorkers.has(this.lead.id) && this.canAssemble(action.seedCommit); if (action.kind === 'lead' && this.assemblyYieldedLeads.has(action)) return false; @@ -958,9 +972,7 @@ export abstract class CooperationCore { } return action.kind !== 'task' || !this.actionRouteRetired(action) && this.archive.tasks.some(node => node.assignment === action.assignment && digest(node.task) === action.assignment.taskDigest && - (!node.nextCheckId || this.archive.nextChecks?.some(record => record.id === node.nextCheckId && record.status === 'pending' && - currentNextCheck(record, this.archive, { problemReceiptDigest: this.input.state.problem.receiptDigest, - environmentDigest: this.input.state.environmentDigest }))) && + this.nextCheckDispatchable(node) && (!node.capacityExploration || currentCapacityExploration(node, this.archive.tasks, this.explorationIdentity)) && (!action.assignment.connectionCheck || taskReferenceDependencies(node) || taskConnectionCheckCurrent(node.task, action.assignment, this.archive.tasks, { environmentDigest: this.input.state.environmentDigest, @@ -1063,8 +1075,9 @@ export abstract class CooperationCore { return [this.node(task.id), ...this.dependencies(task)].some(node => node && (node.pendingValidation || this.preparingStatementTasks.has(node.task.id))); } - protected async waitForDispatch(): Promise { - await this.wait(); + protected async waitForDispatch(observedRevision = this.dispatchRevision): Promise { + // A wake between checking readiness and subscribing already invalidates the selection. + if (observedRevision === this.dispatchRevision) await this.wait(); return RETRY_DISPATCH; } protected visible(task: CooperativeTask): TaskRecord[] { diff --git a/src/solver/cooperationPlanning.ts b/src/solver/cooperationPlanning.ts index 1d626332..f7f355c9 100644 --- a/src/solver/cooperationPlanning.ts +++ b/src/solver/cooperationPlanning.ts @@ -43,10 +43,30 @@ class InvalidLeadPlanDraft extends Error { /** Lead plan acceptance, plan identity and the idle original-goal frontier. */ export abstract class CooperationPlanning extends CooperationIntegration { + /** Notes beyond the legacy plan parser's limit remain available as a draft. */ + protected leadNotes(commit?: string): { text?: string; digest: string } { + const worktree = this.lead.worktree, file = path.join(worktree, 'RESEARCH.md'); + if (commit) { + const [blob, bytes] = git(worktree, ['ls-tree', '--format=%(objectname) %(objectsize)', commit, '--', 'RESEARCH.md']).split(' '); + if (blob && Number(bytes) > MAX_RESEARCH_NOTES_BYTES) return { digest: 'git-blob:' + blob }; + const text = blob ? committedSource(worktree, commit, 'RESEARCH.md') : ''; + return { text, digest: mathDigest(text) }; + } + try { + const text = fs.existsSync(file) ? readMathText(file, MAX_RESEARCH_NOTES_BYTES) : ''; + return { text, digest: mathDigest(text) }; + } catch (error) { + if (!(error instanceof Error) || error.message !== 'math_runtime_file_too_large') throw error; + return { digest: 'git-blob:' + git(worktree, ['hash-object', '--no-filters', '--', file]) }; + } + } + protected syncPlanNotes() { if (!this.archive.planEdited) return; const file = path.join(this.lead.worktree, 'RESEARCH.md'); - const source = fs.existsSync(file) ? readMathText(file, MAX_RESEARCH_NOTES_BYTES) : ''; + const { text: source } = this.leadNotes(); + // The accepted graph is already durable. Leave a large journal intact and use the live plan channel. + if (source === undefined) return; const plan = '```math\n' + formatPlanJson({ tasks: collapseTaskFamilies(this.plannedTasks().map(node => node.task)), groups: this.archive.groups?.map(route => route.group), ...(this.archive.proofRoutes?.length ? { proofRoutes: this.archive.proofRoutes } : {}) }) + '\n```'; // Replace the first plan fence and drop the rest, so an applied revision cannot be read again. @@ -112,17 +132,13 @@ export abstract class CooperationPlanning extends CooperationIntegration { const sourceDigest = commit ? ownedSourceDigest(problem, this.lead.worktree, commit) : mathDigest(canonicalMathJson(problem.ownedFiles.map(file => [file, mathDigest(fs.readFileSync(path.join(this.lead.worktree, problem.projectRelative, file)))]))); - const notes = commit ? (git(this.lead.worktree, ['ls-tree', '--name-only', commit, '--', 'RESEARCH.md']) - ? committedSource(this.lead.worktree, commit, 'RESEARCH.md') : '') : - (fs.existsSync(path.join(this.lead.worktree, 'RESEARCH.md')) - ? readMathText(path.join(this.lead.worktree, 'RESEARCH.md'), MAX_RESEARCH_NOTES_BYTES) : ''); // New peer evidence must release the pause, because a plan input drops any delivery whose task version // has since advanced and would otherwise hide the finding that alone can wake the Lead. The immutable // content of peer publications is that evidence; a peer saving its notes mid-slice is work this Lead // already dispatched and must not re-open the turn on every checkpoint. return mathDigest(canonicalMathJson({ inputDigest: this.planningInputDigest('pause'), evidenceDigest: this.planningEvidenceDigest(), planVersion: this.planVersion(), - sourceDigest, notesDigest: mathDigest(notes) })); + sourceDigest, notesDigest: this.leadNotes(commit).digest })); } /** A completed decision covers its own bookkeeping, but never evidence arriving during that dispatch. */ protected rememberLeadDecision(action: CooperativeAction) { @@ -361,9 +377,8 @@ export abstract class CooperationPlanning extends CooperationIntegration { const { plan, nextCheckDecisions, researchDecisions, progressDecision, configuredGroups, shown, retirement } = this.preparePlan( planInput ?? this.readLeadPlan(leadAction), decidingAction, restoringPlan); const { tasks, proofRoutes } = plan; - const publicationResponseDigest = publication ? this.proposedPlanDigest( - git(this.lead.worktree, ['ls-tree', '--name-only', publication.action.seedCommit, '--', 'RESEARCH.md']) - ? committedSource(this.lead.worktree, publication.action.seedCommit, 'RESEARCH.md') : '') : undefined; + const seedNotes = publication ? this.leadNotes(publication.action.seedCommit) : undefined; + const publicationResponseDigest = seedNotes?.text !== undefined ? this.proposedPlanDigest(seedNotes.text) : seedNotes?.digest; const previousGroups = new Map(this.archive.groups?.map(record => [record.group.id, record])); const current = new Map(this.archive.tasks.map(node => [node.task.id, node])); const invalidated = this.planInvalidation(plan); diff --git a/src/solver/cooperationTaskProofs.ts b/src/solver/cooperationTaskProofs.ts index 90978c10..fae223a2 100644 --- a/src/solver/cooperationTaskProofs.ts +++ b/src/solver/cooperationTaskProofs.ts @@ -21,7 +21,7 @@ import { routeBlockerBasis, type BlockerBasis } from './routeControl'; import { attributeTaskReferences } from './taskReferenceAttribution'; import { checkpointCandidate } from './researchEvidence'; import { committedResearchNotesDigest, feasibilityReviewInputDigest, researchCheckpointInputDigest, researchCheckpointLocalInputDigest, researchCheckpointOutputDigest, - researchHandoffNotesDigest, UNCHANGED_RESEARCH_CHECKPOINT, type ResearchCheckpoint } from './researchCheckpoints'; + researchHandoffNotesDigest, resumableFeasibilityReviewInput, UNCHANGED_RESEARCH_CHECKPOINT, type ResearchCheckpoint } from './researchCheckpoints'; import { savedContextCheckpoint } from './contextCheckpoint'; import { inspectKnowledgeUses, type KnowledgeUse } from './knowledgeUsage'; import { checkKnowledgeApplications } from './knowledgeApplications'; @@ -57,21 +57,29 @@ export abstract class CooperationTaskProofs extends CooperationStatements { protected pendingProofDeliveryRecords = new WeakSet(); abstract interrupted(worker: ResearchWorker, action: CooperativeAction): void; abstract rejected(action: CooperativeAction, feedback: string, commit?: string, incomplete?: boolean): void; - protected feasibilityInputDigest(task: CooperativeTask, workerId: string) { + private feasibilityInput(task: CooperativeTask, workerId: string) { const state = this.input.state; - return feasibilityReviewInputDigest({ task, workerId, tasks: this.archive.tasks, deliveries: this.archive.deliveries ?? [], + return { task, workerId, tasks: this.archive.tasks, deliveries: this.archive.deliveries ?? [], problem: state.problem, environmentDigest: state.environmentDigest, problemReceiptDigest: state.problem.receiptDigest, retrievalDigest: state.retrievalDigest, knowledgeDigest: state.knowledgeDigest, - worktree: this.lead.worktree, canonicalCommit: this.archive.canonicalCommit! }); + worktree: this.lead.worktree, canonicalCommit: this.archive.canonicalCommit! }; + } + protected feasibilityInputDigest(task: CooperativeTask, workerId: string) { + return feasibilityReviewInputDigest(this.feasibilityInput(task, workerId)); } private checkpointInputDigest(task: CooperativeTask, workerId: string) { 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! }); } - private checkpointLocalInputDigest(task: CooperativeTask, workerId: string) { + private checkpointLocalInputDigest(task: CooperativeTask, workerId: string, legacyProgress = false) { return researchCheckpointLocalInputDigest({ task, workerId, tasks: this.archive.tasks, deliveries: this.archive.deliveries ?? [], - environmentDigest: this.input.state.environmentDigest, problemReceiptDigest: this.input.state.problem.receiptDigest }); + environmentDigest: this.input.state.environmentDigest, problemReceiptDigest: this.input.state.problem.receiptDigest }, legacyProgress); + } + private checkpointInputMatches(node: TaskRecord, workerId: string, checkpoint: ResearchCheckpoint, localInputDigest: string) { + if (!checkpoint.localInputDigest) return this.checkpointInputDigest(node.task, workerId) === checkpoint.inputDigest; + return checkpoint.localInputDigest === localInputDigest || Boolean(node.nextCheckId && + checkpoint.localInputDigest === this.checkpointLocalInputDigest(node.task, workerId, true)); } private checkpointOutputDigests = new Map(); private checkpointOutputDigest(worktree: string, commit: string) { @@ -297,9 +305,10 @@ export abstract class CooperationTaskProofs extends CooperationStatements { const node = this.node(taskId), worker = this.input.workers.find(worker => worker.id === node?.assignment?.workerId); if (!node || digest(node.task) !== checkpoint.taskDigest) { delete this.archive.researchCheckpoints![taskId]; continue; } if (!worker || node.status !== 'blocked' || !node.feedback?.startsWith('math_research_checkpoint_unchanged')) continue; - const inputChanged = checkpoint.localInputDigest - ? this.checkpointLocalInputDigest(node.task, worker.id) !== checkpoint.localInputDigest - : this.checkpointInputDigest(node.task, worker.id) !== checkpoint.inputDigest; + const localInputDigest = this.checkpointLocalInputDigest(node.task, worker.id); + const inputChanged = !this.checkpointInputMatches(node, worker.id, checkpoint, localInputDigest); + // Upgrade a matching old pause before processing the next publication after restore. + if (!inputChanged && node.nextCheckId) checkpoint.localInputDigest = localInputDigest; // Seeding another responsibility suspends its old draft before the new model session exists. // That host-written output cannot advance the paused task, even while its session id is stale. const session = this.input.state.workers?.find(record => record.id === worker.id), active = this.active.get(worker.id)?.action; @@ -449,9 +458,8 @@ export abstract class CooperationTaskProofs extends CooperationStatements { if (!saved || !current() || node.assignment !== assignment || this.archive.researchDrafts?.[node.task.id] !== draft) return false; // Snapshot inspection yields to other publications. Only the inputs still // current after that wait may inherit the old unchanged counters. - sameCheckpointInput = checkpoint?.taskDigest === digest(node.task) && (checkpoint.localInputDigest - ? checkpoint.localInputDigest === this.checkpointLocalInputDigest(node.task, assignment.workerId) - : checkpoint.inputDigest === this.checkpointInputDigest(node.task, assignment.workerId)); + sameCheckpointInput = checkpoint?.taskDigest === digest(node.task) && this.checkpointInputMatches(node, assignment.workerId, + checkpoint, this.checkpointLocalInputDigest(node.task, assignment.workerId)); const canonical = this.archive.canonicalCommit!; const canonicalChanged = ownedSourceDigest(problem, this.lead.worktree, canonical) !== saved.canonicalSourceDigest; this.suspendResearchDrafts(worker, node.task.id); @@ -505,9 +513,11 @@ export abstract class CooperationTaskProofs extends CooperationStatements { if (!draft || assignment.workerId !== worker.id) return false; const problem = this.input.state.problem; try { - if (isFeasibilityReview(node.task) && (!draft.feasibilityInputDigest || - draft.feasibilityInputDigest !== assignment.feasibilityInputDigest || - draft.feasibilityInputDigest !== this.feasibilityInputDigest(node.task, worker.id))) { + const feasibility = isFeasibilityReview(node.task); + const resumeInput = () => draft.feasibilityInputDigest === assignment.feasibilityInputDigest + ? resumableFeasibilityReviewInput(this.feasibilityInput(node.task, worker.id), draft) : undefined; + let feasibilityInputDigest = feasibility ? resumeInput() : undefined; + if (feasibility && !feasibilityInputDigest) { draft.suspended = true; this.input.emit('research_draft_restore_failed', { taskId: node.task.id, reason: 'math_feasibility_draft_input_changed' }); @@ -519,8 +529,8 @@ export abstract class CooperationTaskProofs extends CooperationStatements { 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; - // Snapshot inspection yields; input changes during it still require a fresh review. - if (isFeasibilityReview(node.task) && draft.feasibilityInputDigest !== this.feasibilityInputDigest(node.task, worker.id)) { + // Snapshot inspection yields. Recheck against the latest inputs before restoring. + if (feasibility && !(feasibilityInputDigest = resumeInput())) { draft.suspended = true; this.input.save(); return false; @@ -537,7 +547,8 @@ export abstract class CooperationTaskProofs extends CooperationStatements { // 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, - canonicalCommit: this.archive.canonicalCommit, connectionCheck: undefined }; + canonicalCommit: this.archive.canonicalCommit, connectionCheck: undefined, + ...(feasibility ? { feasibilityInputDigest } : {}) }; } else { // Restore the validated snapshot so its frozen seed remains an ancestor. git(worker.worktree, ['reset', '--hard', draft.commit]); @@ -585,8 +596,7 @@ export abstract class CooperationTaskProofs extends CooperationStatements { const inputDigest = this.checkpointInputDigest(node.task, worker.id), outputDigest = this.checkpointOutputDigest(worker.worktree, commit); const localInputDigest = this.checkpointLocalInputDigest(node.task, worker.id); const candidate = checkpointCandidate(notes, artifacts); - const sameInput = previous?.taskDigest === taskDigest && (previous.localInputDigest - ? previous.localInputDigest === localInputDigest : previous.inputDigest === inputDigest); + const sameInput = previous?.taskDigest === taskDigest && this.checkpointInputMatches(node, worker.id, previous, localInputDigest); const count = sameInput && previous.outputDigest === outputDigest ? previous.count + 1 : 1; const unchangedEvidenceCount = sameInput && previous.candidateOutputDigest === candidate.digest diff --git a/src/solver/modules/context.ts b/src/solver/modules/context.ts index a5412474..05b7aeaa 100644 --- a/src/solver/modules/context.ts +++ b/src/solver/modules/context.ts @@ -90,6 +90,8 @@ export type ContextBundle = Readonly<{ continuationManifest?: ContextManifest; /** Recompile before dispatch so an added checkpoint instruction participates in selection and accounting. */ compileDispatch?: (options: ResearchDispatchOptions, current?: ContextBundle) => CompiledContext; + /** Re-anchor exact current inputs after compaction with less optional history. */ + compileCompactedDispatch?: (options: ResearchDispatchOptions, current?: ContextBundle) => CompiledContext | undefined; scope: 'original-problem-and-allowed-library' | 'fixed-statement'; sources: Readonly<{ problemReceiptDigest: string }>; manifest?: ContextManifest; @@ -121,9 +123,26 @@ function compileCustomDispatch(context: ContextBundle, options: ResearchDispatch return compiled; } +export function compactedResearchDispatch(context: ContextBundle, options: ResearchDispatchOptions): ContextBundle | undefined { + let compiled: CompiledContext | undefined; + try { + compiled = context.compileCompactedDispatch?.(options, context); + } catch (error) { + // A valid full dispatch can fit when the compacted prompt's required recovery note cannot. + if (!(error instanceof TaskContextError) || error.code !== 'math_context_mandatory_overflow') throw error; + return undefined; + } + if (!compiled || Buffer.byteLength(compiled.message) >= Buffer.byteLength(context.message)) return; + return withResearchDispatch(context, compiled); +} + /** Finalize the actual M4 output, including replacements of the built-in prompt. */ export function finalizeResearchDispatch(context: ContextBundle, options: ResearchDispatchOptions = {}): ContextBundle { const compiled = context.compileDispatch?.(options, context) ?? compileCustomDispatch(context, options); + return withResearchDispatch(context, compiled); +} + +function withResearchDispatch(context: ContextBundle, compiled: CompiledContext): ContextBundle { return { ...context, ...compiled, ...(context.knowledgeRetrievals ? { knowledgeRetrievals: context.knowledgeRetrievals.map(retrieval => ({ ...retrieval, included: compiled.manifest.included.some(item => item.id === retrieval.sectionId), @@ -329,11 +348,15 @@ ${access.corpusFile ? `For library lookup, run ${command} search-lean --workspac const result: ContextBundle = { ...compiled, ...(access.knowledgeSnapshot ? { knowledgeRetrievals: knowledgeSections.map(section => ({ ...section.knowledge, included: compiled.manifest?.included.some(item => item.id === section.id) ?? false, omissionReason: compiled.manifest?.omitted.find(item => item.id === section.id)?.reason })) } : {}) }; - const recompile = result.compileDispatch; + const recompile = result.compileDispatch, recompileCompacted = result.compileCompactedDispatch; if (!recompile) return result; - return { ...result, compileDispatch: (options, current = result) => { - if (current.instructions === result.instructions && current.message === result.message && - current.continuationMessage === result.continuationMessage) return recompile(options); + const builtInPrompt = (current: ContextBundle) => current.instructions === result.instructions && + current.message === result.message && current.continuationMessage === result.continuationMessage; + return { ...result, ...(recompileCompacted ? { + compileCompactedDispatch: (options: ResearchDispatchOptions, current = result) => + builtInPrompt(current) ? recompileCompacted(options) : undefined, + } : {}), compileDispatch: (options, current = result) => { + if (builtInPrompt(current)) return recompile(options); // Spreading a built-in context must not let its captured compiler overwrite a custom M4 prompt. const changedMessage = current.message !== result.message; const inheritedContinuation = current.continuationMessage === result.continuationMessage; @@ -498,7 +521,7 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio : ''; // A revision states only changed tasks; the host expands it against the accepted graph and validates the result. const planRevisionRules = action.kind === 'lead' && cooperation.tasks.length - ? 'Revise the accepted graph instead of retyping it. RESEARCH.md keeps the host-synced accepted graph in a math fence with one task per line; grep it by task id and never rewrite or copy it wholesale. ' + + ? 'Revise the accepted graph instead of retyping it. Read the current task graph in COOPERATION.json or grep the host-synced accepted graph in the math fence in RESEARCH.md. If RESEARCH.md exceeds 1,000,000 bytes, use the dispatch delivery log for plan submissions and consult COOPERATION.json for the accepted graph. ' + `Use this revision schema in the current delivery-log event, or in a math-plan fence in RESEARCH.md if returning without publication: {"baseVersion":${JSON.stringify(action.planVersion ?? '')},"upsert":[{"id":"existing_task","status":"paused"},{"id":"new_helper","kind":"lemma","objective":"...","theoremName":"...","type":"...","dependsOn":[]}],"remove":["obsolete_task"]}. ` + 'This graph schema must also include every required researchDecisions, progressReview and nextCheckDecisions field from current Lead decision requirements in the same JSON object. An upsert of an existing id replaces only the fields it supplies (null deletes a field; a changed kind replaces the whole task); a new id needs a complete task definition. ' + 'Unlisted tasks, groups and proofRoutes stay unchanged; supply groups or proofRoutes only to replace that whole list. ' + @@ -752,7 +775,8 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio ? { id: 'lead-decision-requirements', kind: 'assignment' as const, text: 'Current Lead decision requirements (this dispatch only):\n' + cooperation.leadDecisionInstruction } : undefined; - const compileFull = (checkpointInstruction?: string, taskSwitch?: boolean) => compileTaskContext({ ...compilation, instructions, optional, taskSwitch, + const compileFull = (checkpointInstruction?: string, taskSwitch?: boolean, compactedResume?: boolean) => compileTaskContext({ + ...compilation, instructions, optional, taskSwitch, compactedResume, mandatory: [...dispatchPrefix(checkpointInstruction), ...(leadDecision ? [leadDecision] : []), ...(compilation.mandatory ?? []), ...receiptIndex, { id: 'work-contract', kind: 'assignment', text: 'Host work contract (one product; completion is not proof acceptance):\n' + JSON.stringify(workContract) }, @@ -797,6 +821,8 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio const compiledContinuation = continuationText === undefined ? undefined : compileContinuation(); return { ...context, assignment: action, workContract, instructions, ...full, continuationMessage: compiledContinuation?.message, continuationManifest: compiledContinuation?.manifest, + ...(compiledContinuation ? { compileCompactedDispatch: (options: ResearchDispatchOptions) => + compileFull(options.checkpointInstruction, false, true) } : {}), compileDispatch: options => options.taskSwitch && taskContinuation ? compileFull(options.checkpointInstruction, true) : options.continuation && compiledContinuation ? options.checkpointInstruction ? compileContinuation(options.checkpointInstruction) : compiledContinuation diff --git a/src/solver/modules/organization.ts b/src/solver/modules/organization.ts index a827fbb3..141a7452 100644 --- a/src/solver/modules/organization.ts +++ b/src/solver/modules/organization.ts @@ -71,7 +71,7 @@ export function assessTaskResponsibility(node: TaskRecord, worker: Pick peer !== node && peer.status === 'running' && peer.assignment && peer.assignment.workerId === node.task.preferredOwnerId && peer.assignment.taskId === peer.task.id && peer.assignment.taskDigest === taskVersion(peer.task)); @@ -108,10 +108,11 @@ export function assignSharedResearchTask(ready: readonly TaskRecord[], worker: R if (!first || eligible.length === 1) return first; // An executable original proof can close the problem. Conditional connection checks // only test an application and may still need unscreened mathematical research. - const connection = (node: TaskRecord) => node.assignment + const connection = (node: TaskRecord) => node.assignment && !releasedPin(node, node.assignment.workerId, stopped) ? taskConnectionCheckCurrent(node.task, node.assignment, tasks) : freshTaskConnection(node, tasks, groups); if (first.task.kind === 'goal' && !connection(first) || !first.attempts && isFeasibilityReview(first.task)) return first; - if (first.connectionCheckpoint && first.connectionCheckpoint.basisDigest === first.assignment?.connectionCheck?.basisDigest && + if (first.connectionCheckpoint && !releasedPin(first, first.assignment?.workerId, stopped) && + first.connectionCheckpoint.basisDigest === first.assignment?.connectionCheck?.basisDigest && connection(first)) { const inputs = new Set(taskDependencyRecords(first.task, tasks)); const priority = createProofRoutePriority(tasks, { groups }); diff --git a/src/solver/research.ts b/src/solver/research.ts index 63494410..13fea360 100644 --- a/src/solver/research.ts +++ b/src/solver/research.ts @@ -20,7 +20,7 @@ import { isStatementAction } from './statementReview'; import { rememberSolverFailure, solverSourceFeedback } from './feedback'; import type { SolverModules } from './modules'; import { solverProofIsCurrent, type ProofCheck } from './modules/evidence'; -import { finalizeResearchDispatch, type ContextBundle } from './modules/context'; +import { compactedResearchDispatch, finalizeResearchDispatch, type ContextBundle } from './modules/context'; import type { KnowledgeContextSnapshot } from './knowledgeContext'; import { researchTaskRole, type ResearchWorker } from './modules/organization'; import type { ResearchOperation } from './modules/value'; @@ -292,6 +292,7 @@ export async function runResearchWorkers(input: { if (delayMs > 0) await delay(delayMs, undefined, { signal }); signal.throwIfAborted(); recovery.phase = 'retrying'; + cooperation?.workerAvailabilityChanged(); } finally { recovery.waitedMs += Math.max(0, Date.now() - started); save(); } @@ -370,9 +371,16 @@ export async function runResearchWorkers(input: { let turnActivity: ((activity: MathAgentActivity) => void) | undefined; let advisoryTurn: { scope: string; contentDigest?: string; inputDigest?: string } | undefined; let turnContext: { digest: string; fresh: boolean } | undefined; - // A thread can revisit a responsibility after other tasks. Keep only contracts actually - // dispatched in this process; a cold resume or provider compaction must send the full context. - const dispatchedContexts = new Map(); + // A thread can revisit a responsibility after other tasks. After compaction only its + // most recent responsibility can use a smaller dispatch, with exact inputs re-anchored. + const dispatchedContexts = new Map(); + const markCompaction = (threadId: string, compaction: 'pending' | 'completed') => { + const latest = [...dispatchedContexts].at(-1); + dispatchedContexts.clear(); + if (latest?.[1].threadId === threadId) + dispatchedContexts.set(latest[0], { ...latest[1], compaction }); + }; let rebuildContext = false; const usage = new ResearchUsage({ state, research, maxTotalTokens: input.maxTotalTokens, signal, remainingMs: () => budget().remainingMs, changed: () => { updateUsage(); save(); }, emit }); @@ -638,7 +646,8 @@ export async function runResearchWorkers(input: { } // Native context maintenance applies to Skill sessions without cooperative assignments too. if (live() && activity.itemType === 'contextCompaction' && - (activity.event === 'item_started' || activity.event === 'item_completed')) dispatchedContexts.clear(); + (activity.event === 'item_started' || activity.event === 'item_completed')) + markCompaction(activeSession.threadId, activity.event === 'item_started' ? 'pending' : 'completed'); if (activity.itemType === 'contextCompaction' && activity.event === 'item_completed') milestone?.compacted(); if (current() && activity.itemType === 'contextCompaction') { if (activity.event === 'item_started' && compactionStartedAt === undefined) { @@ -1006,7 +1015,8 @@ export async function runResearchWorkers(input: { cooperativeCheckpoint = proofHandoffCheckpoint || checkpointRequested && (resultStatus === 'interrupted' || resultStatus === 'checkpoint' || checkpointClosing && resultStatus === 'failed' && researchFailureReason(detail) === 'math_codex_transport_closed'); completed = resultStatus === 'completed'; - if (completed) recovered(); + // An acknowledged scheduler interruption also proves the worker can run again. + if (completed || armed && cooperativeCheckpoint && (resultStatus === 'interrupted' || resultStatus === 'checkpoint')) recovered(); return result; } catch (error) { @@ -1220,8 +1230,7 @@ export async function runResearchWorkers(input: { } } if (await maintainContext(assignment) !== 'unchanged') { - // Recompile the complete current task after compaction or rotation; a short continuation - // may refer to context the native summary no longer retains. + // Select the dispatch again if maintenance changed what this thread retains. rebuildContext = true; if (unreserveTurn()) save(); return false; @@ -1258,6 +1267,7 @@ export async function runResearchWorkers(input: { emit('worker_cooling_down', { reason: cooldown.reason, cycle: cooldown.cycle, delayMs: cooldown.delayMs, nextRetryAt: research.recovery.nextRetryAt }); save(); + cooperation?.workerAvailabilityChanged(); await waitForRecovery(); retries = 0; return; @@ -1301,7 +1311,7 @@ export async function runResearchWorkers(input: { usage.beginMaintenance(assignment); explicitCompaction = true; try { await session.compact(); signal.throwIfAborted(); - dispatchedContexts.clear(); compactedUsageVersion = contextUsageVersion; + markCompaction(threadId, 'completed'); compactedUsageVersion = contextUsageVersion; research.contextCheckpoint = undefined; research.contextCheckpointBaseline = { threadId, notesDigest: checkpointNotesDigest() }; research.lastInputTokens = session.lastInputTokens; @@ -1581,17 +1591,21 @@ export async function runResearchWorkers(input: { const fullContextBasis = selectBasis?.(currentContext.manifest); const dispatchedContext = responsibility === undefined ? undefined : dispatchedContexts.get(responsibility); const researchInputsChanged = fullContextBasis && dispatchedContext?.researchInputDigest !== fullContextBasis.dispatchDigest; - const continuation = access.nativeContinuity !== false && !researchInputsChanged && responsibility !== undefined && Boolean(research.threadId) && + const sameResponsibility = access.nativeContinuity !== false && !researchInputsChanged && responsibility !== undefined && Boolean(research.threadId) && currentContext.continuationMessage !== undefined && dispatchedContext?.threadId === research.threadId; + const continuation = sameResponsibility && !dispatchedContext?.compaction; const taskSwitch = access.nativeContinuity !== false && sameRouteSwitch && !dispatchedContext && - Boolean(research.threadId && dispatchedContexts.size) && currentContext.continuationMessage !== undefined; - Object.assign(currentContext, finalizeResearchDispatch(currentContext, { - continuation, - taskSwitch, - checkpointInstruction: research.threadId && research.contextCheckpoint?.threadId === research.threadId && !currentCheckpointNotesDigest() - ? contextCheckpointInstruction(assignment) : undefined, - })); + Boolean(research.threadId && dispatchedContexts.size) && currentContext.continuationMessage !== undefined && + ![...dispatchedContexts.values()].some(context => context.compaction); + const checkpointInstruction = research.threadId && research.contextCheckpoint?.threadId === research.threadId && !currentCheckpointNotesDigest() + ? contextCheckpointInstruction(assignment) : undefined; + const smallerContext = sameResponsibility && dispatchedContext?.compaction === 'completed' + ? compactedResearchDispatch(currentContext, { checkpointInstruction }) : undefined; + // Preserve the entire admitted research dependency inventory even if its evidence was optional. + const compacted = smallerContext && selectBasis?.(smallerContext.manifest).dispatchDigest === fullContextBasis?.dispatchDigest + ? smallerContext : undefined; + Object.assign(currentContext, compacted ?? finalizeResearchDispatch(currentContext, { continuation, taskSwitch, checkpointInstruction })); const contextBasis = taskSwitch ? selectBasis?.(currentContext.manifest) : fullContextBasis; // A refreshed Lead nonce updates session instructions while preserving its planning history. if (session && sessionInstructions !== currentContext.instructions) await close(); @@ -1602,6 +1616,10 @@ export async function runResearchWorkers(input: { } break; } + if (compacted && assignment && session!.threadId !== dispatchedContext?.threadId) { + dispatchedContexts.clear(); + releaseUnstartedTurn(assignment); continue; + } let candidate: ResearchCandidate | undefined; let executedTurnId: string | undefined; let executionError: string | undefined; @@ -1623,7 +1641,7 @@ export async function runResearchWorkers(input: { researchInputDigest: contextBasis?.dispatchDigest }); if (dispatchedContexts.size > 32) dispatchedContexts.delete(dispatchedContexts.keys().next().value!); } else dispatchedContexts.clear(); - emit('context_dispatched', { mode: taskSwitch ? 'task-switch' : continuation ? 'continuation' : 'full', threadId: turnSession.threadId, + emit('context_dispatched', { mode: compacted ? 'compacted' : taskSwitch ? 'task-switch' : continuation ? 'continuation' : 'full', threadId: turnSession.threadId, messageBytes: Buffer.byteLength(currentContext.message), messageDigest: mathDigest(currentContext.message), compiledContentDigest: currentContext.manifest?.contentDigest }); started(turnId); @@ -1733,8 +1751,11 @@ export async function runResearchWorkers(input: { research.check = undefined; if (assignment) cooperation!.rejected(assignment, sourceError, undefined, turn !== 'completed'); save(); emit('source_rejected', { reason: sourceError }); - if (turn === 'failed' && turnError && !recoverableResearchFailure(turnError) && !locallyStopped(turnError)) - throw new Error(researchFailureReason(turnError), { cause: turnError }); + if (turn === 'failed' && turnError && !locallyStopped(turnError)) { + if (!recoverableResearchFailure(turnError)) throw new Error(researchFailureReason(turnError), { cause: turnError }); + // Independent work has no task rejection to bound a corrective cycle after a request failure. + if (!cooperation) throw new Error(sourceError, { cause: turnError }); + } // A deterministic saved-source rejection needs a corrective turn even when the native // request failed or yielded. The next dispatch carries sourceFeedback; no invalid source // is committed or checked, and no host repair modifies the writer's saved work. diff --git a/src/solver/researchCheckpoints.ts b/src/solver/researchCheckpoints.ts index 108c284a..9e117a0c 100644 --- a/src/solver/researchCheckpoints.ts +++ b/src/solver/researchCheckpoints.ts @@ -1,13 +1,16 @@ import { canonicalMathJson, mathDigest } from '../math/mathRuntimeIo'; -import { ownedSourceDigest } from './cooperativeProof'; +import { inspectLeanDeclarationRegions, startsLeanSourceCommand } from '../math/leanSource'; +import { isSimpleLeanName, maskLeanCommentsAndStrings } from '../math/leanSyntax'; +import { declarationStartWithDoc, ownedSourceDigest } from './cooperativeProof'; import { deliveryInputFields } from './cooperationShared'; import { MAX_RESEARCH_NOTES_BYTES, type DeliveryRecord } from './deliveries'; import { mathematicalGapVisible } from './mathematicalGaps'; import { taskDependencyRecords } from './modules/search'; import { captureObligationSnapshot } from './obligationProgress'; import { committedSource, git, type SolverProblem } from './problem'; -import type { CheckpointCandidate } from './researchEvidence'; +import { checkpointCandidate, type CheckpointCandidate } from './researchEvidence'; import { captureResearchBasis } from './researchRecords'; +import { researchSourceTasks, scopedResearchSources } from './researchSources'; import { routeBlockerBasis } from './routeControl'; import { taskGroup, taskVersion, type CooperativeTask, type TaskRecord } from './tasks'; @@ -38,14 +41,25 @@ function visibleDeliveries(input: CheckpointInput) { }); } +function scopedProgressEvidence(record: DeliveryRecord) { + const { summary: _summary, ...fields } = deliveryInputFields(record); + const artifactDigest = record.artifacts?.artifacts.length ? checkpointCandidate('', record.artifacts).digest : undefined; + if (!artifactDigest && !fields.evidenceRefs.length && !fields.findingDigest && !fields.lemmaRequests?.length && + !fields.mathematicalGap && !fields.checkOutcome && !fields.sourceUses?.length && !fields.searchCheckpoint) return; + return { ...fields, artifactDigest }; +} + /** Keep scheduling identity identical during live recovery and cold continuation. */ -export function researchCheckpointLocalInputDigest(input: CheckpointInput) { +export function researchCheckpointLocalInputDigest(input: CheckpointInput, legacyProgress = false) { const dependencies = taskDependencyRecords(input.task, input.tasks); const relevant = new Set([input.task.id, ...dependencies.map(node => node.task.id)]); - const deliveries = [...new Set(visibleDeliveries(input).filter(record => relevant.has(record.taskId ?? '') || - record.dependencies.some(reference => reference.taskId === input.task.id)).map(record => canonicalMathJson({ - ...deliveryInputFields(record), findingDigest: record.findingDigest, - })))].sort(); + const scopedCheck = !legacyProgress && input.tasks.some(node => node.task.id === input.task.id && node.nextCheckId); + const deliveries = [...new Set(visibleDeliveries(input).flatMap(record => { + if (!relevant.has(record.taskId ?? '') && !record.dependencies.some(reference => reference.taskId === input.task.id)) return []; + // Keep progress prose visible to workers, but don't treat a handoff summary as new check evidence. + const fields = scopedCheck && record.kind === 'progress' ? scopedProgressEvidence(record) : deliveryInputFields(record); + return fields ? [canonicalMathJson(fields)] : []; + }))].sort(); return mathDigest(canonicalMathJson({ taskDigest: taskVersion(input.task), basis: routeBlockerBasis(input.task, input.tasks, input.environmentDigest, input.problemReceiptDigest), dependencies: captureObligationSnapshot(dependencies, { environmentDigest: input.environmentDigest }).digest, @@ -63,11 +77,13 @@ export function researchCheckpointInputDigest(input: CheckpointInput & { { environmentDigest: input.environmentDigest }).digest, deliveries })); } -/** Intermediate review notes belong to one reviewer and the exact inspected inputs, never a verdict. */ -export function feasibilityReviewInputDigest(input: CheckpointInput & { +type FeasibilityReviewInput = CheckpointInput & { problem: SolverProblem; worktree: string; canonicalCommit: string; retrievalDigest?: string; knowledgeDigest?: string; -}) { +}; + +/** Intermediate review notes belong to one reviewer and the exact inspected inputs, never a verdict. */ +export function feasibilityReviewInputDigest(input: FeasibilityReviewInput) { return mathDigest(canonicalMathJson({ workerId: input.workerId, basis: captureResearchBasis(input.task, { problemReceiptDigest: input.problemReceiptDigest, environmentDigest: input.environmentDigest, retrievalDigest: input.retrievalDigest, knowledgeDigest: input.knowledgeDigest, @@ -76,6 +92,61 @@ export function feasibilityReviewInputDigest(input: CheckpointInput & { }) })); } +/** Carry provisional notes onto a new seed only for a recognizable, independent source addition. */ +export function resumableFeasibilityReviewInput(input: FeasibilityReviewInput, + saved: { feasibilityInputDigest?: string; canonicalCommit?: string; seedCommit?: string }): string | undefined { + if (!saved.feasibilityInputDigest) return; + const current = feasibilityReviewInputDigest(input); + if (saved.feasibilityInputDigest === current) return current; + if (!saved.seedCommit || !saved.canonicalCommit || saved.canonicalCommit === input.canonicalCommit) return; + try { + // Recompute the saved identity with today's task, evidence and environment. + // A changed dependency or knowledge input must still start a fresh review. + if (saved.feasibilityInputDigest !== feasibilityReviewInputDigest({ ...input, canonicalCommit: saved.canonicalCommit })) return; + const { problem, worktree, task, tasks } = input; + const sources = (commit: string) => Object.fromEntries(problem.ownedFiles.map(file => + [file, committedSource(worktree, commit, `${problem.projectRelative}/${file}`)])); + const previous = sources(saved.seedCommit); + const next = scopedResearchSources(problem, task, sources(input.canonicalCommit), researchSourceTasks(tasks)); + const changed = problem.ownedFiles.filter(file => previous[file] !== next[file]); + if (!changed.length) return current; + // Without explicit inspection inputs, we cannot distinguish new evidence from + // an unrelated declaration in the reviewer's visible source. + if (!task.dependsOn.length) return; + const dependencies = taskDependencyRecords(task, tasks); + const ids = new Set(dependencies.map(node => node.task.id)); + const names = new Set([...Object.values(previous), + canonicalMathJson([task, dependencies.map(node => ({ task: node.task, finding: node.finding })), + input.deliveries.filter(record => record.taskId && ids.has(record.taskId) && record.status !== 'superseded')])] + .flatMap(text => text.match(/[\p{L}\p{M}\p{N}_'?!]+/gu) ?? [])); + if (changed.every(file => file.endsWith('.lean') && !Object.hasOwn(problem.frozenFiles ?? {}, file) && + onlyNewPlainLemmas(previous[file]!, next[file]!, names))) return current; + } catch { + // An unavailable prior seed or an ambiguous source scope cannot establish equivalence. + } +} + +function onlyNewPlainLemmas(before: string, after: string, knownNames: ReadonlySet): boolean { + let reconstructed = '', cursor = 0; + const regions = inspectLeanDeclarationRegions(after); + const visible = maskLeanCommentsAndStrings(after); + for (const [index, region] of regions.entries()) { + const start = after.lastIndexOf('\n', region.startOffset - 1) + 1; + const name = region.name.split('.').at(-1)!; + if (!isSimpleLeanName(region.name) || knownNames.has(name) || + after.slice(start, region.startOffset).trim() || + !/^(?:theorem|lemma)\s/u.test(after.slice(region.startOffset, region.bodyOffset)) || + declarationStartWithDoc(after, region.startOffset, index ? regions[index - 1]!.endOffset : 0) !== start) continue; + // Declaration regions are indentation based. Do not erase a following + // command just because it used greater indentation than the lemma. + if (visible.slice(region.bodyOffset, region.endOffset).split('\n').slice(1) + .some(line => startsLeanSourceCommand(line.trimStart()))) continue; + reconstructed += after.slice(cursor, start); + cursor = region.endOffset; + } + return cursor > 0 && reconstructed + after.slice(cursor) === before; +} + export const researchCheckpointOutputDigest = (problem: SolverProblem, worktree: string, commit: string) => mathDigest(canonicalMathJson({ sourceDigest: ownedSourceDigest(problem, worktree, commit), notesBlob: git(worktree, ['ls-tree', '--format=%(objectname)', commit, '--', 'RESEARCH.md']) })); diff --git a/src/solver/run.ts b/src/solver/run.ts index b56587ee..7207b383 100644 --- a/src/solver/run.ts +++ b/src/solver/run.ts @@ -110,7 +110,7 @@ export async function runSolver(args: string[], root: string, customModules?: So console.log('Accepted proofs automatically generate audited explanations of every original target. --explanation-language zh|en selects the language (default zh; resume keeps the previous language). --no-explanations skips generation. The result.explanations field records progress and artifact/proof.md paths. Explanation failures preserve proof acceptance and exit code; --resume retries them without solving again. Explanation time and tokens are separate from solving limits.'); console.log('--library-catalog FILE --library-catalog-sha256 DIGEST enables agent search/get/request against one pinned release. Installation requests end this frozen run for host-controlled continuation.'); console.log('--continuation-manifest FILE attaches explicit historical sources and notes without changing the verbatim task file. Resume retains the frozen attachment identity; historical material remains advisory.'); - console.log('--continuation-source-run OLD_RESULT_OR_STATE initializes a new cooperative run from the old run, freshly checks its saved helpers, and starts solving in the same process. Use --resume to retry an interrupted zero-turn initialization; combine with --startup-only to retain a prepared checkpoint.'); + console.log('--continuation-source-run OLD_RESULT_OR_STATE initializes a new cooperative run from the old run, freshly checks its saved helpers, and starts solving in the same process. With --startup-only, the run freezes its continuation and checks saved helpers when resumed. Use --resume to retry an interrupted zero-turn initialization.'); console.log('--check-statement also elaborates the target files at startup (theorem bodies may still be sorry) and fails with math_statement_check_failed on a Lean error; statement-diagnostics.json keeps the messages.'); console.log('--plan-approval holds every worker after the first accepted plan until a person approves that exact plan version (queuePlanApproval, the web workbench). The Lead takes a revision turn only for Lead guidance written while it waits. Waiting counts toward --max-run-seconds. Requires cooperative coordination and at least 2 workers; resume requires the same setting.'); console.log('Lead planning and ordinary research first yield a resumable scheduling checkpoint after 120 seconds, with a reminder after 90 seconds. Lead planning keeps 120-second slices; ordinary research backs off to at most 960 seconds. Saved threads and drafts survive resume. Proof turns and total solving budgets are unchanged.'); @@ -252,6 +252,7 @@ export async function runSolver(args: string[], root: string, customModules?: So let ownedState: SolverRunState | undefined; let proofEnvironment: Awaited> | undefined; let continuationSeeding = false; + let continuationSourceRun = values['continuation-source-run']; let ownsRun = false; let publishedExit: number | undefined; const emit = (event: string, details = {}) => console.log(JSON.stringify({ event, at: Date.now(), ...details, @@ -397,6 +398,7 @@ export async function runSolver(args: string[], root: string, customModules?: So let sourceFeedback: string | undefined; if (values.resume) { state = resumedState!; + continuationSourceRun ??= state.pendingContinuationSource; assertAgentTeamProcessesStopped(state); if (canonicalMathJson(state.agentHarness ?? null) !== canonicalMathJson(agentHarness ?? null)) throw new Error('math_resume_harness_identity_changed'); @@ -660,10 +662,11 @@ export async function runSolver(args: string[], root: string, customModules?: So const failedPreparation = peerPreparation.find(result => result.status === 'rejected'); if (failedPreparation?.status === 'rejected') throw failedPreparation.reason; let freshContinuationChecks: readonly TaskProof[] | undefined; - if (values['continuation-source-run']) { + if (continuationSourceRun) { save(); continuationSeeding = true; - await (singleSkill ? seedSingleSolverContinuation : seedSolverContinuation)({ sourceRun: values['continuation-source-run'], run: stateFile, root, buildManifest: buildFile, + await (singleSkill ? seedSingleSolverContinuation : seedSolverContinuation)({ sourceRun: continuationSourceRun, run: stateFile, root, buildManifest: buildFile, signal, lease, preparedEnvironment: env, timeoutMs: maxRunMs === Infinity ? Infinity : Math.max(1, preparationMs - (Date.now() - preparationStarted)), + deferChecks: values['startup-only'], onProgress: emit, onSeeded: (seeded, checks) => { state = ownedState = seeded; freshContinuationChecks = checks; } }); continuationSeeding = false; if (!state.continuationDigest) throw new Error('math_continuation_identity_missing'); @@ -765,7 +768,7 @@ export async function runSolver(args: string[], root: string, customModules?: So if (ownedState) { // A zero-turn continuation can retry any preparation step, including // snapshot distribution and startup-only output after the seed handoff. - if (!(preparing && values['continuation-source-run'] && ownedState.phase === 'prepared')) + if (!(preparing && continuationSourceRun && ownedState.phase === 'prepared')) ownedState.phase = 'finished'; if (ownedState.solveStartedAt && !ownedState.solveFinishedAt) ownedState.solveFinishedAt = Date.now(); if (executionClock) ownedState.solveWaitingMs = executionClock.waitingMs(); diff --git a/tests/contextDispatchBudget.test.ts b/tests/contextDispatchBudget.test.ts index 704cf13d..dd174a67 100644 --- a/tests/contextDispatchBudget.test.ts +++ b/tests/contextDispatchBudget.test.ts @@ -4,7 +4,7 @@ import { canonicalMathJson, mathDigest } from '../src/math/mathRuntimeIo'; import { compileTaskContext, DEFAULT_TASK_CONTEXT_BYTES, frozenSourceContext, type TaskContextInput } from '../src/solver/contextCompiler'; import { rejectedDeliveryReceipt, deliveryReceiptFeedback, type DeliveryReceipt } from '../src/solver/deliveryReceipts'; import type { DeliveryRecord } from '../src/solver/deliveries'; -import { buildResearchContext, finalizeResearchDispatch } from '../src/solver/modules/context'; +import { buildResearchContext, compactedResearchDispatch, finalizeResearchDispatch } from '../src/solver/modules/context'; import type { LeanResidualGoal } from '../src/math/leanResidualGoals'; import type { SolverProblem } from '../src/solver/problem'; import { prepareResearchDelivery, ResearchAdmissionError } from '../src/solver/researchAdmission'; @@ -122,6 +122,28 @@ function rejectedFindings(maxOptionalContextBytes = 0) { } describe('bounded continuation dispatch', () => { + it('keeps exact current inputs in a smaller dispatch after the native summary can omit them', () => { + const dependency = helper('dependency', [], '∀ x : Nat, x + 0 = x'); + const task = helper('current', [dependency.id]), assignment = { taskId: task.id, taskDigest: taskVersion(task), + workerId: 'researcher', seedCommit: baseCommit }; + const cooperation = { tasks: [node(goal), node(dependency), { ...node(task), assignment, feedback: 'Fresh coercion diagnostic' }], + history: [1, 2, 3, 4, 5].map(index => ({ ...node(helper('prior' + index)), finding: 'Prior route evidence. '.repeat(500) })) }; + const context = buildResearchContext(problem, { environmentDigest: 'environment', cooperation } as SolverRunState, + { root: '/runtime', worktree: '/unavailable/context-budget-fixture', taskText: 'Prove the original target.', + retrievalRoot: '/unavailable/context-budget-fixture', environment: {}, frozenContexts, + assignment: { kind: 'task', task, assignment } }); + const compacted = compactedResearchDispatch(context, { checkpointInstruction: 'Current checkpoint request.' })!; + expect(compacted.message).toContain('Resume the current assignment after thread compaction.'); + expect(compacted.message).toContain(formal); + expect(compacted.message).toContain('n is a natural number'); + expect(compacted.message).toContain(dependency.type); + expect(compacted.message).toContain('Fresh coercion diagnostic'); + expect(compacted.message).toContain('Current checkpoint request.'); + expect(compacted.manifest!.requiredTaskIds).toEqual(context.manifest!.requiredTaskIds); + expect(Buffer.byteLength(compacted.message)).toBeLessThan(Buffer.byteLength(context.message) / 2); + expect(compactedResearchDispatch({ ...context, message: 'Custom context' }, {})).toBeUndefined(); + }); + it('keeps every host-generated correction obligation available without inlining the backlog', () => { const { context, receipts } = rejectedFindings(); expect(new Set(receipts.map(receipt => receipt.id)).size).toBe(1200); diff --git a/tests/continuationSeed.test.ts b/tests/continuationSeed.test.ts index 8cd7f464..685d754f 100644 --- a/tests/continuationSeed.test.ts +++ b/tests/continuationSeed.test.ts @@ -343,7 +343,7 @@ async function freshConditionalFixture(explicit = true, prepared = true) { async function suspendedTaskDraftFixture(kind: 'research' | 'sketch' | 'goal' | 'lemma' | 'feasibility' = 'research', notes: string | null = '\ufeffSUSPENDED_ROUTE_FINDING λ\r\n```math\n' + - '{"conclusion":"inconclusive","summary":"SUSPENDED_ROUTE_FINDING"}\n```\r\n', sourceDraft = true) { + '{"conclusion":"inconclusive","summary":"SUSPENDED_ROUTE_FINDING"}\n```\r\n', sourceDraft = true, scopedReview = false) { const f = fixture(), state = f.oldState, peer = state.workers![1]!; peer.role = 'engineer'; f.newState.workers![1]!.role = 'engineer'; const tasks = state.cooperation!.tasks, goal = tasks.find(node => node.task.id === 'goal')!; @@ -372,8 +372,10 @@ async function suspendedTaskDraftFixture(kind: 'research' | 'sketch' | 'goal' | reason: 'fixture-no-lean', evidence: 'advisory-type-elaboration', proofAcceptance: 'not-assessed' }, current: () => true })); } } else { + if (scopedReview) tasks.push({ task: { id: 'inspected_input', kind: 'research', + objective: 'Check the local finite input.', status: 'paused', dependsOn: [], revision: 0 }, status: 'pending', attempts: 0 }); task = { id: 'saved_route', kind: kind === 'feasibility' ? 'research' : kind, - objective: 'Investigate the first route', dependsOn: kind === 'feasibility' ? [] : ['first'], revision: 0, + objective: 'Investigate the first route', dependsOn: kind === 'feasibility' ? scopedReview ? ['inspected_input'] : [] : ['first'], revision: 0, ownerId: peer.id, ...(kind === 'feasibility' ? { reviewScope: 'feasibility' as const } : {}) }; goal.task = { ...goal.task, dependsOn: [...goal.task.dependsOn, task.id] }; } @@ -793,6 +795,31 @@ describe('continuation of per-task saved drafts', () => { expect(node.researchCompletion).toBeUndefined(); expect(node.finding).toBeUndefined(); }); + it('resumes a scoped feasibility draft after unrelated canonical additions in cold continuation', async () => { + const notes = 'RETAINED_REVIEW_NOTES\n'; + const f = await suspendedTaskDraftFixture('feasibility', notes, false, true); + fs.writeFileSync(path.join(f.sourceWorktree, f.projectRelative, 'Submission/Helpers.lean'), + helpers.replace('end Submission.Helpers', 'lemma unrelated : True := by trivial\nend Submission.Helpers')); + f.oldState.cooperation!.canonicalCommit = commit(f.sourceWorktree, 'Add unrelated helper'); + writeSolverRunState(f.sourceStateFile, f.oldState); + await f.seed(); + + const state = readSolverRunState(f.stateFile), node = state.cooperation!.tasks.find(node => node.task.id === f.task.id)!; + expect(node.assignment).toBeDefined(); + expect(state.cooperation!.researchDrafts?.[f.task.id]).toMatchObject({ commit: f.draftCommit, suspended: true }); + const cooperative = cooperationFor(f, state), peer = { ...state.workers![1]!, ownedFiles: state.problem.ownedFiles }; + try { + await cooperative.restore(); + const action = await cooperative.next(peer, { maxTurns: Infinity, remainingMs: Infinity }); + if (action?.kind !== 'task') throw new Error('fixture_expected_feasibility_review'); + expect(action.task.id).toBe(f.task.id); + expect(action.assignment.feasibilityInputDigest).not.toBe(f.draftAssignment.feasibilityInputDigest); + expect(fs.readFileSync(path.join(peer.worktree, f.projectRelative, 'Submission/Helpers.lean'), 'utf8')).toContain('lemma unrelated'); + expect(fs.readFileSync(path.join(peer.worktree, 'RESEARCH.md'), 'utf8')).toBe(notes); + expect(node.finding).toBeUndefined(); expect(node.proof).toBeUndefined(); + } finally { await cooperative.stop(); } + }); + it('preserves all 17 UTF-8 drafts above 16 MB through bounded attachments and another ordinary continuation', async () => { const f = fixture(), peer = f.oldState.workers![1]!; peer.role = 'engineer'; f.newState.workers![1]!.role = 'engineer'; @@ -2945,7 +2972,7 @@ describe('continuation of a host-frozen unfinished delivery', () => { expect(fs.readFileSync(f.sourceStateFile)).toEqual(historical); }); - it('migrates a scoped pending check and its parent evidence without adding it to the editable proof plan', async () => { + it.each(['pending', 'decided'] as const)('migrates a scoped %s check and its parent evidence without reopening it', async status => { const f = fixture(), cooperation = f.oldState.cooperation!, goal = cooperation.tasks.find(node => node.task.id === 'goal')!.task; const source: CooperativeTask = { id: 'membership_audit', kind: 'research', objective: 'Inspect the missing membership inference.', revision: 0, dependsOn: ['goal'] }; @@ -2962,12 +2989,25 @@ describe('continuation of a host-frozen unfinished delivery', () => { finding, findingDigest: mathDigest(finding), mathematicalGap: gap, mathematicalGapScope: bindMathematicalGap(gap, source, cooperation, identity) }); const proposed = proposedNextChecks(cooperation, identity, 11)[0]!; - cooperation.nextChecks = [proposed.record]; cooperation.tasks.push(proposed.node); + const checkFinding = 'The attempted application still requires membership.'; + if (status === 'decided') { + const { id, taskId, taskDigest, scope } = proposed.record; + const outcome = { checkId: id, conclusion: 'inconclusive' as const, summary: checkFinding, evidenceRefs: [] }; + proposed.record.status = status; + proposed.record.outcome = { ...outcome, deliveryId: 'membership-outcome' }; + proposed.record.decision = { checkId: id, outcomeDeliveryId: 'membership-outcome', action: 'stop', reason: checkFinding, at: 13 }; + cooperation.deliveries!.push({ id: 'membership-outcome', taskId, taskDigest, producer: 'prover-1', kind: 'research', + status: 'advisory', statement: proposed.node.task.objective, premises: [], dependencies: [], remainingObligations: [], + summary: checkFinding, evidenceRefs: [], createdAt: 12, checkOutcome: outcome, checkOutcomeScope: scope }); + } + cooperation.nextChecks = [proposed.record]; + cooperation.tasks.push(status === 'decided' ? { ...proposed.node, status: 'completed', finding: checkFinding } : proposed.node); writeSolverRunState(f.sourceStateFile, f.oldState); await f.seed(); const restored = readSolverRunState(f.stateFile).cooperation!; expect(restored.nextChecks).toEqual([proposed.record]); - expect(restored.tasks.find(node => node.nextCheckId === proposed.record.id)).toMatchObject({ task: proposed.node.task, status: 'pending' }); + expect(restored.tasks.find(node => node.nextCheckId === proposed.record.id)).toMatchObject({ task: proposed.node.task, + ...(status === 'decided' ? { status: 'completed', finding: checkFinding } : { status: 'pending' }) }); expect(restored.deliveries!.find(delivery => delivery.id === 'membership-gap')?.mathematicalGap?.nextCheck).toEqual(gap.nextCheck); expect(restored.tasks.find(node => node.nextCheckId)?.proof).toBeUndefined(); await f.seed(); diff --git a/tests/nextChecks.test.ts b/tests/nextChecks.test.ts index 1385d1eb..e8da4514 100644 --- a/tests/nextChecks.test.ts +++ b/tests/nextChecks.test.ts @@ -5,9 +5,11 @@ import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; import { parseLeadPlan } from '../src/solver/cooperationShared'; import { currentNextCheck, prepareNextCheckDecisions } from '../src/solver/nextChecks'; import { buildResearchContext } from '../src/solver/modules/context'; +import { commitSolverSources } from '../src/solver/problem'; import { prepareResearchDelivery } from '../src/solver/researchAdmission'; +import { researchCheckpointLocalInputDigest } from '../src/solver/researchCheckpoints'; import { queueResearchObservation } from '../src/solver/researchObservation'; -import { leadPlanDeliveryFile, parseCooperationPlan, taskVersion } from '../src/solver/tasks'; +import { assignmentDeliveryFile, leadPlanDeliveryFile, parseCooperationPlan, taskVersion } from '../src/solver/tasks'; import { cooperativeResearch } from './helpers/cooperation'; import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; @@ -19,12 +21,12 @@ afterEach(async () => { expect(host.createSession).not.toHaveBeenCalled(); host.createSession.mockReset(); }); -async function fixture() { +async function fixture(constructionDependencies = ['goal_0']) { const example = localExample('scoped-next-check-'), lead = leadWorker(example.problem, example.workspace); const author = peerWorker(example, 'author'), checker = peerWorker(example, 'checker'); const plan = parseCooperationPlan(example.problem, { tasks: [ ...example.problem.targets.map((target, index) => ({ ...target, id: `goal_${index}`, kind: 'goal', objective: 'Prove the original target.', status: 'paused' })), - { id: 'construction', kind: 'research', objective: 'Find the missing construction.', ownerId: author.id, dependsOn: ['goal_0'] }, + { id: 'construction', kind: 'research', objective: 'Find the missing construction.', ownerId: author.id, dependsOn: constructionDependencies }, ] }); const state = solverState(example.problem, example.workspace, { runId: 'next-check-fixture', phase: 'running', cooperation: { canonicalCommit: example.problem.baseCommit, tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), @@ -80,6 +82,66 @@ async function fixture() { } describe('scoped next check lifecycle', () => { + it.each(['live', 'legacy restart'] as const)('keeps a parked check paused through progress rephrasing and resumes it on new evidence (%s)', async mode => { + const f = await fixture([]), budget = { maxTurns: Infinity, remainingMs: Infinity }; + let state = f.state.cooperation!, check = state.tasks.find(node => node.nextCheckId === f.record.id)!; + let cooperation = f.cooperation, assignment = f.action.assignment; + const progress = async (summary: string, evidenceRefs?: string[]) => { + const log = path.join(f.author.worktree, assignmentDeliveryFile(assignment)); + fs.appendFileSync(log, JSON.stringify({ kind: 'progress', summary, evidenceRefs }) + '\n'); + await cooperation.pulse(f.author.id); + expect(state.deliveries!.at(-1)).toMatchObject({ kind: 'progress', status: 'advisory', summary }); + }; + await progress('Saved the unfinished comparison. No new evidence.'); + for (let attempt = 0; attempt < 3; attempt++) { + const action = await f.cooperation.next(f.checker, budget); + if (action?.kind !== 'task') throw new Error('missing scoped check assignment'); + expect(action.task.id).toBe(check.task.id); + expect(f.cooperation.started(f.checker, action)).toBe(true); + fs.writeFileSync(path.join(f.checker.worktree, 'RESEARCH.md'), 'Membership remains open.\n'); + await f.cooperation.deliver(f.checker, action, commitSolverSources(f.problem, f.checker.worktree), true); + } + expect(check.status).toBe('blocked'); + const checkpoint = structuredClone(state.researchCheckpoints![check.task.id]); + expect(checkpoint).toMatchObject({ count: 3, paused: true }); + if (mode === 'legacy restart') { + const legacyDigest = researchCheckpointLocalInputDigest({ task: check.task, workerId: f.checker.id, + tasks: state.tasks, deliveries: state.deliveries!, environmentDigest: f.state.environmentDigest, + problemReceiptDigest: f.problem.receiptDigest }, true); + expect(legacyDigest).not.toBe(checkpoint.localInputDigest); + state.researchCheckpoints![check.task.id].localInputDigest = legacyDigest; + const file = path.join(f.directory, 'state.json'); + writeSolverRunState(file, f.state); + f.controller.abort(); await f.cooperation.stop(); + + const restored = readSolverRunState(file), controller = new AbortController(); + state = restored.cooperation!; + check = state.tasks.find(node => node.nextCheckId === f.record.id)!; + cooperation = cooperativeResearch({ state: restored, workers: f.workers, retrievalRoot: f.directory, + signal: controller.signal, emit: event => f.events.push(event) }); + instances.push({ stop: async () => { controller.abort(); await cooperation.stop(); } }); + await cooperation.restore(); + expect(check.status).toBe('blocked'); + const action = await cooperation.next(f.author, budget); + if (action?.kind !== 'task') throw new Error('missing author assignment on restart'); + expect(cooperation.started(f.author, action)).toBe(true); + cooperation.activate(f.author, action, async () => {}, async () => {}); + assignment = action.assignment; + } + + await progress('Retained the same comparison and its open question in the draft.'); + expect(check.status).toBe('blocked'); + expect(state.researchCheckpoints![check.task.id]).toEqual(checkpoint); + expect(f.events).not.toContain('research_checkpoint_reopened'); + + await progress('Found a supporting calculation for this membership test.', ['calculation:membership-reduction']); + expect(check.status).toBe('pending'); + expect(f.events).toContain('research_checkpoint_reopened'); + const resumed = await cooperation.next(f.checker, budget); + expect(resumed).toMatchObject({ kind: 'task', task: { id: check.task.id } }); + expect(f.record.outcome).toBeUndefined(); + }); + it('schedules independent work, consumes an unknown outcome, applies a Lead stop and preserves it across restart', async () => { const f = await fixture(); expect(f.record).toMatchObject({ status: 'pending', scope: { parent: { taskId: 'construction' }, @@ -131,6 +193,40 @@ describe('scoped next check lifecycle', () => { expect(f.record.status).toBe('decided'); }); + it('reconciles a running task for a decided check left by an older continuation', async () => { + const f = await fixture(); + await f.publishOutcome(); + const lead = await f.leadDecision(); + await lead.publish([{ checkId: f.record.id, outcomeDeliveryId: f.record.outcome!.deliveryId, action: 'continue', + reason: 'Continue the other estimate using the archived result.' }]); + const check = f.state.cooperation!.tasks.find(node => node.nextCheckId === f.record.id)!; + f.state.cooperation!.tasks = f.state.cooperation!.tasks.map(node => node === check + ? { ...node, status: 'running', assignment: undefined, attempts: 0 } : node); + const file = path.join(f.directory, 'state.json'); + writeSolverRunState(file, f.state); + f.controller.abort(); await f.cooperation.stop(); + + const restored = readSolverRunState(file), controller = new AbortController(), assigned: unknown[] = []; + const resumed = cooperativeResearch({ state: restored, workers: f.workers, retrievalRoot: f.directory, + signal: controller.signal, emit: (event, details) => { if (event === 'task_assigned') assigned.push(details); } }); + instances.push({ stop: async () => { controller.abort(); await resumed.stop(); } }); + await resumed.restore(); + expect(restored.cooperation!.nextChecks![0]).toMatchObject({ id: f.record.id, status: 'decided' }); + expect(restored.cooperation!.tasks.find(node => node.nextCheckId === f.record.id)).toMatchObject({ status: 'completed', attempts: 0 }); + + // Even an inconsistent pending record reaching the scheduler cannot be reserved. + restored.cooperation!.tasks = restored.cooperation!.tasks.map(node => node.nextCheckId === f.record.id + ? { ...node, status: 'pending' } : node); + const offered = resumed.next(f.checker, { maxTurns: Infinity, remainingMs: Infinity }); + try { + await expect(Promise.race([offered, new Promise(resolve => setTimeout(resolve, 30, 'waiting'))])).resolves.toBe('waiting'); + expect(assigned).toEqual([]); + } finally { + controller.abort(); + await offered.catch(() => {}); + } + }); + it('deduplicates the same question across notes-only publications and rejects an outcome from its author', async () => { const f = await fixture(); await f.publishGap('The same missing inference, reported again after a checkpoint.'); diff --git a/tests/researchArchive.test.ts b/tests/researchArchive.test.ts index 8a4466f6..7ff34365 100644 --- a/tests/researchArchive.test.ts +++ b/tests/researchArchive.test.ts @@ -2,6 +2,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { canonicalMathJson } from '../src/math/mathRuntimeIo'; import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; import { captureResearchBasis, settleResearch } from '../src/solver/researchRecords'; import { taskVersion, type CooperativeTask } from '../src/solver/tasks'; @@ -32,6 +33,29 @@ describe('research completion archive schema', () => { const file = path.join(root, 'state.json'); writeSolverRunState(file, state); return readSolverRunState(file); }; + it('keeps canonical checkpoint bytes across no-op saves, in-place edits and file replacement', () => { + const file = path.join(root, 'state.json'); + writeSolverRunState(file, state); + const first = fs.statSync(file, { bigint: true }); + expect(fs.readFileSync(file, 'utf8')).toBe(canonicalMathJson(state)); + writeSolverRunState(file, state); + expect(fs.statSync(file, { bigint: true }).ino).toBe(first.ino); + + const delivery = state.cooperation!.deliveries![0]!; + delivery.evidenceRefs.push('new evidence'); + delete delivery.finding; + writeSolverRunState(file, state); + expect(fs.readFileSync(file, 'utf8')).toBe(canonicalMathJson(state)); + expect(readSolverRunState(file).cooperation!.deliveries![0]).toMatchObject({ evidenceRefs: ['new evidence'] }); + + const replacement = path.join(root, 'replacement.json'); + fs.writeFileSync(replacement, '{}'); + fs.renameSync(replacement, file); + writeSolverRunState(file, state); + expect(fs.readFileSync(file, 'utf8')).toBe(canonicalMathJson(state)); + expect(fs.statSync(file).mode & 0o777).toBe(0o600); + }); + it.each([undefined, [], ['relevant-candidate']])('preserves the automatic candidate filter independently of the raw pool: %j', relevant => { state.knowledgeRetrievals = { dropped: 0, observations: [{ sectionId: 'knowledge:route', catalogDigest: 'fixture-catalog', searchInputDigest: 'fixture-search', diff --git a/tests/runContinuationSeed.test.ts b/tests/runContinuationSeed.test.ts index 9d9739f1..cc67f3c0 100644 --- a/tests/runContinuationSeed.test.ts +++ b/tests/runContinuationSeed.test.ts @@ -131,14 +131,35 @@ describe('same-process CLI continuation initialization', () => { expect(modules.M1.open).not.toHaveBeenCalled(); }); - it('can retain a seeded zero-turn checkpoint without starting research', async () => { + it('freezes a zero-turn startup checkpoint and checks its saved helpers once when resumed', async () => { const f = fixture(); expect(await runSolver([...f.args, '--startup-only'], f.directory, modules)).toBe(0); const state = readSolverRunState(f.stateFile); expect(state.phase).toBe('prepared'); expect(state.turns).toBe(0); expect(state.solveStartedAt).toBeUndefined(); - expect(state.cooperation!.tasks.find(node => node.task.id === 'saved_helper')!.status).toBe('integrated'); + expect(state.cooperation!.tasks.find(node => node.task.id === 'saved_helper')).toMatchObject({ status: 'pending' }); expect(state.workers!.every(worker => fs.existsSync(path.join(worker.worktree, f.problem.projectRelative, '.lake/continuation.json')))).toBe(true); expect(host.run).not.toHaveBeenCalled(); expect(host.prepare).toHaveBeenCalledOnce(); expect(host.dispose).toHaveBeenCalledOnce(); + expect(host.verify).not.toHaveBeenCalled(); + + fs.writeFileSync(path.join(f.sourceWorkers[1].worktree, 'RESEARCH.md'), 'Historical notes added after preflight.\n'); + host.run.mockImplementation(async (input: ResearchInput) => { + const helper = input.state.cooperation!.tasks.find(node => node.task.id === 'saved_helper')!; + expect(input.freshContinuationChecks?.[0]).toBe(helper.integratedCheck); + expect(helper.status).toBe('integrated'); + const solver = new CooperativeResearch({ ...input, exclusiveCheck: check => check() }); + try { await solver.restore(); } + finally { await solver.stop(); } + }); + const sourceFlag = f.args.indexOf('--continuation-source-run'); + const resume = f.args.filter((_arg, index) => index !== sourceFlag && index !== sourceFlag + 1); + expect(await runSolver([...resume, '--resume'], f.directory, modules), fs.readFileSync(f.output, 'utf8')).toBe(4); + expect(host.run).toHaveBeenCalledOnce(); expect(host.verify).toHaveBeenCalledOnce(); + expect(readSolverRunState(f.stateFile)).toMatchObject({ continuationDigest: state.continuationDigest }); + expect(readSolverRunState(f.stateFile).pendingContinuationSource).toBeUndefined(); + const draft = JSON.parse(readContinuationPage(path.join(path.dirname(f.stateFile), 'continuation.json'), + state.continuationDigest!, 'draft-engineer').text); + expect(draft.notes).toBe('Frozen worker notes.\n'); + expect(modules.M1.open).not.toHaveBeenCalled(); }); it('startup-only preserves started initial-planning activity and leaves the new run ready for its first plan', async () => { @@ -258,44 +279,46 @@ describe('same-process CLI continuation initialization', () => { 'retries %s failure after a complete seed while retaining the prepared checkpoint', async failure => { const f = fixture(), directory = path.dirname(f.stateFile), historical = fs.readFileSync(f.sourceStateFile); const reportFile = path.join(directory, 'continuation-seed.json'), snapshotFile = path.join(directory, 'continuation.json'); - const args = failure === 'startup-output' ? [...f.args, '--startup-only'] : f.args; - const seedComplete = () => fs.existsSync(reportFile) && JSON.parse(fs.readFileSync(reportFile, 'utf8')).stage === 'complete'; + const startupOnly = failure === 'startup-output'; + const args = startupOnly ? [...f.args, '--startup-only'] : f.args; + const seedReady = () => fs.existsSync(reportFile) && + JSON.parse(fs.readFileSync(reportFile, 'utf8')).stage === (startupOnly ? 'awaiting-checks' : 'complete'); const fault = `fixture_${failure}_interrupted`; let failures = 0; if (failure === 'root-snapshot-read') { const readSnapshot = continuationInput.readContinuationSnapshot; vi.spyOn(continuationInput, 'readContinuationSnapshot').mockImplementation((...input) => { - if (!failures && input[0] === snapshotFile && seedComplete()) { failures++; throw new Error(fault); } + if (!failures && input[0] === snapshotFile && seedReady()) { failures++; throw new Error(fault); } return readSnapshot(...input); }); } else if (failure === 'ready-observer') { vi.mocked(console.log).mockImplementation(message => { - if (!failures && JSON.parse(String(message)).event === 'ready' && seedComplete()) { + if (!failures && JSON.parse(String(message)).event === 'ready' && seedReady()) { failures++; throw new Error(fault); } }); } else { const rename = fs.renameSync; vi.spyOn(fs, 'renameSync').mockImplementation((from, to) => { - if (!failures && String(to) === f.output && seedComplete()) { failures++; throw new Error(fault); } + if (!failures && String(to) === f.output && seedReady()) { failures++; throw new Error(fault); } return rename(from, to); }); } expect(await runSolver(args, f.directory, modules)).toBe(1); expect(failures).toBe(1); - expect(seedComplete()).toBe(true); + expect(seedReady()).toBe(true); expect(JSON.parse(fs.readFileSync(f.output, 'utf8')).reason).toBe(fault); const interrupted = readSolverRunState(f.stateFile), digest = interrupted.continuationDigest!; const frozenFile = path.join(directory, 'continuation-seed-source.json'), frozenSource = fs.readFileSync(frozenFile); expect(interrupted.phase).toBe('prepared'); expect(interrupted.turns).toBe(0); expect(interrupted.solveStartedAt).toBeUndefined(); - expect(interrupted.cooperation!.tasks.find(node => node.task.id === 'saved_helper')!.status).toBe('integrated'); - expect(host.verify).toHaveBeenCalledOnce(); expect(host.run).not.toHaveBeenCalled(); + expect(interrupted.cooperation!.tasks.find(node => node.task.id === 'saved_helper')!.status).toBe(startupOnly ? 'pending' : 'integrated'); + expect(host.verify).toHaveBeenCalledTimes(startupOnly ? 0 : 1); expect(host.run).not.toHaveBeenCalled(); fs.writeFileSync(path.join(f.sourceWorkers[1].worktree, 'RESEARCH.md'), 'Late notes after the prepared checkpoint failed.\n'); expect(await runSolver([...args, '--resume'], f.directory, modules), fs.readFileSync(f.output, 'utf8')) - .toBe(failure === 'startup-output' ? 0 : 4); + .toBe(startupOnly ? 0 : 4); const resumed = readSolverRunState(f.stateFile); expect(failures).toBe(1); expect(resumed.continuationDigest).toBe(digest); expect(fs.readFileSync(frozenFile)).toEqual(frozenSource); @@ -306,8 +329,8 @@ describe('same-process CLI continuation initialization', () => { } const draft = JSON.parse(readContinuationPage(snapshotFile, digest, 'draft-engineer').text); expect(draft.notes).toBe('Frozen worker notes.\n'); - expect(host.run).toHaveBeenCalledTimes(failure === 'startup-output' ? 0 : 1); - expect(host.verify).toHaveBeenCalledTimes(2); expect(host.dispose).toHaveBeenCalledTimes(2); + expect(host.run).toHaveBeenCalledTimes(startupOnly ? 0 : 1); + expect(host.verify).toHaveBeenCalledTimes(startupOnly ? 0 : 2); expect(host.dispose).toHaveBeenCalledTimes(2); expect(modules.M1.open).not.toHaveBeenCalled(); }); diff --git a/tests/runLeaseSafety.test.ts b/tests/runLeaseSafety.test.ts index 3b5f1beb..1c84347b 100644 --- a/tests/runLeaseSafety.test.ts +++ b/tests/runLeaseSafety.test.ts @@ -7,15 +7,8 @@ import { directSolverModules } from '../src/solver/modules'; import { runSolver } from '../src/solver/run'; import { localExample } from './helpers/solver'; -const host = vi.hoisted(() => ({ run: vi.fn(), beforeWrite: undefined as - ((file: string, value: unknown) => void) | undefined })); -vi.mock('../src/math/mathRuntimeIo', async original => { - const actual = await original(); - return { ...actual, writeMathJsonDurable: (...args: Parameters) => { - host.beforeWrite?.(args[0], args[1]); - return actual.writeMathJsonDurable(...args); - } }; -}); +const host = vi.hoisted(() => ({ run: vi.fn() })); +let beforePublish: ((file: string) => void) | undefined; vi.mock('../src/math/mathBuildManifest', () => ({ readMathBuildManifest: vi.fn() })); vi.mock('../src/math/leanDiagnostics', async original => ({ ...await original(), @@ -54,11 +47,16 @@ function competingLock(lockPath: string): number | null { } beforeEach(() => { - host.run.mockReset(); open.mockClear(); host.beforeWrite = undefined; + host.run.mockReset(); open.mockClear(); beforePublish = undefined; + const rename = fs.renameSync; + vi.spyOn(fs, 'renameSync').mockImplementation((source, destination) => { + beforePublish?.(String(destination)); + rename(source, destination); + }); vi.spyOn(console, 'log').mockImplementation(() => {}); }); afterEach(() => { - host.beforeWrite = undefined; + beforePublish = undefined; vi.restoreAllMocks(); vi.unstubAllEnvs(); for (const directory of directories.splice(0)) fs.rmSync(directory, { recursive: true, force: true }); }); @@ -67,7 +65,7 @@ describe('run failure checkpoint ownership', () => { it('retains the real run lock while publishing failure state and output', async () => { const current = fixture(), writes: string[] = []; let failed = false; - host.beforeWrite = file => { + beforePublish = file => { if (!failed || ![current.stateFile, current.output].includes(file)) return; writes.push(file); expect(competingLock(current.lockPath)).toBe(73); @@ -90,7 +88,7 @@ describe('run failure checkpoint ownership', () => { it('publishes one cancellation checkpoint and does not overwrite it after releasing the lease', async () => { const current = fixture(), writes: string[] = []; let cancelled = false; - host.beforeWrite = file => { + beforePublish = file => { if (!cancelled || ![current.stateFile, current.output].includes(file)) return; writes.push(file); expect(competingLock(current.lockPath)).toBe(73); @@ -118,7 +116,7 @@ describe('run failure checkpoint ownership', () => { it('leaves state and output untouched after the lock inode is replaced', async () => { const current = fixture(), writes: string[] = []; let invalidated = false, before!: Buffer; - host.beforeWrite = file => { + beforePublish = file => { if (invalidated && [current.stateFile, current.output].includes(file)) writes.push(file); }; host.run.mockImplementation(async () => { diff --git a/tests/solverCooperativeCheckpoints.test.ts b/tests/solverCooperativeCheckpoints.test.ts index 2b00cda5..ce09c632 100644 --- a/tests/solverCooperativeCheckpoints.test.ts +++ b/tests/solverCooperativeCheckpoints.test.ts @@ -4,7 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { MathAgentOptions, MathAgentSession } from '../src/runtime/codexSession'; import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; import { CooperativeResearch } from '../src/solver/cooperation'; -import { leadResearchInputs } from '../src/solver/contextCompiler'; +import { compileContextSections, leadResearchInputs } from '../src/solver/contextCompiler'; import { observeGoalProgress } from '../src/solver/goalProgress'; import { mathDigest } from '../src/math/mathRuntimeIo'; import { directSolverModules, type SolverModules } from '../src/solver/modules'; @@ -80,7 +80,7 @@ describe('cooperative advisory scheduling checkpoints', () => { const events: { event: string; details?: Record }[] = []; const controller = new AbortController(); controllers.push(controller); - const contextSettings = { instructionsSuffix: '' }; + const contextSettings = { instructionsSuffix: '', compactedDispatch: false }; const modules = (open: (options: MathAgentOptions) => Promise): SolverModules => ({ ...directSolverModules, M1: { ...directSolverModules.M1, open }, M2: { ...directSolverModules.M2, check, checkTask: check }, @@ -96,6 +96,10 @@ describe('cooperative advisory scheduling checkpoints', () => { exactTasks: state.cooperation!.tasks.map(node => node.task), sentinel: 'full-context-exact-types-'.repeat(300) }) : JSON.stringify(assignment), ...(continuation && continuation !== 'custom-full' ? { continuationMessage: JSON.stringify({ ...current, mode: 'short' }) } : {}), + ...(contextSettings.compactedDispatch ? { compileCompactedDispatch: () => compileContextSections({ + instructions: 'Offline scheduling fixture.', inlineManifest: false, mandatory: [{ id: 'compacted', kind: 'continuation', + text: JSON.stringify({ ...current, mode: 'compacted', exactTasks: state.cooperation!.tasks.map(node => node.task) }) }], + }) } : {}), scope: 'original-problem-and-allowed-library', sources: { problemReceiptDigest: problem.receiptDigest }, }; } }, @@ -335,7 +339,8 @@ describe('cooperative advisory scheduling checkpoints', () => { }); it('pauses the Lead scheduling clock during compaction and resumes its remaining work slice', async () => { - const { events, controller, run } = fixture(false, undefined, 'lead'); + const { events, controller, run, contextSettings } = fixture(false, undefined, 'lead'); + contextSettings.compactedDispatch = true; const held = heldContinuationTurns({ saveNotes: true }), completion = run(held.open, Infinity); void completion.catch(() => {}); await held.wait(0, completion); await vi.advanceTimersByTimeAsync(30_000); @@ -350,7 +355,7 @@ describe('cooperative advisory scheduling checkpoints', () => { await vi.advanceTimersByTimeAsync(1); await held.wait(1, completion); expect(held.interrupt).toHaveBeenCalledOnce(); expect(held.threads).toEqual(['continuation-thread-1', 'continuation-thread-1']); - expect(held.messages.map(message => message.mode)).toEqual(['full', 'full']); + expect(held.messages.map(message => message.mode)).toEqual(['full', 'compacted']); expect(events.some(item => item.event === 'context_compaction_completed')).toBe(true); controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); expect(vi.getTimerCount()).toBe(0); @@ -867,14 +872,28 @@ describe('cooperative advisory scheduling checkpoints', () => { controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); }); - it.each(['success', 'failure'] as const)('uses native compact between settled turns and restores full task context (%s)', async nativeCompact => { - const { state, workers, check, events, controller, run, pulse } = fixture(false, undefined, 'lead'); + it.each(['success', 'failure', 'changed-plan'] as const)('restores exact task context after native compaction (%s)', async outcome => { + const { state, workers, check, events, controller, run, pulse, contextSettings } = fixture(false, undefined, 'lead'); + const nativeCompact = outcome === 'failure' ? 'failure' : 'success'; + contextSettings.compactedDispatch = true; const held = heldContinuationTurns({ saveNotes: true, highContext: true, nativeCompact }); const completion = run(held.open, Infinity); void completion.catch(() => {}); await held.wait(0, completion); held.open.mock.calls[0][0].onActivity!({ event: 'reasoning' }); expect(held.compact).not.toHaveBeenCalled(); const request = state.workers![0].contextCheckpoint!; + if (outcome === 'changed-plan') { + const next = CooperativeResearch.prototype.next; + vi.spyOn(CooperativeResearch.prototype, 'next').mockImplementation(async function (this: CooperativeResearch, worker, budget) { + const action = await next.call(this, worker, budget); + if (action?.kind === 'lead') { + state.cooperation!.planVersion = 'compaction-revised-plan'; + state.cooperation!.tasks.find(node => node.task.kind === 'goal')!.task.type = '∀ n : Nat, n = n'; + action.planVersion = state.cooperation!.planVersion; + } + return action; + }); + } fs.appendFileSync(path.join(workers[0].worktree, held.messages[0].receipt!), JSON.stringify({ kind: 'checkpoint', requestId: request.requestId, notesDigest: mathDigest(fs.readFileSync(path.join(workers[0].worktree, 'RESEARCH.md'))), @@ -882,7 +901,11 @@ describe('cooperative advisory scheduling checkpoints', () => { await pulse(workers[0].id); await vi.advanceTimersByTimeAsync(5_000); await held.wait(1, completion); expect(held.compact).toHaveBeenCalledOnce(); expect(held.threads).toEqual(['continuation-thread-1', nativeCompact === 'success' ? 'continuation-thread-1' : 'continuation-thread-2']); - expect(held.messages[1].mode).toBe('full'); expect(held.messages[1].exactTasks).toEqual(state.cooperation!.tasks.map(node => node.task)); + expect(held.messages[1].mode).toBe(outcome === 'success' ? 'compacted' : 'full'); + expect(held.messages[1].exactTasks).toEqual(state.cooperation!.tasks.map(node => node.task)); + const dispatches = events.filter(item => item.event === 'context_dispatched').map(item => item.details); + expect(dispatches.map(details => details?.mode)).toEqual(['full', outcome === 'success' ? 'compacted' : 'full']); + if (outcome === 'success') expect(dispatches[1]?.messageBytes).toBeLessThan(Number(dispatches[0]?.messageBytes) / 2); expect(events.some(item => item.event === 'context_restarted')).toBe(nativeCompact === 'failure'); expect(events.some(item => item.event === (nativeCompact === 'success' ? 'context_compaction_completed' : 'context_compaction_failed'))).toBe(true); expect(state.workers![0].usageAccounting?.startedTurns).toBe(2); diff --git a/tests/solverLivenessRecovery.test.ts b/tests/solverLivenessRecovery.test.ts index f9b36a50..0d374bb6 100644 --- a/tests/solverLivenessRecovery.test.ts +++ b/tests/solverLivenessRecovery.test.ts @@ -5,6 +5,7 @@ import { mathDigest } from '../src/math/mathRuntimeIo'; import type { MathAgentOptions, MathAgentSession } from '../src/runtime/codexSession'; import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; import { CooperativeResearch } from '../src/solver/cooperation'; +import { MAX_RESEARCH_NOTES_BYTES } from '../src/solver/deliveries'; import { IDLE_PEER_WAKE_MS } from '../src/solver/leadInbox'; import { directSolverModules, type SolverModules } from '../src/solver/modules'; import { runResearchWorkers } from '../src/solver/research'; @@ -187,13 +188,13 @@ describe('Lead planning liveness across checkpoints and restore', () => { kind: 'research', summary, producer: workers[2].id })); }; /** Publish an unchanged complete plan as the Lead's answer to its dispatched planning input. */ - const answer = async (action = latestLead().assignment) => { + const answer = async (action = latestLead().assignment, upsert?: { id: string; objective: string }[]) => { const presented = leads().find(message => message.assignment.kind === 'lead' && message.assignment.planNonce === action.planNonce); fs.appendFileSync(path.join(workers[0].worktree, leadPlanDeliveryFile(action)!), JSON.stringify({ kind: 'plan', dispatchNonce: action.planNonce, baseVersion: action.planVersion, - tasks: fixture.state.cooperation!.tasks.map(node => node.task), - groups: fixture.state.cooperation!.groups!.map(route => route.group), + ...(upsert ? { upsert } : { tasks: fixture.state.cooperation!.tasks.map(node => node.task), + groups: fixture.state.cooperation!.groups!.map(route => route.group) }), researchDecisions: (presented?.researchInputIds ?? []).map(deliveryId => ({ deliveryId, outcome: 'decline', reason: 'The current evidence does not establish a sound change to this route.' })), ...(presented?.progressReview ? { progressReview: { id: presented.progressReview.id, @@ -230,6 +231,21 @@ describe('Lead planning liveness across checkpoints and restore', () => { return { ...fixture, get state() { return fixture.state; }, set state(value) { fixture.state = value; }, start }; } + it('clears peer recovery after the first acknowledged scheduling checkpoint', async () => { + const fixtureState = fixture({ seedDecision: false }); + const peer = fixtureState.state.workers![2]; + peer.recovery = { phase: 'retrying', reason: 'math_model_request_failed', cycles: 6, + startedAt: Date.now() - 2_000_000, nextRetryAt: Date.now(), waitedMs: 1_320_000 }; + const run = fixtureState.start({ saveResearchProgress: true }); + try { + await run.ready(); + await vi.advanceTimersByTimeAsync(LEAD_REVISION_MS); + expect(run.events.filter(e => e.event === 'turn_checkpoint' && e.details?.workerId === peer.id).length).toBeGreaterThan(1); + expect(run.events.filter(e => e.event === 'worker_recovered' && e.details?.workerId === peer.id)).toHaveLength(1); + expect(peer.recovery).toMatchObject({ phase: 'recovered', cycles: 6 }); + } finally { await run.stop(); } + }); + it('replaces a legacy coordination thread once, preserves its draft and resumes the planning thread', async () => { const fixtureState = fixture({ seedDecision: false }), lead = fixtureState.state.workers![0]; lead.threadId = 'legacy-mathematical-coordination'; lead.sessionRole = 'lead'; lead.sessionLeadMode = 'coordination'; @@ -275,6 +291,34 @@ describe('Lead planning liveness across checkpoints and restore', () => { expect(fixtureState.check).not.toHaveBeenCalled(); await run.stop(); }); + it('saves oversized Lead notes across a checkpoint and accepts the next plan through the dispatch log', async () => { + const fixtureState = fixture(), run = fixtureState.start(); + try { + await run.ready(); + const lead = fixtureState.workers[0], first = run.latestLead().assignment; + const notes = path.join(lead.worktree, 'RESEARCH.md'); + const line = 'Partial mathematical argument.\n'; + const draft = line.repeat(Math.ceil(MAX_RESEARCH_NOTES_BYTES / Buffer.byteLength(line)) + 1); + fs.writeFileSync(notes, draft); + await vi.advanceTimersByTimeAsync(LEAD_REVISION_MS); + await run.waitForLead(first.planNonce); + expect(run.events).toContainEqual(expect.objectContaining({ event: 'lead_checkpoint_saved', + details: expect.objectContaining({ reason: 'oversized-notes-draft' }) })); + expect(run.events.some(item => item.event === 'worker_failed')).toBe(false); + const second = run.latestLead().assignment; + const edits = [{ id: 'investigate', objective: 'Check the precise remaining inference.' }]; + await run.answer(second, edits); + run.finishLead(second); + await vi.advanceTimersByTimeAsync(1_000); + expect(fixtureState.state.cooperation!.tasks.find(node => node.task.id === 'investigate')?.task.objective) + .toBe(edits[0].objective); + expect(fixtureState.state.cooperation!.planPublication).toMatchObject({ nonce: second.planNonce, finalized: true }); + expect(fs.readFileSync(notes, 'utf8')).toBe(draft); + expect(run.events.some(item => item.event === 'worker_failed')).toBe(false); + expect(fixtureState.check).not.toHaveBeenCalled(); + } finally { await run.stop(); } + }); + it('waits for hours after an unchanged checkpoint, then wakes for new evidence until a plan answers it', async () => { const fixtureState = fixture({ seedDecision: false }), run = fixtureState.start({ saveResearchProgress: true }); await run.ready(); await vi.advanceTimersByTimeAsync(LEAD_REVISION_MS + 60_000); diff --git a/tests/solverResearchDrafts.test.ts b/tests/solverResearchDrafts.test.ts index 64c91fac..581fa3c8 100644 --- a/tests/solverResearchDrafts.test.ts +++ b/tests/solverResearchDrafts.test.ts @@ -678,6 +678,37 @@ describe('isolated advisory research drafts', () => { expect(node('first_route').finding).toBeUndefined(); expect(node('first_route').researchCompletion).toBeUndefined(); }); + it.each(['plain lemma', 'following command', 'inspected name'] as const)('handles a canonical addition with a %s when resuming a review', async change => { + node('first_route').task = { ...node('first_route').task, reviewScope: 'feasibility', dependsOn: ['goal_1'] }; + node('goal_1').task = { ...node('goal_1').task, sharing: 'problem', status: 'paused', dependsOn: [], + ...(change === 'inspected name' ? { objective: 'Inspect fixtureAdded as a potential witness.' } : {}) }; + const notesText = 'Retained halfway through the finite check.\n'; + const first = await task(); + fs.writeFileSync(notes(), notesText); + const draftCommit = commitSolverSources(problem, peer.worktree); + await cooperative.deliver(peer, first, draftCommit, true, 'request-failure'); + const original = fs.readFileSync(source(lead), 'utf8'); + const addition = 'lemma fixtureAdded : True := by trivial\n' + + (change === 'following command' ? ' attribute [simp] fixtureAdded\n' : '') + '\n'; + const current = original.replace('theorem add_zero', addition + 'theorem add_zero'); + fs.writeFileSync(source(lead), current); + state.cooperation!.canonicalCommit = commitSolverSources(problem, lead.worktree); + + const resumed = await task(); + expect(resumed.task.id).toBe('first_route'); + expect(resumed.assignment.canonicalCommit).toBe(state.cooperation!.canonicalCommit); + expect(resumed.assignment.feasibilityInputDigest).not.toBe(first.assignment.feasibilityInputDigest); + expect(fs.readFileSync(source(), 'utf8')).toBe(current); + expect(fs.readFileSync(notes(), 'utf8')).toBe(change === 'plain lemma' ? notesText : ''); + expect(committedSource(peer.worktree, draftCommit, 'RESEARCH.md')).toBe(notesText); + if (change === 'plain lemma') { + const commit = commitSolverSources(problem, peer.worktree); + await cooperative.deliver(peer, resumed, commit, true, 'request-failure'); + expect((await task()).assignment.assignmentId).toBe(resumed.assignment.assignmentId); + expect(fs.readFileSync(notes(), 'utf8')).toBe(notesText); + } + }); + it('starts a new reviewer with fresh notes while retaining the prior reviewer\'s pinned draft', async () => { node('first_route').task = { ...node('first_route').task, reviewScope: 'feasibility' }; const action = await task(); fs.writeFileSync(notes(), 'PRIOR_REVIEWER_NOTES\n'); diff --git a/tests/solverRoutePreflightScheduling.test.ts b/tests/solverRoutePreflightScheduling.test.ts new file mode 100644 index 00000000..78a7cf5f --- /dev/null +++ b/tests/solverRoutePreflightScheduling.test.ts @@ -0,0 +1,168 @@ +import fs from 'node:fs'; +import { setTimeout as delay } from 'node:timers/promises'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { SolverRunState } from '../src/solver/archive'; +import type { CooperativeResearch } from '../src/solver/cooperation'; +import type { ResearchWorker } from '../src/solver/modules/organization'; +import { TaskTypePreflightCache, type TaskTypePreflight } from '../src/solver/taskTypePreflight'; +import { parseCooperationPlan, taskVersion, type CooperativeAction } from '../src/solver/tasks'; +import { deferred } from './helpers/async'; +import { cooperativeResearch, workerDeliveryModules } from './helpers/cooperation'; +import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; + +type Check = Awaited>; +type Action = Extract; +const budget = { maxTurns: Infinity, remainingMs: Infinity }; +describe('route capacity during concurrent host preflight', () => { + let directory: string, state: SolverRunState, controller: AbortController, scheduler: CooperativeResearch; + let first: ResearchWorker, second: ResearchWorker; + const active = new Map void }[]>(); + const waits: Promise[] = []; + const events: { name: string; detail?: Record }[] = []; + const next = (worker: ResearchWorker) => { + const result = scheduler.next(worker, budget); + waits.push(result); + void result.catch(() => {}); + return result; + }; + const held = (id: string, index = 0) => active.get(id)![index]!; + const names = () => [...active].flatMap(([id, calls]) => calls.map(() => id)); + const busy = () => state.cooperation!.groups!.find(group => group.group.id === 'main')?.busy; + const node = (id: string) => state.cooperation!.tasks.find(task => task.task.id === id)!; + const assigned = () => events.filter(event => event.name === 'task_assigned').map(event => event.detail?.taskId); + const waitUntil = async (predicate: () => boolean) => { + for (let retry = 0; !predicate() && retry < 20; retry++) await new Promise(resolve => setImmediate(resolve)); + expect(predicate()).toBe(true); + }; + beforeEach(() => { + active.clear(); events.length = 0; + const example = localExample('route-preflight-contention-', 'lead'); + directory = example.directory; + const lead = leadWorker(example.problem, example.workspace); + first = peerWorker(example, 'first'); second = peerWorker(example, 'second'); + const workers = [lead, first, second]; + const plan = parseCooperationPlan(example.problem, { tasks: [ + { id: 'first_helper', kind: 'lemma', objective: 'First independent helper', theoremName: 'Tutorial.first_helper', + proofPath: 'Submission.lean', type: 'True', ownerId: first.id }, + { id: 'second_helper', kind: 'lemma', objective: 'Second independent helper', theoremName: 'Tutorial.second_helper', + proofPath: 'Submission.lean', type: 'True', ownerId: second.id }, + ...example.problem.targets.map((target, index) => ({ id: 'goal_' + index, kind: 'goal', + objective: 'Frozen target', theoremName: target.theoremName, proofPath: target.proofPath, status: 'paused' })), + ], groups: [{ id: 'main', objective: 'Run one proof at a time.', maxConcurrent: 1 }, + { id: 'other', objective: 'Independent route with its own capacity.', maxConcurrent: 1 }] }); + state = solverState(example.problem, example.workspace, { runId: 'preflight-replay', phase: 'running', + workers: workers.map(worker => ({ ...worker, phase: 'running', turns: 0 })), + cooperation: { canonicalCommit: example.problem.baseCommit, + tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), + groups: plan.groups.map(group => ({ group, turns: 0 })) } }); + controller = new AbortController(); + scheduler = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, + modules: workerDeliveryModules, emit: (name, detail) => events.push({ name, detail }) }); + vi.spyOn(TaskTypePreflightCache.prototype, 'check').mockImplementation(({ task, signal }) => { + const gate = deferred(); + const calls = active.get(task.id) ?? []; + calls.push({ signal: signal!, finish: () => gate.resolve({ current: () => true, + result: { status: 'elaborated', inputDigest: task.id, taskDigest: taskVersion(task), reason: 'fixture', + evidence: 'advisory-type-elaboration', proofAcceptance: 'not-assessed' } as TaskTypePreflight }) }); + active.set(task.id, calls); + return gate.promise; + }); + }); + afterEach(async () => { + controller.abort(); + for (const calls of active.values()) for (const call of calls) call.finish(); + await Promise.allSettled(waits.splice(0)); + await scheduler.stop(); + vi.restoreAllMocks(); + fs.rmSync(directory, { recursive: true, force: true }); + }); + + it('holds the final route slot from preflight through model dispatch', async () => { + const firstPending = next(first); + const secondPending = next(second); + await waitUntil(() => state.workers![2].scheduling?.wait !== undefined); + expect(names()).toEqual(['first_helper']); + expect(assigned()).toEqual([]); + expect(busy()).toBe(1); + expect(held('first_helper').signal.aborted).toBe(false); + held('first_helper').finish(); + const firstAction = await firstPending as Action; + expect(firstAction.task.id).toBe('first_helper'); + expect(busy()).toBe(1); + expect(names()).toEqual(['first_helper']); + expect(node('second_helper')).toMatchObject({ status: 'pending', attempts: 0 }); + + scheduler.release(first, firstAction); + await waitUntil(() => active.has('second_helper')); + held('second_helper').finish(); + expect(await secondPending).toMatchObject({ kind: 'task', task: { id: 'second_helper' } }); + expect(names()).toEqual(['first_helper', 'second_helper']); + expect(assigned()).toEqual(['first_helper', 'second_helper']); + }); + + it('retains the concurrent preflight on a separate route', async () => { + node('second_helper').task = { ...node('second_helper').task, groupId: 'other' }; + const firstPending = next(first); + const secondPending = next(second); + await waitUntil(() => names().length === 2); + held('first_helper').finish(); + expect(await firstPending).toMatchObject({ kind: 'task', task: { id: 'first_helper' } }); + expect(held('second_helper').signal.aborted).toBe(false); + held('second_helper').finish(); + expect(await secondPending).toMatchObject({ kind: 'task', task: { id: 'second_helper' } }); + expect(names()).toEqual(['first_helper', 'second_helper']); + }); + + it('keeps a stopped owner’s assignment when the peer preflight is cancelled', async () => { + node('second_helper').task = { ...node('second_helper').task, status: 'paused' }; + const original = next(first); + held('first_helper').finish(); + const firstAction = await original as Action; + expect(scheduler.started(first, firstAction)).toBe(true); + scheduler.stopped(first); + const takeover = next(second); + await waitUntil(() => active.get('first_helper')?.length === 2); + expect(node('first_helper').assignment).toBe(firstAction.assignment); + + scheduler.stopped(second); + expect(held('first_helper', 1).signal.aborted).toBe(true); + held('first_helper', 1).finish(); + expect(await takeover).toBeUndefined(); + expect(node('first_helper').assignment).toBe(firstAction.assignment); + expect(events.some(event => event.name === 'task_assignment_released')).toBe(false); + expect(busy()).toBe(0); + }); + + it('wakes an idle peer for fixed review when the preferred worker enters cooldown', async () => { + node('first_helper').task = { ...node('first_helper').task, status: 'paused' }; + node('second_helper').task = { ...node('second_helper').task, status: 'paused' }; + const commit = state.cooperation!.canonicalCommit!; + scheduler.requireReview({ commit, sourceDigest: 'fixture-source', passed: true, + verification: { schema: 'deepscientist.mathematics.verification-batch/v1', sessionId: 'fixture', + status: 'kernel_verified', results: [], targetCommit: commit, events: [], startedAt: 0, checkedAt: 0, durationMs: 0 } }); + const offered = next(second); + expect(await Promise.race([offered, delay(30, 'waiting')])).toBe('waiting'); + state.workers![1]!.recovery = { phase: 'cooling-down', reason: 'math_model_request_failed', cycles: 4, + nextRetryAt: Date.now() + 300_000, startedAt: Date.now(), waitedMs: 0 }; + scheduler.workerAvailabilityChanged(); + expect(await Promise.race([offered, delay(1000, 'waiting')])).toMatchObject({ kind: 'review', seedCommit: commit }); + expect(state.cooperation!.review).toMatchObject({ status: 'running', workerId: second.id }); + }); + + it('gives fixed review to the idle peer while the preferred worker is in preflight', async () => { + node('second_helper').task = { ...node('second_helper').task, status: 'paused' }; + const firstPending = next(first); + await waitUntil(() => names().length === 1); + const commit = state.cooperation!.canonicalCommit!; + scheduler.requireReview({ commit, sourceDigest: 'fixture-source', passed: true, + verification: { schema: 'deepscientist.mathematics.verification-batch/v1', sessionId: 'fixture', + status: 'kernel_verified', results: [], targetCommit: commit, events: [], startedAt: 0, checkedAt: 0, durationMs: 0 } }); + expect(state.workers![1].scheduling).toMatchObject({ status: 'preparing', taskId: 'first_helper' }); + expect(state.workers![2].scheduling?.status).toBe('idle'); + expect(await Promise.race([next(second), delay(1000, 'waiting')])).toMatchObject({ kind: 'review', seedCommit: commit }); + expect(state.cooperation!.review).toMatchObject({ status: 'running', workerId: second.id }); + expect(held('first_helper').signal.aborted).toBe(false); + held('first_helper').finish(); + expect(await firstPending).toMatchObject({ kind: 'task', task: { id: 'first_helper' } }); + }); +}); diff --git a/tests/solverWorkerExitDispatch.test.ts b/tests/solverWorkerExitDispatch.test.ts new file mode 100644 index 00000000..b6bd3a0c --- /dev/null +++ b/tests/solverWorkerExitDispatch.test.ts @@ -0,0 +1,107 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; +import { expect, it } from 'vitest'; +import { directSolverModules } from '../src/solver/modules'; +import { commitSolverSources } from '../src/solver/problem'; +import { parseCooperationPlan } from '../src/solver/tasks'; +import { cooperativeResearch } from './helpers/cooperation'; +import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; + +const budget = { maxTurns: Infinity, remainingMs: Infinity }; + +function fixture(emitHook?: (event: string, details?: Record) => void, addOtherWork = false) { + const example = localExample('worker-exit-replay-', 'lead'); + const { directory, workspace, problem } = example; + const workers = [leadWorker(problem, workspace), peerWorker(example, 'owner'), peerWorker(example, 'idle')]; + const [, owner, idle] = workers; + const plan = parseCooperationPlan(problem, { tasks: [ + ...(addOtherWork ? [{ id: 'other', kind: 'research', objective: 'Run an independent enumeration.', ownerId: idle.id }] : []), + { id: 'reserved', kind: 'research', objective: 'Investigate a local obstruction.', ownerId: owner.id }, + ...problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal', + objective: 'Original target.', theoremName: target.theoremName, proofPath: target.proofPath, status: 'paused' })), + ] }); + const state = solverState(problem, workspace, { runId: 'worker-exit-replay', phase: 'running', + workers: workers.map(worker => ({ ...worker, phase: 'running', turns: 0 })), + cooperation: { canonicalCommit: problem.baseCommit, tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), + groups: plan.groups.map(group => ({ group, turns: 0 })) } }); + const events: Array<{ event: string; details?: Record }> = []; + const emit = (event: string, details?: Record) => { events.push({ event, details }); emitHook?.(event, details); }; + const controller = new AbortController(); + const forbidden = () => { throw new Error('fixture_model_and_verifier_forbidden'); }; + const newRuntime = (saved = state) => cooperativeResearch({ state: saved, workers, retrievalRoot: directory, + emit, signal: controller.signal, modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open: forbidden }, + M2: { ...directSolverModules.M2, check: forbidden, checkTask: forbidden } } }); + const runtime = newRuntime(); + return { ...example, owner, idle, state, runtime, events, controller, newRuntime, + reserved: state.cooperation!.tasks.find(node => node.task.id === 'reserved')! }; +} + +it.each(['registered', 'racing'] as const)('dispatches a stopped owner’s task with %s waiter timing', async timing => { + let f: ReturnType; + f = fixture((event, details) => { + if (timing === 'racing' && event === 'dispatch_wait' && details?.workerId === 'idle') + queueMicrotask(() => f.runtime.stopped(f.owner, 'fixture_worker_failed')); + }); + let waiting: ReturnType | undefined; + try { + const original = await f.runtime.next(f.owner, budget); + if (original?.kind !== 'task') throw new Error('owner task missing'); + expect(f.runtime.started(f.owner, original)).toBe(true); + f.runtime.start(); + waiting = f.runtime.next(f.idle, budget); + const observed = waiting.then(action => ({ task: action?.kind === 'task' && action.task.id })); + if (timing === 'registered') { + await new Promise(resolve => setImmediate(resolve)); + f.runtime.stopped(f.owner, 'fixture_worker_failed'); + } + expect(await Promise.race([observed, delay(1000, 'waiting')])).toEqual({ task: 'reserved' }); + expect(f.events.filter(item => item.event === 'task_assignment_released')).toEqual([{ + event: 'task_assignment_released', details: { taskId: 'reserved', workerId: f.owner.id, takenBy: f.idle.id, reason: 'worker-stopped' }, + }]); + } finally { + f.controller.abort(); + await Promise.allSettled([waiting]); + await f.runtime.stop(); + fs.rmSync(f.directory, { recursive: true, force: true }); + } +}); + +it('preserves a stopped worker’s draft when the live peer takes a different task', async () => { + const f = fixture(undefined, true); + let resumed: ReturnType | undefined; + try { + const action = await f.runtime.next(f.owner, budget); + if (action?.kind !== 'task') throw new Error('owner task missing'); + expect(action.task.id).toBe('reserved'); + expect(f.runtime.started(f.owner, action)).toBe(true); + const marker = 'A checked bound for the original task.'; + const proofFile = path.join(f.owner.worktree, f.problem.projectRelative, 'Submission.lean'); + fs.appendFileSync(proofFile, '\n-- ' + marker + '\n'); + fs.writeFileSync(path.join(f.owner.worktree, 'RESEARCH.md'), marker + '\n'); + const commit = commitSolverSources(f.problem, f.owner.worktree); + f.runtime.retainContextDraft(f.owner, action, commit); + f.runtime.stopped(f.owner, 'fixture_worker_failed'); + expect(f.reserved.assignment?.assignmentId).toBe(action.assignment.assignmentId); + expect(f.state.cooperation!.researchDrafts!.reserved.commit).toBe(commit); + const candidate = await f.runtime.next(f.idle, budget); + expect(candidate).toMatchObject({ kind: 'task', task: { id: 'other' } }); + expect(f.reserved).toMatchObject({ status: 'pending' }); + expect(f.reserved.assignment?.assignmentId).toBe(action.assignment.assignmentId); + expect(f.events.some(item => item.event === 'task_assignment_released')).toBe(false); + const previous = JSON.parse(JSON.stringify(f.state)) as typeof f.state; + resumed = f.newRuntime(previous); + await resumed.restore(); + const afterRestart = await resumed.next(f.owner, budget); + expect(afterRestart).toMatchObject({ kind: 'task', task: { id: 'reserved' } }); + if (afterRestart?.kind !== 'task') throw new Error('restart task missing'); + expect(afterRestart.assignment.assignmentId).toBe(action.assignment.assignmentId); + expect(fs.readFileSync(proofFile, 'utf8')).toContain(marker); + expect(previous.cooperation!.researchDrafts!.reserved.commit).toBe(commit); + } finally { + f.controller.abort(); + await resumed?.stop(); + await f.runtime.stop(); + fs.rmSync(f.directory, { recursive: true, force: true }); + } +}); From bcbd1ac16a1e3c9f105acfbb7de367407466142b Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:39:24 +0800 Subject: [PATCH 2/2] fix(solver): preserve assignment type after claiming a task --- src/solver/cooperation.ts | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/src/solver/cooperation.ts b/src/solver/cooperation.ts index 92c6f80f..1c063789 100644 --- a/src/solver/cooperation.ts +++ b/src/solver/cooperation.ts @@ -863,6 +863,7 @@ export class CooperativeResearch extends CooperationInputs { node.assignment = dispatchAssignment; if (stoppedAssignment) this.input.emit('task_assignment_released', { taskId: node.task.id, workerId: stoppedAssignment.workerId, takenBy: worker.id, reason: 'worker-stopped' }); + return dispatchAssignment; }; const canonicalGoal = !resuming && node.task.kind === 'goal' && this.canonicalTaskCandidate(node, worker, scopedSeed); if (node.task.kind === 'lemma' || node.task.kind === 'goal' && (canonicalGoal || this.input.access.get(worker.id)?.installedLibrary)) { @@ -1102,16 +1103,19 @@ export class CooperativeResearch extends CooperationInputs { this.preparingTaskTypes.delete(node); finishPreparation(); this.changed(); } } - claimAssignment(); - if (!node.assignment.connectionCheck && automaticTaskConnection(node.task, this.archive.tasks, this.archive.groups)) { + let assignment = claimAssignment(); + if (!assignment.connectionCheck && automaticTaskConnection(node.task, this.archive.tasks, this.archive.groups)) { // Upgrading an idle historical assignment keeps its saved draft but supersedes late publications. - if (resuming && node.assignment === resumedAssignment) node.assignment = { ...node.assignment, assignmentId: crypto.randomUUID() }; - node.assignment.connectionCheck = createTaskConnectionCheck(node.task, node.assignment, this.archive.tasks, + if (resuming && assignment === resumedAssignment) { + assignment = { ...assignment, assignmentId: crypto.randomUUID() }; + node.assignment = assignment; + } + assignment.connectionCheck = createTaskConnectionCheck(node.task, assignment, this.archive.tasks, { environmentDigest: this.input.state.environmentDigest, problemReceiptDigest: this.input.state.problem.receiptDigest }, - dependency => committedSource(worker.worktree, node.assignment!.seedCommit, + 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: node.assignment.connectionCheck }); + connectionCheck: assignment.connectionCheck }); } if (!advisory(node.task) && fs.existsSync(path.join(worker.worktree, this.input.state.problem.projectRelative, '.lake/source-constraints.json'))) { @@ -1121,7 +1125,7 @@ export class CooperativeResearch extends CooperationInputs { const declarations = Object.fromEntries(Object.entries(problem.declarations).map(([file, originals]) => { // Library modules are byte-frozen as a whole; their declarations need no per-task bodies. if (problem.frozenFiles && Object.hasOwn(problem.frozenFiles, file)) return [file, originals]; - const source = committedSource(worker.worktree, node.assignment!.seedCommit, `${problem.projectRelative}/${file}`); + const source = committedSource(worker.worktree, assignment.seedCommit, `${problem.projectRelative}/${file}`); const matching = originalDeclarationRegions(source); return [file, originals.map(original => { if (original.body || file === node.task.proofPath && @@ -1136,10 +1140,10 @@ export class CooperativeResearch extends CooperationInputs { this.moveTask(node, 'running', 'dispatched'); const route = this.archive.groups?.find(record => record.group.id === taskGroup(node.task)); this.input.emit('task_assigned', { taskId: node.task.id, workerId: worker.id, kind: node.task.kind, - taskDigest: node.assignment.taskDigest, assignmentKey: assignmentDeliveryFile(node.assignment), + taskDigest: assignment.taskDigest, assignmentKey: assignmentDeliveryFile(assignment), planVersion: this.archive.planVersion, groupId: taskGroup(node.task), groupTurns: route?.turns, - seedCommit: node.assignment.seedCommit }); - this.changed(); return { kind: 'task', assignment: node.assignment, task: node.task }; + seedCommit: assignment.seedCommit }); + this.changed(); return { kind: 'task', assignment, task: node.task }; } /** Host proof attempts start only from a fresh, unconditional typed helper whose dependencies are checked. */ private tacticBatteryCandidate(node: TaskRecord): boolean {