From fe3ce98036ac5b0dfe57eed395c81df69cd38bb5 Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:32:31 +0800 Subject: [PATCH] Consolidate harness bundles and fix library continuation --- .github/workflows/verify.yml | 3 + apps/web/Dockerfile | 2 +- apps/web/libraryResearch.ts | 155 ++++++++----- apps/web/worker.ts | 23 +- bin/math.ts | 123 ++++++----- docs/usage.md | 2 +- scripts/build-agent-tools.ts | 184 +++++++++------- scripts/build.ts | 169 ++++++++------ scripts/mathematics/autoLibrary.ts | 1 + scripts/mathematics/runExample.ts | 2 +- .../mathematics/verifyFirstProofOffline.ts | 2 +- src/math/mathBuildManifest.ts | 207 ++++++++++++++++-- src/solver/agentTeam.ts | 18 +- src/solver/autoLibrary.ts | 73 +++--- src/solver/continuationInput.ts | 5 +- src/solver/research.ts | 20 +- src/solver/researchToolGuide.ts | 16 ++ src/solver/run.ts | 22 +- tests/agentTools.test.ts | 37 +++- tests/autoLibraryCli.test.ts | 16 +- tests/autoLibraryHost.test.ts | 126 ++++++++--- tests/mathProofEnvironment.test.ts | 3 +- tests/mathRetrievalCorpus.test.ts | 3 +- tests/standalone.test.ts | 199 +++++++++++++++-- tests/webAgentActions.test.ts | 10 +- tests/webLibraryResearch.test.ts | 62 +++++- 26 files changed, 1064 insertions(+), 419 deletions(-) diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 9e0bb439..eed9f0b9 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -187,5 +187,8 @@ jobs: run: bunx vitest run --maxWorkers=4 tests/taskTypeContract.test.ts tests/projectionNotation.test.ts tests/taskSourceImplicitInstances.test.ts tests/taskSourceMacroProjection.test.ts tests/taskSourceNotationHints.test.ts tests/taskSourceNotationContext.test.ts - name: Verify search tools, failure reuse and completed research delivery run: bunx vitest run --maxWorkers=4 tests/declarationSearch.test.ts tests/continuationSearch.test.ts tests/tacticBatteryFailureCache.test.ts tests/codexCompletedResponse.test.ts + - name: Verify standalone packaging and automatic library recovery + if: matrix.lean == '4.36.0' + run: bunx vitest run --maxWorkers=4 tests/standalone.test.ts tests/autoLibraryHost.test.ts tests/autoLibraryCli.test.ts - name: Verify definition contracts, conditional publication and research continuation run: bunx vitest run --maxWorkers=4 tests/conditionalProjectionElaborator.test.ts tests/customSolverModules.test.ts tests/definitionContractChecks.test.ts tests/nextCheckNegativeDecisions.test.ts tests/planResearchConnections.test.ts tests/solver.test.ts tests/taskConditionalUniverses.test.ts tests/taskSourceConditionalContext.test.ts tests/webModuleIdentity.test.ts diff --git a/apps/web/Dockerfile b/apps/web/Dockerfile index 3ad0eeb4..96476f88 100644 --- a/apps/web/Dockerfile +++ b/apps/web/Dockerfile @@ -91,7 +91,7 @@ RUN bun scripts/prepare-web-library.ts \ # Use the installed binaries directly: the verifier mounts the toolchain read-only. # Agent shells cannot read /opt/theorem-os or /opt/runtime-state; they run the bundled commands instead. RUN bun scripts/build.ts --state-root /opt/runtime-state > /opt/theoremos-build.json \ - && bun scripts/build-agent-tools.ts --out /opt/theoremos-agent-tools > /dev/null \ + && cp -R out/main/agent-tools /opt/theoremos-agent-tools \ && bun scripts/build-proof-environment-seed.ts --project /opt/theoremos-mathlib \ --packages /opt/theoremos-mathlib/.lake/packages --out /opt/theoremos-proof-environment-seed \ && bun scripts/build-proof-environment-seed.ts --project /opt/theoremos-mathlib \ diff --git a/apps/web/libraryResearch.ts b/apps/web/libraryResearch.ts index c75139ef..4a2b3fda 100644 --- a/apps/web/libraryResearch.ts +++ b/apps/web/libraryResearch.ts @@ -3,7 +3,13 @@ import path from 'node:path'; import { mathDigest, readMathJson, readMathText, writeMathJsonDurable } from '../../src/math/mathRuntimeIo'; import { assertMathCanonicalPath, isMathPathWithin } from '../../src/math/paths'; import { readSolverRunState, type SolverRunState, type SolverWorkerState } from '../../src/solver/archive'; -import { readContinuationInput, type ContinuationAttachmentKind } from '../../src/solver/continuationInput'; +import { + MAX_CONTINUATION_ATTACHMENT_BYTES, + MAX_CONTINUATION_ATTACHMENTS, + MAX_CONTINUATION_TOTAL_BYTES, + readContinuationInput, + type ContinuationAttachmentKind, +} from '../../src/solver/continuationInput'; import { requestedLibraryPack, type LibraryAccess, type LibraryRequest } from '../../src/solver/libraryAccess'; import type { LibrarySelection } from '../../src/solver/libraryCatalog'; import { nativeApprovalPlanBrief, planApprovalStatus } from '../../src/solver/planApproval'; @@ -31,44 +37,65 @@ type Material = { text: string; provenance: { source?: string; evidence: 'unverified' | 'recorded-not-replayed'; runId?: string; commit?: string }; }; +type Attachment = Material & { sha256: string; bytes: number }; -/** Library changes create new receipts. Prior proof work is carried only as advisory reading material. */ -function writeResearchContinuation(directory: string, seed: Seed, materials: Map) { - let entries = [...materials.entries()]; - if (entries.length > 32) { - const grouped: [string, Material][] = []; - for (const kind of new Set(entries.map(([, item]) => item.kind))) { - let text = ''; - const flush = () => { - if (text) - grouped.push([ - mathDigest(text), - { - kind, - text, - provenance: { - evidence: 'unverified', - source: - 'Saved library research archive; each entry retains its own provenance and original content digest.', - }, - }, - ]); - text = ''; - }; - for (const [digest, item] of entries.filter(([, item]) => item.kind === kind)) { - const part = `\n--- Saved material ${digest} ---\nProvenance: ${JSON.stringify(item.provenance)}\n${item.text}\n`; - if (Buffer.byteLength(text) + Buffer.byteLength(part) > 16_000_000) flush(); - text += part; +function packResearch(materials: Attachment[]): Attachment[] { + if (materials.length <= MAX_CONTINUATION_ATTACHMENTS) return materials; + const grouped: Attachment[] = []; + for (const kind of new Set(materials.map(item => item.kind))) { + let parts: string[] = []; + let bytes = 0; + let first: Attachment | undefined; + const flush = () => { + if (parts.length === 1) grouped.push(first!); + else if (parts.length > 1) { + const text = parts.join(''); + grouped.push({ + kind, + text, + bytes, + sha256: mathDigest(text), + provenance: { + evidence: 'unverified', + source: + 'Saved library research archive; each entry retains its own provenance and original content digest.', + }, + }); + } + parts = []; + bytes = 0; + first = undefined; + }; + for (const item of materials.filter(item => item.kind === kind)) { + const header = `\n--- Saved material ${item.sha256} ---\nProvenance: ${JSON.stringify(item.provenance)}\n`; + const partBytes = Buffer.byteLength(header) + item.bytes + 1; + if (bytes + partBytes > MAX_CONTINUATION_ATTACHMENT_BYTES) flush(); + if (partBytes > MAX_CONTINUATION_ATTACHMENT_BYTES) { + grouped.push(item); + continue; } - flush(); + first ??= item; + parts.push(header + item.text + '\n'); + bytes += partBytes; } - entries = grouped; + flush(); } - const attachments = entries.map(([sha256, item], index) => { - const file = `research-${index}.txt`, - bytes = Buffer.byteLength(item.text); - fs.writeFileSync(path.join(directory, file), item.text, { mode: 0o600, flag: 'wx' }); - return { id: `research-${index}`, kind: item.kind, path: file, sha256, bytes, provenance: item.provenance }; + if ( + grouped.length <= MAX_CONTINUATION_ATTACHMENTS && + grouped.reduce((total, item) => total + item.bytes, 0) <= MAX_CONTINUATION_TOTAL_BYTES + ) + return grouped; + // The initial continuation already fits on its own and precedes collected material. + return materials.slice(0, MAX_CONTINUATION_ATTACHMENTS); +} + +/** Library changes create new receipts. Prior proof work is carried only as advisory reading material. */ +function writeResearchContinuation(directory: string, seed: Seed, materials: Attachment[]) { + if (!materials.length) return; + const attachments = packResearch(materials).map(({ text, ...item }, index) => { + const file = `research-${index}.txt`; + fs.writeFileSync(path.join(directory, file), text, { mode: 0o600, flag: 'wx' }); + return { id: `research-${index}`, path: file, ...item }; }); const file = path.join(directory, 'continuation-input.json'); const identity = { @@ -81,8 +108,19 @@ function writeResearchContinuation(directory: string, seed: Seed, materials: Map return file; } -function collectResearch(state: SolverRunState, directory: string, materials: Map) { +function readAdvisoryFile(file: string, maxBytes: number) { + assertMathCanonicalPath(file); + try { + return readMathText(file, maxBytes); + } catch (error) { + if (error instanceof Error && error.message === 'math_runtime_file_too_large') return; + throw error; + } +} + +function collectResearch(state: SolverRunState, directory: string, remember: (item: Material) => void) { const trees = [...new Set([state.worktree, ...(state.workers ?? []).map(worker => worker.worktree)])]; + const files = state.problem.ownedFiles.filter(file => !state.problem.frozenFiles?.[file]); for (const [index, tree] of trees.entries()) { if (!isMathPathWithin(directory, tree)) throw new Error('math_library_request_worktree_outside_run'); assertMathCanonicalPath(tree); @@ -94,20 +132,16 @@ function collectResearch(state: SolverRunState, directory: string, materials: Ma commit, }; // Writers have all stopped. Keep saved drafts as well as committed work, without copying frozen library modules. - const files = state.problem.ownedFiles.filter(file => !state.problem.frozenFiles?.[file]); - const text = files - .map(file => { - const full = path.join(tree, state.problem.projectRelative, file); - assertMathCanonicalPath(full); - return `-- Saved file: ${file}\n${readMathText(full, 16_000_000)}`; - }) - .join('\n\n'); - if (text) materials.set(mathDigest(text), { kind: 'proof-source', text, provenance }); + for (const file of files) { + const full = path.join(tree, state.problem.projectRelative, file); + const header = `-- Saved file: ${file}\n`; + const text = readAdvisoryFile(full, MAX_CONTINUATION_ATTACHMENT_BYTES - Buffer.byteLength(header)); + if (text !== undefined) remember({ kind: 'proof-source', text: header + text, provenance }); + } const notesFile = path.join(tree, 'RESEARCH.md'); if (fs.existsSync(notesFile)) { - assertMathCanonicalPath(notesFile); - const notes = readMathText(notesFile, 16_000_000); - if (notes) materials.set(mathDigest(notes), { kind: 'research-notes', text: notes, provenance }); + const notes = readAdvisoryFile(notesFile, MAX_CONTINUATION_ATTACHMENT_BYTES); + if (notes) remember({ kind: 'research-notes', text: notes, provenance }); } } } @@ -136,19 +170,26 @@ export async function runWebLibraryResearch(options: { libraryCatalog: options.libraryCatalog, planApproval: options.request.input.planApproval, }; - const materials = new Map(); + const materials: Attachment[] = []; if (options.continuationFile) { const input = readContinuationInput(options.continuationFile, { taskDigest: mathDigest(readMathText(options.seed.taskFile)), problemReceiptDigest: readSolverProblem(options.seed.workspaceRoot, options.seed.activeProblemPath).receiptDigest, }); - for (const item of input.manifest.attachments) - materials.set(item.sha256, { - text: input.contents.get(item.sha256)!, - kind: item.kind, - provenance: item.provenance, - }); + for (const { sha256, bytes, kind, provenance } of input.manifest.attachments) + materials.push({ sha256, bytes, kind, provenance, text: input.contents.get(sha256)! }); } + const materialDigests = new Set(materials.map(item => item.sha256)); + let remainingBytes = MAX_CONTINUATION_TOTAL_BYTES - materials.reduce((total, item) => total + item.bytes, 0); + const remember = (item: Material) => { + const bytes = Buffer.byteLength(item.text); + if (bytes > remainingBytes || bytes > MAX_CONTINUATION_ATTACHMENT_BYTES) return; + const sha256 = mathDigest(item.text); + if (materialDigests.has(sha256)) return; + materialDigests.add(sha256); + remainingBytes -= bytes; + materials.push({ ...item, sha256, bytes }); + }; let turns = 0, solveWallMs = 0, solveExecutionMs = 0; @@ -246,7 +287,7 @@ export async function runWebLibraryResearch(options: { const text = `This route was approved before proof work began. Continue the research with the installed library.\n` + nativeApprovalPlanBrief(state.cooperation.tasks); - materials.set(mathDigest(text), { + remember({ kind: 'research-notes', text, provenance: { @@ -275,7 +316,7 @@ export async function runWebLibraryResearch(options: { ? 'math_run_stopped' : tokenBudget.reason; if (reason) return finish({ ...raw, status: 'limit_reached', run_outcome: 'limit_reached', reason }); - collectResearch(state, options.directory, materials); + collectResearch(state, options.directory, remember); const round = current.round + 1, directory = path.join(options.directory, 'rounds', String(round)); fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); diff --git a/apps/web/worker.ts b/apps/web/worker.ts index fa6552ba..ce624f6b 100644 --- a/apps/web/worker.ts +++ b/apps/web/worker.ts @@ -8,7 +8,7 @@ import { classifyWebError, classifyWebResult } from './failure'; import { getLeanTaskEnvironment, type LeanTaskEnvironment } from '../../src/math/leanTaskEnvironment'; import { PANTOGRAPH_DIGEST_ENV, PANTOGRAPH_MANIFEST_ENV } from '../../src/math/pantographSession'; import { mathDigest, readMathJson, readMathText } from '../../src/math/mathRuntimeIo'; -import { readMathBuildManifest } from '../../src/math/mathBuildManifest'; +import { assertMathBuildAgentTools, readMathBuildManifest } from '../../src/math/mathBuildManifest'; import { isMathPathWithin } from '../../src/math/paths'; import { sub2apiModelCatalog } from '../../src/runtime/sub2api'; import { configurableRuntimeModules, type RuntimeSolverModules } from '../../src/solver/modules/runtime'; @@ -349,20 +349,6 @@ export function webSolverModules( return base.M1.open({ ...options, ...(isolation ? { hiddenRoots: [...(options.hiddenRoots ?? []), ...isolation.hiddenRoots] } : {}), - ...(isolation && options.leanHealthCheck - ? { - leanHealthCheck: { - executable: isNativeToolBundle(isolation.tools) - ? isolation.tools - : options.leanHealthCheck.executable, - arguments: [ - ...(isNativeToolBundle(isolation.tools) ? [] : [isolation.tools]), - 'check-lean', - ...options.leanHealthCheck.arguments.slice(1), - ], - }, - } - : {}), environment: { ...options.environment, THEOREMOS_PROVIDER_API_KEY: request.input.apiKey }, ...(context ? { @@ -519,7 +505,7 @@ async function main(watchdog: ReturnType const receipt = prepareWebProblem(directory, request); const buildFile = process.env.THEOREMOS_WORKER_BUILD || '/opt/theoremos-build.json'; const buildIndex = readMathJson(buildFile) as { buildManifestRef: string }; - readMathBuildManifest(buildIndex.buildManifestRef, root, path.join(root, 'out/main')); + const build = readMathBuildManifest(buildIndex.buildManifestRef, root, path.join(root, 'out/main'), 'source'); const taskFile = receipt.taskFile; const knowledgeFile = freezeWebKnowledge(directory, request.knowledgeCatalog); const expertCardArguments = webExpertCardArguments(directory, request); @@ -543,6 +529,11 @@ async function main(watchdog: ReturnType // Without the bundle the shells would need the application itself, so the run stops rather than expose it. if (!fs.existsSync(tools) || isMathPathWithin(root, fs.realpathSync(tools))) throw new Error('math_agent_tools_unavailable'); + // Native deployments can supply their own dispatcher. The packaged TypeScript copy is bound to this build. + if (!isNativeToolBundle(tools)) { + if ('agentTools' in build && path.basename(tools) !== 'math.mjs') throw new Error('math_agent_tools_unavailable'); + assertMathBuildAgentTools(build, path.dirname(path.resolve(tools))); + } const modules = webSolverModules( request, { diff --git a/bin/math.ts b/bin/math.ts index 0393b4c8..735fe6d6 100644 --- a/bin/math.ts +++ b/bin/math.ts @@ -6,7 +6,21 @@ import { spawn } from 'node:child_process'; import os from 'node:os'; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +export const agentToolCommands = { + 'check-lean': 'scripts/mathematics/checkLean.ts', + 'search-lean': 'scripts/mathematics/searchLean.ts', + declarations: 'scripts/mathematics/readDeclarations.ts', + knowledge: 'scripts/mathematics/theoremKnowledge.ts', + hub: 'scripts/mathematics/huggingMath.ts', + checkpoint: 'scripts/mathematics/checkpoint.ts', + 'plan-validate': 'scripts/mathematics/planValidate.ts', + 'check-finite': 'scripts/mathematics/checkFinite.ts', + 'kernel-certificate': 'scripts/mathematics/kernelCertificate.ts', + library: 'scripts/mathematics/library.ts', + continuation: 'scripts/mathematics/readContinuation.ts', +} as const; const commands: Readonly> = { + ...agentToolCommands, build: 'scripts/build.ts', doctor: 'scripts/mathematics/doctor.ts', example: 'scripts/mathematics/runExample.ts', @@ -17,24 +31,9 @@ const commands: Readonly> = { 'bootstrap-lean-eval': 'scripts/mathematics/bootstrapLeanEvalHeldOut.ts', 'list-lean-eval': 'scripts/mathematics/listLeanEval.ts', 'freeze-retrieval': 'scripts/mathematics/freezeMathRetrievalCorpus.ts', - 'search-lean': fs.existsSync(path.join(root, 'out/main/search-lean.js')) - ? 'out/main/search-lean.js' - : 'scripts/mathematics/searchLean.ts', - declarations: 'scripts/mathematics/readDeclarations.ts', - knowledge: 'scripts/mathematics/theoremKnowledge.ts', - hub: 'scripts/mathematics/huggingMath.ts', - 'check-lean': fs.existsSync(path.join(root, 'out/main/check-lean.js')) - ? 'out/main/check-lean.js' - : 'scripts/mathematics/checkLean.ts', - checkpoint: 'scripts/mathematics/checkpoint.ts', - 'plan-validate': 'scripts/mathematics/planValidate.ts', - 'check-finite': 'scripts/mathematics/checkFinite.ts', - 'kernel-certificate': 'scripts/mathematics/kernelCertificate.ts', 'library-pack': 'scripts/mathematics/libraryPack.ts', 'library-catalog': 'scripts/mathematics/libraryCatalog.ts', - library: 'scripts/mathematics/library.ts', 'auto-library': 'scripts/mathematics/autoLibrary.ts', - continuation: 'scripts/mathematics/readContinuation.ts', 'continuation-seed': 'scripts/mathematics/seedContinuation.ts', inspect: 'scripts/mathematics/inspectMathRun.ts', recover: 'scripts/mathematics/recoverMathSnapshot.ts', @@ -47,45 +46,59 @@ const commands: Readonly> = { 'evaluate-formalization': 'scripts/mathematics/evaluateFormalization.ts', summarize: 'scripts/mathematics/summarizeMathProofRuns.ts', }; -const [command, ...args] = process.argv.slice(2); -if (args.length === 1 && args[0] === '-h') args[0] = '--help'; -const runHelp = command === 'run' && args.length === 1 && args[0] === '--help'; -const missingBundle = command === 'run' && !fs.existsSync(path.join(root, commands.run)); -if (!command || ['help', '--help', '-h'].includes(command)) { - process.stdout.write(fs.readFileSync(path.join(root, 'bin/math-help.txt'))); -} else if (!Object.hasOwn(commands, command)) { - console.error(`Unknown command: ${command}. Run theorem-os --help to list commands.`); - process.exitCode = 1; -} else if (missingBundle && !runHelp) { - console.error('Solver bundle not found. From the checkout, run bun run build, then retry theorem-os run.'); - process.exitCode = 1; -} else { - // Only help may use the source entry; proof runs require the frozen bundle. - const bundledSeed = command === 'continuation-seed' && fs.existsSync(path.join(root, commands.run)); - const entry = bundledSeed ? commands.run : missingBundle ? 'scripts/mathematics/runMathProof.ts' : commands[command]!; - if (bundledSeed) args.unshift('--theoremos-continuation-seed'); - const env = { - ...process.env, - CODEX_HOME: process.env.CODEX_HOME || path.join(os.homedir(), '.config', 'deepscientist', 'math-sol-codex'), - }; - // Argument arrays preserve literal task/evaluator arguments without a shell. - const child = spawn(process.execPath, [path.join(root, entry), ...args], { - cwd: process.cwd(), - env, - stdio: 'inherit', - }); - const forward = (signal: NodeJS.Signals) => child.kill(signal); - const interrupt = () => forward('SIGINT'); - const terminate = () => forward('SIGTERM'); - process.on('SIGINT', interrupt); - process.on('SIGTERM', terminate); - child.once('error', error => { - console.error(error.message); +if (import.meta.main) runCli(); + +function runCli() { + const [command, ...args] = process.argv.slice(2); + if (args.length === 1 && args[0] === '-h') args[0] = '--help'; + const runHelp = command === 'run' && args.length === 1 && args[0] === '--help'; + const missingBundle = command === 'run' && !fs.existsSync(path.join(root, commands.run)); + if (!command || ['help', '--help', '-h'].includes(command)) { + process.stdout.write(fs.readFileSync(path.join(root, 'bin/math-help.txt'))); + } else if (!Object.hasOwn(commands, command)) { + console.error(`Unknown command: ${command}. Run theorem-os --help to list commands.`); + process.exitCode = 1; + } else if (missingBundle && !runHelp) { + console.error('Solver bundle not found. From the checkout, run bun run build, then retry theorem-os run.'); process.exitCode = 1; - }); - child.once('exit', (code, signal) => { - process.removeListener('SIGINT', interrupt); - process.removeListener('SIGTERM', terminate); - process.exitCode = code ?? (signal === 'SIGINT' ? 130 : signal === 'SIGTERM' ? 143 : 1); - }); + } else { + // Only help may use the source entry; proof runs require the frozen bundle. + const bundledSeed = command === 'continuation-seed' && fs.existsSync(path.join(root, commands.run)); + let entry = path.join( + root, + bundledSeed ? commands.run : missingBundle ? 'scripts/mathematics/runMathProof.ts' : commands[command]!, + ); + const tools = path.join(root, 'out/main/agent-tools'); + if (Object.hasOwn(agentToolCommands, command) && fs.existsSync(tools)) { + entry = path.join(tools, `${command}.mjs`); + } else if (command === 'check-lean' || command === 'search-lean') { + const legacy = path.join(root, 'out/main', `${command}.js`); + if (fs.existsSync(legacy)) entry = legacy; + } + if (bundledSeed) args.unshift('--theoremos-continuation-seed'); + const env = { + ...process.env, + CODEX_HOME: process.env.CODEX_HOME || path.join(os.homedir(), '.config', 'deepscientist', 'math-sol-codex'), + }; + // Argument arrays preserve literal task/evaluator arguments without a shell. + const child = spawn(process.execPath, [entry, ...args], { + cwd: process.cwd(), + env, + stdio: 'inherit', + }); + const forward = (signal: NodeJS.Signals) => child.kill(signal); + const interrupt = () => forward('SIGINT'); + const terminate = () => forward('SIGTERM'); + process.on('SIGINT', interrupt); + process.on('SIGTERM', terminate); + child.once('error', error => { + console.error(error.message); + process.exitCode = 1; + }); + child.once('exit', (code, signal) => { + process.removeListener('SIGINT', interrupt); + process.removeListener('SIGTERM', terminate); + process.exitCode = code ?? (signal === 'SIGINT' ? 130 : signal === 'SIGTERM' ? 143 : 1); + }); + } } diff --git a/docs/usage.md b/docs/usage.md index 192c8327..b917899a 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -40,7 +40,7 @@ bun install --frozen-lockfile bun run build ``` -构建生成 `out/main/math-solver.js`、`out/main/search-lean.js` 和 `out/main/check-lean.js`,并输出 JSON。运行时传入 `buildManifestRef` 对应的绝对路径。源码与 bundle 均按哈希校验,修改运行时代码后需重新构建。 +构建生成 `out/main/math-solver.js`,并将 Lean 检查、检索等 CLI 与 Web 共用的 Agent 工具打包到 `out/main/agent-tools/`。运行时传入构建输出中 `buildManifestRef` 对应的绝对路径。清单按哈希校验源码、求解器和工具,修改运行时代码后需重新构建。 CLI 默认使用 `~/.config/deepscientist/math-sol-codex` 中的 Codex profile,通过本地 Sub2API 网关 `http://127.0.0.1:8080/v1` 调用模型。`run` 的默认模型为 `deepseek-flash`,新运行的默认推理强度为 `high`。本机 profile 的认证命令按需读取已有部署的 Westlake 号池密钥,无需复制密钥或手动 export。也可通过 `CODEX_HOME` 指向其他已有 profile。 diff --git a/scripts/build-agent-tools.ts b/scripts/build-agent-tools.ts index f2cf4566..5fe5382a 100644 --- a/scripts/build-agent-tools.ts +++ b/scripts/build-agent-tools.ts @@ -5,93 +5,111 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { execFileSync } from 'node:child_process'; import { parseArgs } from 'node:util'; -import { build } from 'esbuild'; +import { build, type Metafile, type Plugin } from 'esbuild'; +import { agentToolCommands } from '../bin/math'; import { buildMathResources } from './build-math-resources'; -/** - * The commands an Agent's shell runs, bundled into one directory outside the application: the web worker hides - * the application tree from Agent shells, so these files are all of the code a shell can read. `--out DIR`. - */ -const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); -const { values } = parseArgs({ - options: { out: { type: 'string' }, 'rust-tools': { type: 'string' }, 'native-process': { type: 'string' } }, -}); -const output = path.resolve(values.out ?? path.join(root, 'out/agent-tools')); -const agentToolCommands = { - 'check-lean': 'checkLean.ts', - 'search-lean': 'searchLean.ts', - knowledge: 'theoremKnowledge.ts', - library: 'library.ts', - declarations: 'readDeclarations.ts', - hub: 'huggingMath.ts', - checkpoint: 'checkpoint.ts', - 'plan-validate': 'planValidate.ts', - 'check-finite': 'checkFinite.ts', - 'kernel-certificate': 'kernelCertificate.ts', - continuation: 'readContinuation.ts', -} as const; -const native = values['rust-tools'] ? path.resolve(values['rust-tools']) : undefined; -const migrated = new Set(native ? execFileSync(native, ['--list'], { encoding: 'utf8' }).trim().split('\n') : []); -const hosted = Object.keys(agentToolCommands).some(name => !migrated.has(name)); -const addon = hosted && values['native-process'] ? fs.readFileSync(path.resolve(values['native-process'])) : undefined; -for (const name of migrated) - if (!Object.hasOwn(agentToolCommands, name)) throw new Error(`Unknown native worker command: ${name}`); -fs.rmSync(output, { recursive: true, force: true }); -const result = await build({ - entryPoints: { - math: path.join(root, 'scripts/mathematics/agentTools.ts'), - ...Object.fromEntries( - Object.entries(agentToolCommands) - .filter(([name]) => !migrated.has(name)) - .map(([name, file]) => [name, path.join(root, 'scripts/mathematics', file)]), - ), +export const noDesktopRuntime: Plugin = { + name: 'no-desktop-runtime', + setup(build) { + build.onResolve({ filter: /^(?:electron|react|react-dom|@office-ai\/platform)(?:\/|$)/ }, ({ path }) => { + throw new Error(`Desktop dependency is forbidden: ${path}`); + }); }, - // ESM for the commands' top-level await; bundled CommonJS dependencies still need require for node: modules. - outdir: output, - outExtension: { '.js': '.mjs' }, - bundle: true, - platform: 'node', - format: 'esm', - define: { - ...buildMathResources(root, output), - ...(addon && { - __THEOREMOS_NATIVE_PROCESS_SHA256__: JSON.stringify(crypto.createHash('sha256').update(addon).digest('hex')), - }), - }, - minify: true, - legalComments: 'none', - metafile: true, - banner: { - js: "import{createRequire as __agentRequire}from'node:module';const require=__agentRequire(import.meta.url);const __dirname=import.meta.dirname;", - }, - loader: { '.py': 'text', '.lean': 'text' }, - tsconfig: path.join(root, 'tsconfig.json'), - logLevel: 'silent', -}); -// Nothing may stay a runtime import: the shell sees no node_modules. -const external = Object.values(result.metafile.outputs).flatMap(item => - item.imports.filter(entry => entry.external && !entry.path.startsWith('node:')), -); -if (external.length) - throw new Error( - `Agent tools import outside the bundle: ${[...new Set(external.map(entry => entry.path))].join(', ')}`, +}; + +/** Build the dispatcher and its commands in a fresh output directory. */ +export async function buildAgentTools( + root: string, + output: string, + options: { native?: string; addon?: Buffer | string } = {}, +): Promise { + const { native } = options; + const migrated = new Set(native ? execFileSync(native, ['--list'], { encoding: 'utf8' }).trim().split('\n') : []); + const hosted = Object.keys(agentToolCommands).some(name => !migrated.has(name)); + for (const name of migrated) + if (!Object.hasOwn(agentToolCommands, name)) throw new Error(`Unknown native worker command: ${name}`); + const addon = hosted + ? typeof options.addon === 'string' + ? fs.readFileSync(options.addon) + : options.addon + : undefined; + const { metafile } = await build({ + absWorkingDir: root, + entryPoints: { + math: 'scripts/mathematics/agentTools.ts', + ...Object.fromEntries(Object.entries(agentToolCommands).filter(([name]) => !migrated.has(name))), + }, + // ESM for the commands' top-level await; bundled CommonJS dependencies still need require for node: modules. + outdir: output, + outExtension: { '.js': '.mjs' }, + bundle: true, + platform: 'node', + format: 'esm', + define: { + ...buildMathResources(root, output), + ...(addon && { + __THEOREMOS_NATIVE_PROCESS_SHA256__: JSON.stringify(crypto.createHash('sha256').update(addon).digest('hex')), + }), + }, + minify: true, + legalComments: 'none', + metafile: true, + banner: { + js: "import{createRequire as __agentRequire}from'node:module';const require=__agentRequire(import.meta.url);const __dirname=import.meta.dirname;", + }, + loader: { '.py': 'text', '.lean': 'text' }, + tsconfig: path.join(root, 'tsconfig.json'), + logLevel: 'silent', + plugins: [noDesktopRuntime], + }); + // Nothing may stay a runtime import: the shell sees no node_modules. + const external = Object.values(metafile.outputs).flatMap(item => + item.imports.filter(entry => entry.external && !entry.path.startsWith('node:')), ); -if (addon) fs.writeFileSync(path.join(output, 'theoremos-process.node'), addon, { flag: 'wx', mode: 0o444 }); -if (native) { - const dispatcher = path.join(output, 'math.native'); - // Legacy tools in this bundle use the same Bun as its builder, even with a different shell PATH. - if (hosted) fs.symlinkSync(process.execPath, path.join(output, 'bun')); - fs.copyFileSync(native, dispatcher); - fs.chmodSync(dispatcher, 0o755); - for (const name of migrated) fs.linkSync(dispatcher, path.join(output, name + '.native')); + if (external.length) + throw new Error( + `Agent tools import outside the bundle: ${[...new Set(external.map(entry => entry.path))].join(', ')}`, + ); + if (addon) fs.writeFileSync(path.join(output, 'theoremos-process.node'), addon, { flag: 'wx', mode: 0o444 }); + if (native) { + const dispatcher = path.join(output, 'math.native'); + // Legacy tools in this bundle use the same Bun as its builder, even with a different shell PATH. + if (hosted) fs.symlinkSync(process.execPath, path.join(output, 'bun')); + fs.copyFileSync(native, dispatcher); + fs.chmodSync(dispatcher, 0o755); + for (const name of migrated) fs.linkSync(dispatcher, path.join(output, name + '.native')); + } + return metafile; } -console.log( - JSON.stringify({ - output, - files: fs - .readdirSync(output, { withFileTypes: true }) + +if (import.meta.main) { + const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); + const { values } = parseArgs({ + options: { out: { type: 'string' }, 'rust-tools': { type: 'string' }, 'native-process': { type: 'string' } }, + }); + if (values.out === '') throw new Error('Missing value for --out'); + const output = path.resolve(values.out ?? path.join(root, 'out/agent-tools')); + const existing = fs.lstatSync(output, { throwIfNoEntry: false }); + if (existing && (!existing.isDirectory() || fs.readdirSync(output).length > 0)) + throw new Error(`Agent tools output must be an empty directory: ${output}`); + + const native = values['rust-tools'] ? path.resolve(values['rust-tools']) : undefined; + const addon = values['native-process'] ? path.resolve(values['native-process']) : undefined; + const parent = path.dirname(output); + fs.mkdirSync(parent, { recursive: true }); + const staging = fs.mkdtempSync(path.join(parent, '.agent-tools-')); + try { + const candidate = path.join(staging, 'tools'); + await buildAgentTools(root, candidate, { native, addon }); + const files = fs + .readdirSync(candidate, { withFileTypes: true }) .filter(entry => !entry.isDirectory()) .map(entry => entry.name) - .sort(), - }), -); + .sort(); + fs.renameSync(candidate, output); + console.log(JSON.stringify({ output, files })); + } finally { + fs.rmSync(staging, { recursive: true, force: true }); + } +} diff --git a/scripts/build.ts b/scripts/build.ts index acf84cda..d7dc9895 100644 --- a/scripts/build.ts +++ b/scripts/build.ts @@ -4,9 +4,17 @@ import path from 'node:path'; import crypto from 'node:crypto'; import { fileURLToPath } from 'node:url'; import { build } from 'esbuild'; +import { buildAgentTools, noDesktopRuntime } from './build-agent-tools'; import { buildMathResources } from './build-math-resources'; -import { mathBuildFile, mathBuildSource, MATH_RUNTIME_BUNDLES } from '../src/math/mathBuildManifest'; -import { canonicalMathJson, writeMathJsonDurable, syncMathDirectory } from '../src/math/mathRuntimeIo'; +import { + mathBuildAgentToolFiles, + mathBuildFile, + mathBuildSource, + mathRuntimeInputPaths, + MATH_AGENT_TOOLS_DIRECTORY, + MATH_SOLVER_BUNDLE, +} from '../src/math/mathBuildManifest'; +import { canonicalMathJson, writeMathJsonDurable } from '../src/math/mathRuntimeIo'; import { isMathPathWithin } from '../src/math/paths'; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); @@ -34,69 +42,104 @@ if (args.includes('--help') || args.includes('-h')) { const nativeBytes = nativePath ? fs.readFileSync(nativePath) : undefined; const nativeDigest = nativeBytes ? crypto.createHash('sha256').update(nativeBytes).digest('hex') : undefined; const source = mathBuildSource(root); - const bundleRoot = path.join(root, 'out', 'main'); - fs.rmSync(bundleRoot, { recursive: true, force: true }); - // Reject any reintroduced desktop dependency instead of leaving a runtime stub. - await build({ - entryPoints: { - 'math-solver': path.join(root, 'scripts/mathematics/runMathProof.ts'), - 'search-lean': path.join(root, 'scripts/mathematics/searchLean.ts'), - 'check-lean': path.join(root, 'scripts/mathematics/checkLean.ts'), - }, - outdir: bundleRoot, - bundle: true, - platform: 'node', - format: 'cjs', - define: { - ...buildMathResources(root, bundleRoot), - ...(nativeDigest && { __THEOREMOS_NATIVE_PROCESS_SHA256__: JSON.stringify(nativeDigest) }), - }, - loader: { '.py': 'text', '.lean': 'text' }, - tsconfig: path.join(root, 'tsconfig.json'), - metafile: true, - logLevel: 'silent', - plugins: [ - { - name: 'no-desktop-runtime', - setup(build) { - build.onResolve({ filter: /^(?:electron|react|react-dom|@office-ai\/platform)(?:\/|$)/ }, ({ path }) => { - throw new Error(`Desktop dependency is forbidden: ${path}`); - }); - }, + const output = path.join(root, 'out'); + const bundleRoot = path.join(output, 'main'); + fs.mkdirSync(output, { recursive: true }); + const staging = fs.mkdtempSync(path.join(output, '.math-build-')); + const candidate = path.join(staging, 'main'); + const previous = path.join(staging, 'previous'); + let preserveStaging = false; + try { + // Reject any reintroduced desktop dependency instead of leaving a runtime stub. + const { metafile } = await build({ + absWorkingDir: root, + outfile: path.join(candidate, MATH_SOLVER_BUNDLE), + bundle: true, + metafile: true, + platform: 'node', + define: { + ...buildMathResources(root, candidate), + ...(nativeDigest && { __THEOREMOS_NATIVE_PROCESS_SHA256__: JSON.stringify(nativeDigest) }), }, - ], - }); - if (nativeBytes) { - fs.writeFileSync(path.join(bundleRoot, 'theoremos-process.node'), nativeBytes, { flag: 'wx', mode: 0o444 }); - fs.writeFileSync(path.join(bundleRoot, 'theoremos-process.sha256'), nativeDigest + '\n', { - flag: 'wx', - mode: 0o444, + loader: { '.py': 'text', '.lean': 'text' }, + tsconfig: path.join(root, 'tsconfig.json'), + logLevel: 'silent', + plugins: [noDesktopRuntime], + entryPoints: ['scripts/mathematics/runMathProof.ts'], + format: 'cjs', }); - } - if (canonicalMathJson(mathBuildSource(root)) !== canonicalMathJson(source)) - throw new Error('math_runtime_build_inputs_changed'); - const buildId = crypto.randomUUID(); - const directory = path.join(stateRoot, 'builds', buildId); - fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); - const manifest = path.join(directory, 'manifest.json'); - writeMathJsonDurable(manifest, { - schema: 'deepscientist.math.build-manifest.v1', - buildId, - startedAt, - finishedAt: new Date().toISOString(), - source, - bundleRoot, - bundles: MATH_RUNTIME_BUNDLES.map(name => mathBuildFile(path.join(bundleRoot, name))), - }); - fs.chmodSync(manifest, 0o400); - const fd = fs.openSync(manifest, 'r'); - try { - fs.fsyncSync(fd); + const agentToolsDirectory = path.join(candidate, MATH_AGENT_TOOLS_DIRECTORY); + const toolMetafile = await buildAgentTools(root, agentToolsDirectory, { addon: nativeBytes }); + if (nativeBytes) { + fs.writeFileSync(path.join(candidate, 'theoremos-process.node'), nativeBytes, { flag: 'wx', mode: 0o444 }); + fs.writeFileSync(path.join(candidate, 'theoremos-process.sha256'), nativeDigest + '\n', { + flag: 'wx', + mode: 0o444, + }); + } + const knownInputs = new Set(source.inputs.map(entry => entry.path)); + const bundledPaths = [...Object.keys(metafile.inputs), ...Object.keys(toolMetafile.inputs)] + .filter(file => file !== '') + .map(file => path.resolve(root, file.replace(/\?raw$/u, ''))) + // The solver can run without installed dependencies. Package metadata and output hashes pin the bundled bytes. + .filter(file => !file.split(path.sep).includes('node_modules')) + .map(file => path.relative(root, file)); + const runtimeInputs = mathRuntimeInputPaths(root, [...bundledPaths, 'scripts/build-agent-tools.ts']); + const unknownInput = runtimeInputs.find(relative => !knownInputs.has(path.join(root, relative))); + if (unknownInput) throw new Error('math_runtime_build_input_unknown:' + unknownInput); + if (canonicalMathJson(mathBuildSource(root)) !== canonicalMathJson(source)) + throw new Error('math_runtime_build_inputs_changed'); + const bundles = [ + { + ...mathBuildFile(path.join(candidate, MATH_SOLVER_BUNDLE)), + path: path.join(bundleRoot, MATH_SOLVER_BUNDLE), + }, + ]; + const agentTools = mathBuildAgentToolFiles(agentToolsDirectory).map(entry => ({ + ...entry, + path: path.join(bundleRoot, path.relative(candidate, entry.path)), + })); + const buildId = crypto.randomUUID(); + const builds = path.join(stateRoot, 'builds'); + const directory = path.join(builds, buildId); + fs.mkdirSync(builds, { recursive: true, mode: 0o700 }); + fs.mkdirSync(directory, { mode: 0o700 }); + const manifest = path.join(directory, 'manifest.json'); + try { + writeMathJsonDurable( + manifest, + { + schema: 'deepscientist.math.build-manifest.v4', + buildId, + startedAt, + finishedAt: new Date().toISOString(), + source, + runtimeInputs, + bundleRoot, + bundles, + agentTools, + }, + 0o400, + ); + const hasPrevious = fs.existsSync(bundleRoot); + if (hasPrevious) fs.renameSync(bundleRoot, previous); + try { + fs.renameSync(candidate, bundleRoot); + } catch (error) { + if (hasPrevious) { + // If restoration itself fails, leave the prior bundle available in staging. + preserveStaging = true; + fs.renameSync(previous, bundleRoot); + preserveStaging = false; + } + throw error; + } + } catch (error) { + fs.rmSync(directory, { recursive: true, force: true }); + throw error; + } + console.log(JSON.stringify({ buildId, buildManifestRef: manifest, bundleRoot, bundleCount: bundles.length })); } finally { - fs.closeSync(fd); + if (!preserveStaging) fs.rmSync(staging, { recursive: true, force: true }); } - syncMathDirectory(directory); - console.log( - JSON.stringify({ buildId, buildManifestRef: manifest, bundleRoot, bundleCount: MATH_RUNTIME_BUNDLES.length }), - ); } diff --git a/scripts/mathematics/autoLibrary.ts b/scripts/mathematics/autoLibrary.ts index 559001d4..d5b4a921 100644 --- a/scripts/mathematics/autoLibrary.ts +++ b/scripts/mathematics/autoLibrary.ts @@ -137,6 +137,7 @@ function prepare(flags: ReadonlyMap, directory: string) { model: prover.model, effort: prover.effort, executable: prover.executable, + profile: prover.profile, ...(prover.agentHarness ? { agentHarness: prover.agentHarness } : {}), workers, coordination, diff --git a/scripts/mathematics/runExample.ts b/scripts/mathematics/runExample.ts index 3bf1bea8..e8ea815a 100644 --- a/scripts/mathematics/runExample.ts +++ b/scripts/mathematics/runExample.ts @@ -55,7 +55,7 @@ async function prepare( ); if (build.exitCode !== 0) throw new Error(`Example build failed: ${build.stderr || build.stdout}`); const { buildManifestRef } = JSON.parse(build.stdout); - readMathBuildManifest(buildManifestRef, root, path.join(root, 'out/main')); + readMathBuildManifest(buildManifestRef, root, path.join(root, 'out/main'), 'runtime'); const receipt = bootstrapLocalExample(path.join(directory, 'workspace')); fs.writeFileSync(path.join(directory, 'task.md'), task + '\n', { flag: 'wx', mode: 0o600 }); writeMathJsonDurable(path.join(directory, 'case.json'), { diff --git a/scripts/mathematics/verifyFirstProofOffline.ts b/scripts/mathematics/verifyFirstProofOffline.ts index 4b43c286..9b63c72d 100644 --- a/scripts/mathematics/verifyFirstProofOffline.ts +++ b/scripts/mathematics/verifyFirstProofOffline.ts @@ -37,7 +37,7 @@ export async function verifyFirstProofOffline(argv: string[]): Promise { throw new Error('Keep fixtures outside the source checkout.'); if (fs.existsSync(directory)) throw new Error('Offline fixture directory already exists; choose a new directory.'); const buildManifest = path.resolve(required(flags, 'build-manifest')); - readMathBuildManifest(buildManifest, root, path.join(root, 'out/main')); + readMathBuildManifest(buildManifest, root, path.join(root, 'out/main'), 'runtime'); fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); const task = 'Offline integration fixture, not a benchmark case. Prove both original natural-number addition targets.'; diff --git a/src/math/mathBuildManifest.ts b/src/math/mathBuildManifest.ts index b3d5306b..281473e5 100644 --- a/src/math/mathBuildManifest.ts +++ b/src/math/mathBuildManifest.ts @@ -3,7 +3,8 @@ import fs from 'node:fs'; import path from 'node:path'; import { z } from 'zod'; import { assertMathCanonicalPath, isMathPathWithin } from './paths'; -import { mathFileIdentity, readMathJson } from './mathRuntimeIo'; +import { mathDigest, mathFileIdentity, parseMathJson, readMathFile, readMathJson } from './mathRuntimeIo'; +import { MATH_RUNTIME_RESOURCES } from './mathRuntimeResources'; const hash = z.string().regex(/^[a-f0-9]{64}$/u); const fileSchema = z.object({ path: z.string(), bytes: z.number().int().nonnegative(), sha256: hash }).strict(); @@ -16,8 +17,11 @@ const sourceSchema = z inputs: z.array(fileSchema), }) .strict(); -export const MATH_RUNTIME_BUNDLES = ['math-solver.js', 'search-lean.js', 'check-lean.js'] as const; -const schema = z +export const MATH_SOLVER_BUNDLE = 'math-solver.js'; +/** Standalone bundles recorded by v1 through v3. */ +export const MATH_RUNTIME_BUNDLES = [MATH_SOLVER_BUNDLE, 'search-lean.js', 'check-lean.js'] as const; +export const MATH_AGENT_TOOLS_DIRECTORY = 'agent-tools'; +const v1Schema = z .object({ schema: z.literal('deepscientist.math.build-manifest.v1'), buildId: z.string().uuid(), @@ -28,6 +32,24 @@ const schema = z bundles: z.array(fileSchema).length(MATH_RUNTIME_BUNDLES.length), }) .strict(); +const schema = z.discriminatedUnion('schema', [ + v1Schema, + v1Schema.extend({ + schema: z.literal('deepscientist.math.build-manifest.v2'), + runtimeInputs: z.array(z.string()).nonempty(), + }), + v1Schema.extend({ + schema: z.literal('deepscientist.math.build-manifest.v3'), + runtimeInputs: z.array(z.string()).nonempty(), + agentTools: z.array(fileSchema).nonempty(), + }), + v1Schema.extend({ + schema: z.literal('deepscientist.math.build-manifest.v4'), + bundles: z.array(fileSchema).length(1), + runtimeInputs: z.array(z.string()).nonempty(), + agentTools: z.array(fileSchema).nonempty(), + }), +]); export type MathBuildManifest = Readonly>; export const MATH_BUILD_INPUTS = [ 'bun.lock', @@ -38,6 +60,10 @@ export const MATH_BUILD_INPUTS = [ 'bin/math.ts', 'scripts/mathematics/searchLean.ts', ] as const; +const sourceDirectories = ['src', 'scripts', 'bin', 'resources', 'skills']; +const runtimeDirectories = ['skills/theoremos-research']; +const runtimeResources = MATH_RUNTIME_RESOURCES.map(name => path.join('resources', name)); +const runtimeInputs = [...MATH_BUILD_INPUTS, 'scripts/build-math-resources.ts', ...runtimeResources]; const checkedFiles = new Map(); export function mathBuildFile(file: string): MathBuildFile { @@ -77,59 +103,198 @@ export function mathBuildSource( inputPaths: readonly string[] = MATH_BUILD_INPUTS, ): z.infer { assertMathCanonicalPath(root); + return { + root, + commit: mathBuildCommit(root), + submodules: [], + inputs: mathBuildInputs(root, inputPaths, sourceDirectories), + }; +} + +function mathBuildCommit(root: string): string { const provenance = z .object({ schema: z.literal('deepscientist.math.extraction.v1'), sourceCommit: z.string().regex(/^[a-f0-9]{40,64}$/u), }) .parse(readMathJson(path.join(root, 'extraction.json'))); + return provenance.sourceCommit; +} + +const browserFixtureDirectory = path.join('scripts', 'e2e'); + +function mathBuildInputPaths( + root: string, + inputPaths: readonly string[], + directories: readonly string[], + includeBrowserFixtures = false, +): string[] { const paths = new Set(inputPaths); const collect = (directory: string): void => { const absolute = path.join(root, directory); assertMathCanonicalPath(absolute); for (const entry of fs.readdirSync(absolute, { withFileTypes: true })) { const relative = path.join(directory, entry.name); + if (!includeBrowserFixtures && relative === browserFixtureDirectory) continue; if (entry.isSymbolicLink()) throw new Error('math_build_source_symlink'); if (entry.isDirectory()) collect(relative); else if (entry.isFile()) paths.add(relative); else throw new Error('math_build_source_invalid'); } }; - for (const directory of ['src', 'scripts', 'bin', 'resources', 'skills']) - if (fs.existsSync(path.join(root, directory))) collect(directory); - const inputs = [...paths].toSorted().map(relative => { + for (const directory of directories) if (fs.existsSync(path.join(root, directory))) collect(directory); + return [...paths].sort(); +} + +export function mathRuntimeInputPaths(root: string, bundledPaths: readonly string[]): string[] { + return mathBuildInputPaths(root, [...runtimeInputs, ...bundledPaths], runtimeDirectories); +} + +function mathBuildInputs( + root: string, + inputPaths: readonly string[], + directories: readonly string[], + includeBrowserFixtures = false, +): MathBuildFile[] { + return mathBuildInputPaths(root, inputPaths, directories, includeBrowserFixtures).map(relative => { const file = path.resolve(root, relative); if (!isMathPathWithin(root, file) || file === root) throw new Error('math_build_input_invalid'); return mathBuildFile(file); }); - return { root, commit: provenance.sourceCommit, submodules: [], inputs }; } -function sameBuildFile(expected: MathBuildFile, actual: MathBuildFile): boolean { - return expected.path === actual.path && expected.bytes === actual.bytes && expected.sha256 === actual.sha256; +function sameBuildBytes(expected: MathBuildFile | undefined, actual: MathBuildFile): boolean { + return expected?.bytes === actual.bytes && expected.sha256 === actual.sha256; +} + +function sameBuildFile(expected: MathBuildFile | undefined, actual: MathBuildFile): boolean { + return expected?.path === actual.path && sameBuildBytes(expected, actual); +} + +export function mathBuildAgentToolFiles(directory: string): MathBuildFile[] { + return mathBuildInputs(directory, [], ['.']); } -export function readMathBuildManifest(file: string, root: string, bundleRoot: string): MathBuildManifest { +/** Check the packaged tools or their identical copy outside the Web worker's hidden application root. */ +export function assertMathBuildAgentTools( + manifest: MathBuildManifest, + directory = path.join(manifest.bundleRoot, MATH_AGENT_TOOLS_DIRECTORY), +): void { + if (!('agentTools' in manifest)) return; + const packaged = path.join(manifest.bundleRoot, MATH_AGENT_TOOLS_DIRECTORY); + const actual = mathBuildAgentToolFiles(directory); + if ( + actual.length !== manifest.agentTools.length || + !actual.some(entry => entry.path === path.join(directory, 'math.mjs')) || + actual.some((entry, index) => { + const relative = path.relative(directory, entry.path); + return !sameBuildFile(manifest.agentTools[index], { ...entry, path: path.join(packaged, relative) }); + }) + ) + throw new Error('math_build_artifact_changed'); +} + +export function readMathBuildManifest( + file: string, + root: string, + bundleRoot: string, + scope: 'runtime' | 'source' = 'source', +): MathBuildManifest { + return verifyMathBuildManifest(file, root, bundleRoot, scope).manifest; +} + +/** Hash the same manifest bytes used for the source and artifact checks. */ +export function readMathBuildManifestDigest( + file: string, + root: string, + bundleRoot: string, + expectedDigest?: string, + scope: 'runtime' | 'source' = 'runtime', + options: { + encoding?: 'utf8'; + maxBytes?: number; + expectedTextDigest?: { digest: string; mismatch: string }; + } = {}, +): string { + const { bytes } = verifyMathBuildManifest(file, root, bundleRoot, scope, options.maxBytes); + // Workflow requests historically hashed the decoded text, which omits a UTF-8 BOM. + const textDigest = + options.encoding === 'utf8' || options.expectedTextDigest + ? mathDigest(new TextDecoder('utf-8').decode(bytes)) + : undefined; + if (options.expectedTextDigest && textDigest !== options.expectedTextDigest.digest) + throw new Error(options.expectedTextDigest.mismatch); + const digest = options.encoding === 'utf8' ? textDigest! : mathDigest(bytes); + if (expectedDigest !== undefined && expectedDigest !== digest) throw new Error('math_build_manifest_changed'); + return digest; +} + +function verifyMathBuildManifest( + file: string, + root: string, + bundleRoot: string, + scope: 'runtime' | 'source', + maxBytes?: number, +) { assertMathCanonicalPath(file); - if ((fs.lstatSync(file).mode & 0o222) !== 0) throw new Error('math_build_manifest_not_frozen'); - const parsed = schema.safeParse(readMathJson(file)); + const stat = fs.lstatSync(file, { bigint: true }); + if ((stat.mode & 0o222n) !== 0n) throw new Error('math_build_manifest_not_frozen'); + const { bytes, identity } = readMathFile(file, maxBytes); + if (identity !== mathFileIdentity(stat)) throw new Error('math_build_manifest_changed'); + const parsed = schema.safeParse(parseMathJson(bytes, 'math_build_manifest_invalid')); if (!parsed.success) throw new Error('math_build_manifest_invalid'); const manifest = parsed.data; + const bundleNames = + manifest.schema === 'deepscientist.math.build-manifest.v4' ? [MATH_SOLVER_BUNDLE] : MATH_RUNTIME_BUNDLES; if ( manifest.source.root !== root || manifest.bundleRoot !== bundleRoot || - MATH_RUNTIME_BUNDLES.some(name => !manifest.bundles.some(item => item.path === path.join(bundleRoot, name))) + bundleNames.some(name => !manifest.bundles.some(item => item.path === path.join(bundleRoot, name))) ) throw new Error('math_build_manifest_identity'); - const source = mathBuildSource(root); - if ( - manifest.source.commit !== source.commit || - manifest.source.submodules.length !== 0 || - manifest.source.inputs.length !== source.inputs.length || - manifest.source.inputs.some((entry, index) => !sameBuildFile(entry, source.inputs[index])) - ) + const expected = manifest.source; + if (expected.commit !== mathBuildCommit(root) || expected.submodules.length !== 0) throw new Error('math_build_source_changed'); + if (scope === 'source' || manifest.schema === 'deepscientist.math.build-manifest.v1') { + // v1 builds originally scanned the browser fixtures alongside runtime source. + const includeBrowserFixtures = + manifest.schema === 'deepscientist.math.build-manifest.v1' && + expected.inputs.some(entry => entry.path.startsWith(path.join(root, browserFixtureDirectory) + path.sep)); + const inputs = mathBuildInputs(root, MATH_BUILD_INPUTS, sourceDirectories, includeBrowserFixtures); + if ( + expected.inputs.length !== inputs.length || + inputs.some((entry, index) => !sameBuildFile(expected.inputs[index], entry)) + ) + throw new Error('math_build_source_changed'); + } else { + const paths = mathRuntimeInputPaths(root, manifest.runtimeInputs); + const frozen = new Map(expected.inputs.map(entry => [entry.path, entry])); + if ( + paths.length !== manifest.runtimeInputs.length || + paths.some((relative, index) => { + if (relative !== manifest.runtimeInputs[index]) return true; + const sourceFile = path.join(root, relative); + if (!isMathPathWithin(root, sourceFile) || !frozen.has(sourceFile) || !fs.existsSync(sourceFile)) return true; + return !sameBuildFile(frozen.get(sourceFile), mathBuildFile(sourceFile)); + }) + ) + throw new Error('math_build_source_changed'); + } for (const entry of manifest.bundles) if (!sameBuildFile(entry, mathBuildFile(entry.path))) throw new Error('math_build_artifact_changed'); - return manifest; + if (manifest.schema !== 'deepscientist.math.build-manifest.v1') { + for (const relative of runtimeResources) { + const built = path.join(bundleRoot, relative); + if ( + !fs.existsSync(built) || + !sameBuildBytes( + expected.inputs.find(entry => entry.path === path.join(root, relative)), + mathBuildFile(built), + ) + ) + throw new Error('math_build_artifact_changed'); + } + } + assertMathBuildAgentTools(manifest); + return { manifest, bytes }; } diff --git a/src/solver/agentTeam.ts b/src/solver/agentTeam.ts index c00c0158..9c73ff4b 100644 --- a/src/solver/agentTeam.ts +++ b/src/solver/agentTeam.ts @@ -74,7 +74,7 @@ import { import { IncrementalHelperRejection, landVerifiedHelpers } from './incrementalHelpers'; import { createSoftSlice, softSliceSettings, type SoftSliceSettings } from './softSlice'; import { portfolioRouteIdSchema, type RetiredRoute, type routeRetirementSchema } from './routeControl'; -import { researchToolRoots } from './researchToolGuide'; +import { researchLeanHealthCheck, researchToolRoots } from './researchToolGuide'; type LiveWorker = { session?: MathAgentSession; @@ -1542,17 +1542,11 @@ export class AgentResearchTeam { profile: this.input.profile, workspace: worker.worktree, proofProjectRoot: path.join(worker.worktree, state.problem.projectRelative), - leanHealthCheck: { - executable: process.execPath, - arguments: [ - path.join(this.input.root, 'out/main/check-lean.js'), - '--workspace', - path.join(worker.worktree, state.problem.projectRelative), - '--health', - '--timeout-seconds', - '0', - ], - }, + leanHealthCheck: researchLeanHealthCheck( + this.input.root, + path.join(worker.worktree, state.problem.projectRelative), + this.input.modules.M4.tools, + ), model: state.model, effort: state.effort, threadId: worker.threadId, diff --git a/src/solver/autoLibrary.ts b/src/solver/autoLibrary.ts index 858d274d..562c3533 100644 --- a/src/solver/autoLibrary.ts +++ b/src/solver/autoLibrary.ts @@ -49,7 +49,7 @@ import { parseLibraryPack, type LibraryPack, } from '../math/libraryPacks'; -import { readMathBuildManifest } from '../math/mathBuildManifest'; +import { readMathBuildManifestDigest } from '../math/mathBuildManifest'; import { acquireMathModelSlot, configuredMathModelSlots, type MathModelSlot } from '../math/mathModelSlot'; import { resolveMathematicsRuntimeEnvironment } from '../math/mathRuntimeEnvironment'; import { @@ -104,6 +104,7 @@ export const autoRequestSchema = z model: z.string().min(1).max(128), effort: z.string().min(1).max(32), executable: z.string().min(1).max(4096), + profile: z.string().min(1).max(4096).optional(), agentHarness: agentHarnessIdentitySchema.optional(), workers: z.number().int().min(1).max(MAX_RESEARCH_WORKERS), coordination: z.enum(['cooperative', 'independent']), @@ -143,13 +144,23 @@ export function prepareAutoLibraryBuild( assertWorkflowSessionSupported(input.planner, { environment: environment.id }); workflowProfileFiles(input.planner, () => null, process.env); workflowProfileFiles( - { ...input.prover, profile: input.prover.agentHarness?.profile ?? input.planner.profile }, + { ...input.prover, profile: input.prover.profile ?? input.prover.agentHarness?.profile ?? input.planner.profile }, () => null, process.env, ); const buildManifestRef = path.resolve(input.buildManifestRef), pool = path.resolve(input.pool); - readMathBuildManifest(buildManifestRef, root, path.join(root, 'out/main')); + const buildDigest = readMathBuildManifestDigest( + buildManifestRef, + root, + path.join(root, 'out/main'), + undefined, + 'source', + { + encoding: 'utf8', + maxBytes: 8_000_000, + }, + ); assertMathCanonicalPath(pool); if (isMathPathWithin(directory, pool) || isMathPathWithin(pool, directory)) throw new Error('auto_library_pool_must_be_separate'); @@ -166,7 +177,7 @@ export function prepareAutoLibraryBuild( pool, buildManifestRef, ...(effective ? { libraryBinding: effective.binding } : {}), - buildDigest: mathDigest(readMathText(buildManifestRef, 8_000_000)), + buildDigest, basePackDigest: basePack ? libraryPackDigest(basePack) : null, }); if (request.definitionTargets) { @@ -471,43 +482,51 @@ export async function runAutoLibraryBuild( throw new Error('auto_library_directory_must_be_external'); const { request, basePack } = readAutoLibraryRequest(directory), requestDigest = mathDigest(canonicalMathJson(request)); - readMathBuildManifest(request.buildManifestRef, root, path.join(root, 'out/main')); - if (mathDigest(readMathText(request.buildManifestRef, 8_000_000)) !== request.buildDigest) - throw new Error('auto_library_build_changed'); + const expectedBuild = { digest: request.buildDigest, mismatch: 'auto_library_build_changed' }; + const assertBuildCurrent = () => + readMathBuildManifestDigest(request.buildManifestRef, root, path.join(root, 'out/main'), undefined, 'source', { + expectedTextDigest: expectedBuild, + }); + assertBuildCurrent(); const env = resolveMathematicsRuntimeEnvironment(options.env ?? process.env); assertWorkflowSessionSupported(request.planner, { environment: request.environment as LeanTaskEnvironment }); workflowProfileFiles(request.planner, () => null, options.env ?? process.env); const proverBinding = () => workflowProfileFiles( - { ...request.prover, profile: request.prover.agentHarness?.profile ?? request.planner.profile }, + { + ...request.prover, + profile: request.prover.profile ?? request.prover.agentHarness?.profile ?? request.planner.profile, + }, () => null, options.env ?? process.env, ); proverBinding(); - const solver = options.solve ?? ((args: string[]) => runSolver(args, root)); - const solve: AutoLibrarySolve = async (args, purpose) => { - proverBinding(); - const code = await solver(args, purpose); - proverBinding(); - return code; - }; - const controller = new AbortController(), - externalAbort = () => controller.abort(); - options.signal?.addEventListener('abort', externalAbort, { once: true }); - if (options.signal?.aborted) controller.abort(); try { return await withMathRuntimeLease( - { lockPath: path.join(directory, 'run.lock'), flockExecutable: '/usr/bin/flock', signal: controller.signal }, - lease => build({ directory, request, requestDigest, basePack, env, solve, lease, options }), + { lockPath: path.join(directory, 'run.lock'), flockExecutable: '/usr/bin/flock', signal: options.signal }, + lease => { + const solve: AutoLibrarySolve = async (args, purpose) => { + lease.signal.throwIfAborted(); + assertBuildCurrent(); + proverBinding(); + const code = options.solve + ? await options.solve(args, purpose) + : await runSolver(args, root, undefined, lease.signal, { + expectedBuild, + leanOnly: purpose.phase !== 'prove', + }); + proverBinding(); + return code; + }; + return build({ directory, request, requestDigest, basePack, env, solve, lease, options }); + }, ); } catch (cause) { - if (controller.signal.aborted && errorText(cause) === 'math_runtime_lease_lost') { + if (options.signal?.aborted && errorText(cause) === 'math_runtime_lease_lost') { const stopped = readAutoLibraryState(directory); if (stopped?.status === 'stopped') return summarize(directory, stopped); } throw cause; - } finally { - options.signal?.removeEventListener('abort', externalAbort); } } @@ -685,7 +704,11 @@ async function build(context: { '--harness-executable', request.prover.agentHarness.executable, ] - : ['--codex', request.prover.executable]), + : [ + '--codex', + request.prover.executable, + ...(request.prover.profile ? ['--harness-profile', request.prover.profile] : []), + ]), '--max-turns', String(request.prover.maxTurns), '--max-turn-seconds', diff --git a/src/solver/continuationInput.ts b/src/solver/continuationInput.ts index d610208f..dd8816bf 100644 --- a/src/solver/continuationInput.ts +++ b/src/solver/continuationInput.ts @@ -9,6 +9,7 @@ import type { ContextSection } from './contextCompiler'; import { largestFittingPage, splitsSurrogate } from './textPage'; export const MAX_CONTINUATION_ATTACHMENT_BYTES = 16_000_000; +export const MAX_CONTINUATION_ATTACHMENTS = 32; export const MAX_CONTINUATION_TOTAL_BYTES = 64_000_000; const maxManifestBytes = 1_000_000; const digest = z.string().regex(/^[a-f0-9]{64}$/u); @@ -46,7 +47,7 @@ const inputSchema = z .object({ schema: z.literal('theorem-os.continuation-input.v1'), ...identity, - attachments: z.array(attachment).min(1).max(32), + attachments: z.array(attachment).min(1).max(MAX_CONTINUATION_ATTACHMENTS), }) .strict(); const snapshotSchema = z @@ -56,7 +57,7 @@ const snapshotSchema = z attachments: z .array(attachment.extend({ contentPath: z.string() }).strict()) .min(1) - .max(32), + .max(MAX_CONTINUATION_ATTACHMENTS), }) .strict(); diff --git a/src/solver/research.ts b/src/solver/research.ts index c7a76181..914427ac 100644 --- a/src/solver/research.ts +++ b/src/solver/research.ts @@ -60,7 +60,7 @@ import { DECLARATION_SUBMISSION_FILE } from './declarationArtifacts'; import { createSoftSlice, softSliceSettings, type SoftSliceSettings } from './softSlice'; import { materializeResearchToolHelp } from './researchToolHelp'; import { assertActiveResearchState } from './researchRetirement'; -import { researchToolRoots } from './researchToolGuide'; +import { researchLeanHealthCheck, researchToolRoots } from './researchToolGuide'; const interruptGraceMs = 10_000; const nonToolItems = new Set(['reasoning', 'agentMessage', 'userMessage', 'contextCompaction']); @@ -723,17 +723,11 @@ export async function runResearchLead(input: { : {}), ...(team ? { - leanHealthCheck: { - executable: process.execPath, - arguments: [ - path.join(input.root, 'out/main/check-lean.js'), - '--workspace', - path.join(worker.worktree, state.problem.projectRelative), - '--health', - '--timeout-seconds', - '0', - ], - }, + leanHealthCheck: researchLeanHealthCheck( + input.root, + path.join(worker.worktree, state.problem.projectRelative), + modules.M4.tools, + ), } : {}), hiddenRoots: [prepareTacticBatteryFailureCacheRoot(), ...(team?.hiddenRoots ?? [])], @@ -1139,7 +1133,7 @@ export async function runResearchLead(input: { const operation = action.operation; if (!options.includes(action.operation)) throw new Error('math_research_operation_unavailable'); emit('research_action', { operation: action.operation, reason: action.reason }); - readMathBuildManifest(input.buildFile, input.root, path.join(input.root, 'out', 'main')); + readMathBuildManifest(input.buildFile, input.root, path.join(input.root, 'out', 'main'), 'runtime'); const onStarted = (turnId: string) => { // Some headless CLIs report a native ID only after starting. Persist that exact // identity before publishing a turn; an empty ID cannot stand for a saved thread. diff --git a/src/solver/researchToolGuide.ts b/src/solver/researchToolGuide.ts index 84392735..5759d121 100644 --- a/src/solver/researchToolGuide.ts +++ b/src/solver/researchToolGuide.ts @@ -1,3 +1,4 @@ +import fs from 'node:fs'; import path from 'node:path'; import { DECLARATION_INDEX_FILE } from './declarationIndex'; import type { ContextAccess } from './modules/context'; @@ -16,6 +17,21 @@ export const researchToolRoots = (root: string, tools?: string) => [ ...(tools ? [path.dirname(path.resolve(root, tools))] : []), ]; +export function researchLeanHealthCheck(root: string, project: string, tools?: string) { + const arguments_ = ['--workspace', project, '--health', '--timeout-seconds', '0']; + if (tools && isNativeToolBundle(tools)) return { executable: tools, arguments: ['check-lean', ...arguments_] }; + + const packaged = path.join(root, 'out/main/agent-tools'); + const legacy = path.join(root, 'out/main/check-lean.js'); + const command = + tools !== undefined || fs.existsSync(packaged) + ? [tools ?? path.join(packaged, 'math.mjs'), 'check-lean'] + : fs.existsSync(legacy) + ? [legacy] + : [path.join(root, 'bin/math.ts'), 'check-lean']; + return { executable: process.execPath, arguments: [...command, ...arguments_] }; +} + export const longCommandGuidance = 'For a long calculation, record the inputs, print progress and save completed batches in .scratch/tmp. Use unbuffered output for Python (python3 -u). ' + 'With native exec_command, keep the session ID returned after a short yield_time_ms. Poll with write_stdin and empty chars. ' + diff --git a/src/solver/run.ts b/src/solver/run.ts index f7d443a2..dec7953d 100644 --- a/src/solver/run.ts +++ b/src/solver/run.ts @@ -4,7 +4,7 @@ import path from 'node:path'; import crypto from 'node:crypto'; import { VerificationCheckpointError, withVerificationCheckpoints } from './verificationCheckpoint'; import { parseRunOptions, resolveRunStrategy, resolveRunLimits, frozenRunConfiguration } from './runOptions'; -import { readMathBuildManifest } from '../math/mathBuildManifest'; +import { readMathBuildManifest, readMathBuildManifestDigest } from '../math/mathBuildManifest'; import { MathGitError } from '../math/mathGit'; import { scheduleMathTimeout } from '../math/mathTimers'; import { @@ -114,9 +114,11 @@ export async function runSolver( root: string, customModules?: RuntimeSolverModules, hostSignal?: AbortSignal, - entryPoint: 'internal' | 'cli' = 'internal', + launch: 'internal' | 'cli' | { expectedBuild: { digest: string; mismatch: string }; leanOnly: boolean } = 'internal', owner?: { drive: ResearchDriver; lockDescriptor: number; conclude: typeof concludeRun }, ): Promise { + const autoLibrary = typeof launch === 'object' ? launch : undefined; + const entryPoint = typeof launch === 'string' ? launch : 'internal'; const values = parseRunOptions(args, entryPoint); if (values.help) { console.log( @@ -265,7 +267,15 @@ export async function runSolver( } const buildFile = fs.realpathSync(required('build-manifest')); const bundleRoot = path.join(root, 'out', 'main'); - readMathBuildManifest(buildFile, root, bundleRoot); + const readBuildDigest = () => { + if (autoLibrary) + return readMathBuildManifestDigest(buildFile, root, bundleRoot, undefined, 'runtime', { + expectedTextDigest: autoLibrary.expectedBuild, + }); + readMathBuildManifest(buildFile, root, bundleRoot, 'runtime'); + return mathDigest(fs.readFileSync(buildFile)); + }; + const buildDigest = readBuildDigest(); const task = fs.readFileSync(required('task-file'), 'utf8'); const receiptFile = values['receipt-file'] || path.join(workspace, 'active-problem.json'); const problem = readSolverProblem(workspace, receiptFile); @@ -377,7 +387,7 @@ export async function runSolver( }); const identity = { taskDigest: mathDigest(task), - buildDigest: mathDigest(fs.readFileSync(buildFile)), + buildDigest, providerProfile: providerProfile?.profile, providerProfileDigest: providerProfile?.digest, environmentDigest: preparedEnvironment.environmentDigest, @@ -630,7 +640,7 @@ export async function runSolver( state.check = undefined; save(); } - if (values['startup-only']) { + if (values['startup-only'] && !autoLibrary?.leanOnly) { const connectivity = modules.M1.open === directRuntimeModules.M1.open ? await checkCodexProviderConnectivity({ env, signal, profile }) @@ -974,7 +984,7 @@ export async function runSolver( if (winner?.check.passed) { state.phase = 'evaluating'; save(); - readMathBuildManifest(buildFile, root, bundleRoot); + if (readBuildDigest() !== buildDigest) throw new Error('math_build_manifest_changed'); const evaluationStarted = Date.now(); emit('evaluation_started', { workerId: state.winningWorker ?? 'solver' }); evaluation = await evaluateSolverProof(state.problem, winner.check, env, signal, { diff --git a/tests/agentTools.test.ts b/tests/agentTools.test.ts index 833a8702..76ffef1d 100644 --- a/tests/agentTools.test.ts +++ b/tests/agentTools.test.ts @@ -24,6 +24,7 @@ const commands = [ 'search-lean', ]; const fixture = path.resolve('examples/finite/old-b1-nine-constraints.json'); +const builder = path.resolve('scripts/build-agent-tools.ts'); const native = process.env.THEOREMOS_TEST_AGENT_BINARY; const addon = process.env.THEOREMOS_TEST_PROCESS_ADDON; const nativeCommands = new Set(native ? commands : []); @@ -41,8 +42,9 @@ describe('bundled Agent commands', () => { beforeAll(() => { directory = fs.mkdtempSync(path.join(os.tmpdir(), 'theorem-os-agent-tools-')); tools = path.join(directory, 'tools'); + fs.mkdirSync(tools); const buildArgs = [ - 'scripts/build-agent-tools.ts', + builder, '--out', tools, ...(native ? ['--rust-tools', native] : []), @@ -64,6 +66,38 @@ describe('bundled Agent commands', () => { }, 90_000); afterAll(() => fs.rmSync(directory, { recursive: true, force: true })); + it('preserves files when --out names a nonempty directory', () => { + const output = path.join(directory, 'existing-output'); + fs.mkdirSync(output); + const notes = path.join(output, 'notes.txt'); + fs.writeFileSync(notes, 'Keep this file.\n'); + const built = spawnSync('bun', [builder, '--out', output], { encoding: 'utf8', timeout: 20_000 }); + expect(built.status).toBe(1); + expect(built.stderr).toContain('output must be an empty directory'); + expect(fs.readdirSync(output)).toEqual(['notes.txt']); + expect(fs.readFileSync(notes, 'utf8')).toBe('Keep this file.\n'); + }); + + it('does not publish or leave staging files behind after a compile failure', () => { + const parent = path.join(directory, 'failed-build'); + const checkout = path.join(parent, 'checkout'); + fs.mkdirSync(path.join(checkout, 'scripts'), { recursive: true }); + for (const name of ['bin', 'node_modules', 'resources', 'src']) + fs.symlinkSync(path.resolve(name), path.join(checkout, name), 'dir'); + for (const name of ['scripts/build-agent-tools.ts', 'scripts/build-math-resources.ts', 'tsconfig.json']) + fs.copyFileSync(path.resolve(name), path.join(checkout, name)); + + // Missing tool entry points cause esbuild to fail after staging the resources. + const built = spawnSync( + 'bun', + [path.join(checkout, 'scripts/build-agent-tools.ts'), '--out', path.join(parent, 'tools')], + { encoding: 'utf8', timeout: 20_000 }, + ); + expect(built.status).toBe(1); + expect(built.stderr).toContain('Could not resolve "scripts/mathematics/'); + expect(fs.readdirSync(parent)).toEqual(['checkout']); + }); + it.runIf(addon && !native)('requires the sealed process module for source-only bundles', () => { const file = path.join(tools, 'theoremos-process.node'); expect(fs.statSync(file).mode & 0o222).toBe(0); @@ -163,6 +197,7 @@ describe('bundled Agent commands', () => { 'node', [ '--permission', + ...(addon ? ['--allow-addons'] : []), `--allow-fs-read=${directory}`, `--allow-fs-write=${worktree}`, '--input-type=module', diff --git a/tests/autoLibraryCli.test.ts b/tests/autoLibraryCli.test.ts index e3e1f0e7..a9efba00 100644 --- a/tests/autoLibraryCli.test.ts +++ b/tests/autoLibraryCli.test.ts @@ -93,13 +93,13 @@ afterEach(() => { }); describe('auto-library CLI entry points', () => { - it('selects a separate portable prover while retaining the existing Codex planner', async () => { + it('selects a separate Codex prover while retaining the existing planner', async () => { const challenge = path.join(directory, 'Challenge.lean'), profile = path.join(directory, 'native-profile'), executable = path.join(directory, 'native'); fs.writeFileSync(challenge, 'theorem target : True := by sorry\n'); fs.mkdirSync(profile); - fs.writeFileSync(path.join(profile, 'settings.json'), '{}'); + fs.writeFileSync(path.join(profile, 'config.toml'), ''); fs.writeFileSync(executable, '#!/bin/sh\nexit 0\n', { mode: 0o700 }); expect( await autoLibrary([ @@ -118,7 +118,7 @@ describe('auto-library CLI entry points', () => { '--prover-model', 'fixture', '--prover-harness', - 'claude-code', + 'codex', '--prover-harness-profile', profile, '--prover-harness-executable', @@ -127,14 +127,14 @@ describe('auto-library CLI entry points', () => { ).toBe(0); const input = host.prepare.mock.calls[0][2]; expect(input.planner).not.toHaveProperty('agentHarness'); - expect(input.prover.agentHarness).toMatchObject({ id: 'claude-code', profile, executable }); + expect(input.prover).toMatchObject({ profile, agentHarness: { id: 'codex', profile, executable } }); }); - it('freezes a portable sealed planner independently from its default prover', async () => { + it('freezes a Codex planner independently from its default prover', async () => { const profile = path.join(directory, 'planner-profile'), executable = path.join(directory, 'native'); fs.mkdirSync(profile); - fs.writeFileSync(path.join(profile, 'settings.json'), '{}'); + fs.writeFileSync(path.join(profile, 'config.toml'), ''); fs.writeFileSync(executable, '#!/bin/sh\nexit 0\n', { mode: 0o700 }); const challenge = path.join(directory, 'Challenge.lean'); fs.writeFileSync(challenge, 'theorem target : True := by sorry\n'); @@ -145,7 +145,7 @@ describe('auto-library CLI entry points', () => { '--directory', path.join(directory, 'build'), '--harness', - 'claude-code', + 'codex', '--model', 'fixture', '--harness-profile', @@ -163,7 +163,7 @@ describe('auto-library CLI entry points', () => { ]), ).toBe(0); expect(host.prepare.mock.calls[0][2].planner.agentHarness).toMatchObject({ - id: 'claude-code', + id: 'codex', executable, profile, }); diff --git a/tests/autoLibraryHost.test.ts b/tests/autoLibraryHost.test.ts index e0e95f1c..3ab155dc 100644 --- a/tests/autoLibraryHost.test.ts +++ b/tests/autoLibraryHost.test.ts @@ -28,8 +28,28 @@ import { temporaryDirectory } from './helpers/files'; import { bindResearchHarness } from '../src/runtime/researchHarness'; import { prepareLibraryKnowledge } from '../src/solver/theoremKnowledgeLibrary'; import { readAuthorizedKnowledgeCatalog } from '../src/solver/theoremKnowledgeAuthorization'; +import * as leanDiagnostics from '../src/math/leanDiagnostics'; +import * as leanToolchain from '../src/math/leanToolchainReadiness'; +import * as connectivity from '../src/runtime/codexConnectivity'; +import type { MathAgentOptions } from '../src/runtime/agentSession'; -vi.mock('../src/math/mathBuildManifest', () => ({ readMathBuildManifest: vi.fn() })); +vi.mock('../src/math/mathBuildManifest', async original => ({ + ...(await original()), + readMathBuildManifest: vi.fn(), + readMathBuildManifestDigest: ( + file: string, + _root: string, + _bundles: string, + _digest?: string, + _scope?: string, + options?: { expectedTextDigest?: { digest: string; mismatch: string } }, + ) => { + const digest = mathDigest(fs.readFileSync(file)); + const expected = options?.expectedTextDigest; + if (expected && expected.digest !== digest) throw new Error(expected.mismatch); + return digest; + }, +})); let directory: string, fixture: ReturnType; const challenge = 'theorem target : True := by sorry\n'; const source = 'namespace TheoremOS.Auto.Checked\ntheorem t : True := trivial\nend TheoremOS.Auto.Checked\n'; @@ -109,7 +129,7 @@ function approve(item: AutoLibraryRecord) { hostAutoEvidence('records', mathDigest(canonicalLibraryJson(item)), item, workspace(), true); return item; } -function prepare(prover: Partial = {}) { +function prepare(prover: Partial = {}, environment = 'openai-math') { const manifest = path.join(directory, 'manifest.json'); fs.writeFileSync(manifest, '{}'); const build = path.join(directory, 'build'), @@ -118,7 +138,7 @@ function prepare(prover: Partial = {}) { challengeId: 'parent', challengeSource: challenge, task: 'Prove target.', - environment: 'openai-math', + environment, pool: path.join(directory, 'pool'), buildManifestRef: manifest, planner: { model: 'preset', effort: 'low', executable: 'unused', profile: 'unused' }, @@ -145,6 +165,36 @@ function prepare(prover: Partial = {}) { return { build, root, input, request }; } +async function planPortable(options: MathAgentOptions, afterPlan?: () => void) { + return { + threadId: 'preset', + close: async () => {}, + interrupt: async () => {}, + run: async (_message: string, _id: string, workspace: string, started: (id: string) => void) => { + started('preset-turn'); + options.onUsage?.({ totalTokens: 0 }); + const input = JSON.parse(fs.readFileSync(path.join(workspace, 'INPUT.json'), 'utf8')); + fs.writeFileSync( + path.join(workspace, 'OUTPUT.json'), + JSON.stringify({ + inputDigest: input.inputDigest, + decision: 'module', + reason: 'Disposable protocol fixture.', + name: 'Portable', + summary: 'Portable true lemma.', + sources: [], + lean: 'namespace TheoremOS.Auto.Portable\ntheorem portable : True := by sorry\nend TheoremOS.Auto.Portable\n', + target: 'target', + application: 'Apply TheoremOS.Auto.Portable.portable', + remaining: [], + }), + ); + afterPlan?.(); + return 'completed' as const; + }, + }; +} + describe('host-authorized Auto composition', () => { it('indexes an authorized Auto composition without promoting its declarations to release replay evidence', () => { const item = approve(record()), @@ -589,32 +639,7 @@ describe('Auto request and recovery', () => { fs.writeFileSync(executable, '#!/bin/sh\nexit 0\n', { mode: 0o700 }); const agentHarness = bindResearchHarness('codex', executable, profile); const { build, root } = prepare({ model: 'fixture', executable, agentHarness }); - const openSession = vi.fn(async (options: any) => ({ - threadId: 'preset', - close: async () => {}, - interrupt: async () => {}, - run: async (_message: string, _id: string, workspace: string, started: (id: string) => void) => { - started('preset-turn'); - options.onUsage({ totalTokens: 0 }); - const input = JSON.parse(fs.readFileSync(path.join(workspace, 'INPUT.json'), 'utf8')); - fs.writeFileSync( - path.join(workspace, 'OUTPUT.json'), - JSON.stringify({ - inputDigest: input.inputDigest, - decision: 'module', - reason: 'Disposable protocol fixture.', - name: 'Portable', - summary: 'Portable true lemma.', - sources: [], - lean: 'namespace TheoremOS.Auto.Portable\ntheorem portable : True := by sorry\nend TheoremOS.Auto.Portable\n', - target: 'target', - application: 'Apply TheoremOS.Auto.Portable.portable', - remaining: [], - }), - ); - return 'completed'; - }, - })); + const openSession = planPortable; const solve = vi.fn(async (args: string[]) => { expect(args).toContain('--harness'); expect(args[args.indexOf('--harness') + 1]).toBe('codex'); @@ -636,6 +661,49 @@ describe('Auto request and recovery', () => { ); }); + it('checks the statement offline and cancels the child when the parent stops during proof preparation', async () => { + vi.stubEnv('THEOREMOS_LIBRARY_HOST_CONFIG', undefined); + vi.stubEnv('DEEPSCIENTIST_MATH_ENV_FILE', path.join(directory, 'math.env')); + vi.stubEnv('DEEPSCIENTIST_MATH_RETRIEVAL_CORPUS', undefined); + const events = vi.spyOn(console, 'log').mockImplementation(() => {}); + const profile = path.join(directory, 'profile'), + executable = path.join(directory, 'unused-codex'); + fs.mkdirSync(profile); + fs.writeFileSync(path.join(profile, 'config.toml'), ''); + fs.writeFileSync(executable, '#!/bin/sh\nexit 99\n', { mode: 0o700 }); + const { build, root } = prepare({ executable, profile, prepareTimeoutSeconds: 10 }, 'standard'); + fs.mkdirSync(root); + fs.cpSync(path.resolve('skills'), path.join(root, 'skills'), { recursive: true }); + const probe = vi.spyOn(connectivity, 'checkCodexProviderConnectivity').mockResolvedValue({ status: 'unavailable' }); + vi.spyOn(leanToolchain, 'checkResolvedLeanToolchainReadiness').mockReturnValue({ status: 'ready' }); + const controller = new AbortController(); + const accepted = { exitCode: 0, timedOut: false, phases: [], stdout: '', stderr: '' }; + const prepareLean = vi + .spyOn(leanDiagnostics, 'runLeanDiagnostics') + .mockResolvedValueOnce(accepted) + .mockResolvedValueOnce(accepted) + .mockImplementationOnce(async ({ signal }) => { + controller.abort(); + signal?.throwIfAborted(); + throw new Error('fixture_solver_did_not_cancel'); + }); + + const result = await runAutoLibraryBuild(build, root, { openSession: planPortable, signal: controller.signal }); + expect(probe).not.toHaveBeenCalled(); + expect( + prepareLean.mock.calls.map(([input]) => Boolean(input.dependenciesOnly)), + JSON.stringify({ result, events: events.mock.calls }), + ).toEqual([true, false, true]); + expect(result.status).toBe('stopped'); + const [{ prove }] = JSON.parse(fs.readFileSync(path.join(build, 'state.json'), 'utf8')).modules[0].rounds; + const child = path.join(build, 'modules', '0', 'round-1', prove, 'result.json'); + expect(JSON.parse(fs.readFileSync(child, 'utf8'))).toMatchObject({ + status: 'limit_reached', + reason: 'math_preparation_stopped', + turns: 0, + }); + }); + it('supports a no-model planner run, frozen pool digests and completed recovery', async () => { const { build, root } = prepare(); const openSession = vi.fn(async (options: any) => ({ diff --git a/tests/mathProofEnvironment.test.ts b/tests/mathProofEnvironment.test.ts index ee47f0a9..6bb49591 100644 --- a/tests/mathProofEnvironment.test.ts +++ b/tests/mathProofEnvironment.test.ts @@ -306,7 +306,8 @@ it.skipIf(process.env.DEEPSCIENTIST_TEST_CODEX_SANDBOX !== '1')( // The built checker is a tool the worker is given, like the research tools a real thread reads. ...workerSandbox(project, [path.resolve('out/main')]), process.execPath, - path.resolve('out/main/check-lean.js'), + path.resolve('out/main/agent-tools/math.mjs'), + 'check-lean', '--workspace', project, '--file', diff --git a/tests/mathRetrievalCorpus.test.ts b/tests/mathRetrievalCorpus.test.ts index c506f252..21024453 100644 --- a/tests/mathRetrievalCorpus.test.ts +++ b/tests/mathRetrievalCorpus.test.ts @@ -1221,7 +1221,8 @@ describe('frozen Lean declaration lookup', () => { const cached = fs.existsSync(index) ? fs.readdirSync(index).map(name => ({ file: path.join(index, name), stat: fs.statSync(path.join(index, name)) })) : []; - if (fs.existsSync(path.resolve('out/main/search-lean.js'))) expect(cached).toHaveLength(1); + if (['out/main/agent-tools/search-lean.mjs', 'out/main/search-lean.js'].some(file => fs.existsSync(file))) + expect(cached).toHaveLength(1); const batch = spawnSync('bun', [...args, '--query', 'Order.helper'], options); expect(batch.status).toBe(0); expect(JSON.parse(batch.stdout).queries.map((query: { query: string }) => query.query)).toEqual([ diff --git a/tests/standalone.test.ts b/tests/standalone.test.ts index 804d3d10..5d8e5d35 100644 --- a/tests/standalone.test.ts +++ b/tests/standalone.test.ts @@ -6,12 +6,15 @@ import { spawnSync } from 'node:child_process'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { writeMathJsonDurable } from '../src/math/mathRuntimeIo'; import { + assertMathBuildAgentTools, mathBuildFile, mathBuildSource, readMathBuildManifest, + readMathBuildManifestDigest, MATH_BUILD_INPUTS, MATH_RUNTIME_BUNDLES, } from '../src/math/mathBuildManifest'; +import { researchLeanHealthCheck } from '../src/solver/researchToolGuide'; const roots: string[] = []; const temp = () => { @@ -99,6 +102,24 @@ describe('standalone build identity', () => { fs.writeFileSync(f.source, 'export const originalTarget = false;'); expect(() => readMathBuildManifest(f.file, f.root, f.bundleRoot)).toThrow('math_build_source_changed'); }); + it('binds the raw manifest bytes and rejects a valid replacement at the same path', () => { + const f = fixture(); + const original = fs.readFileSync(f.file); + const digest = crypto.createHash('sha256').update(original).digest('hex'); + expect(readMathBuildManifestDigest(f.file, f.root, f.bundleRoot, digest)).toBe(digest); + + const replacement = f.file + '.other'; + const changed = Buffer.concat([original, Buffer.from('\n')]); + fs.writeFileSync(replacement, changed, { mode: 0o400 }); + fs.renameSync(replacement, f.file); + expect(readMathBuildManifest(f.file, f.root, f.bundleRoot)).toEqual(f.manifest); + expect(readMathBuildManifestDigest(f.file, f.root, f.bundleRoot)).toBe( + crypto.createHash('sha256').update(changed).digest('hex'), + ); + expect(() => readMathBuildManifestDigest(f.file, f.root, f.bundleRoot, digest)).toThrow( + 'math_build_manifest_changed', + ); + }); it('rejects a renamed source even when the file count, sizes and contents stay the same', () => { const f = fixture(); readMathBuildManifest(f.file, f.root, f.bundleRoot); @@ -126,24 +147,172 @@ describe('standalone build identity', () => { fs.chmodSync(f.file, 0o400); expect(() => readMathBuildManifest(f.file, f.root, f.bundleRoot)).toThrow('math_build_manifest_invalid'); }); + function buildCheckout() { + const directory = temp(); + const root = path.join(directory, 'source'); + const state = path.join(directory, 'state'); + fs.mkdirSync(root); + for (const name of ['src', 'bin', 'resources', 'scripts', 'skills', ...MATH_BUILD_INPUTS]) + fs.cpSync(path.resolve(name), path.join(root, name), { recursive: true }); + fs.symlinkSync(fs.realpathSync('node_modules'), path.join(root, 'node_modules'), 'dir'); + const rebuild = () => + spawnSync('bun', ['scripts/build.ts', '--state-root', state], { + cwd: root, + encoding: 'utf8', + timeout: 15_000, + }); + const build = rebuild(); + expect(build.status, build.stderr).toBe(0); + const { buildManifestRef, bundleRoot, bundleCount } = JSON.parse(build.stdout) as { + buildManifestRef: string; + bundleRoot: string; + bundleCount: number; + }; + expect(bundleCount).toBe(1); + return { root, state, rebuild, buildManifestRef, bundleRoot }; + } + + it('keeps the prior bundle and manifest usable after a failed rebuild', () => { + const { root, state, rebuild, buildManifestRef, bundleRoot } = buildCheckout(); + const entry = path.join(root, 'scripts/mathematics/runMathProof.ts'); + const original = fs.readFileSync(entry); + fs.appendFileSync(entry, '\nexport const =\n'); + const failed = rebuild(); + expect(failed.stderr).toContain('Expected identifier'); + expect(failed.status).toBe(1); + fs.writeFileSync(entry, original); + expect(readMathBuildManifest(buildManifestRef, root, bundleRoot).bundleRoot).toBe(path.join(root, 'out/main')); + expect(fs.readdirSync(path.join(state, 'builds'))).toEqual([path.basename(path.dirname(buildManifestRef))]); + + const rebuilt = rebuild(); + expect(rebuilt.status, rebuilt.stderr).toBe(0); + const next = JSON.parse(rebuilt.stdout); + expect(next.buildManifestRef).not.toBe(buildManifestRef); + expect(readMathBuildManifest(next.buildManifestRef, root, bundleRoot).bundles).toEqual( + readMathBuildManifest(buildManifestRef, root, bundleRoot).bundles, + ); + }); + + it('freezes proof bundles and agent tools while keeping unrelated edits out of the runtime scope', () => { + const { root, buildManifestRef, bundleRoot } = buildCheckout(); + const verify = (scope: 'runtime' | 'source' = 'runtime') => + readMathBuildManifest(buildManifestRef, root, bundleRoot, scope); + const manifest = verify('source'); + expect(manifest.schema).toBe('deepscientist.math.build-manifest.v4'); + if (manifest.schema !== 'deepscientist.math.build-manifest.v4') throw new Error('wrong build schema'); + expect(fs.readdirSync(bundleRoot).sort()).toEqual(['agent-tools', 'math-solver.js', 'resources']); + + const hosted = path.join(temp(), 'agent-tools'); + const tools = path.join(bundleRoot, 'agent-tools'); + fs.cpSync(tools, hosted, { recursive: true }); + assertMathBuildAgentTools(manifest, hosted); + fs.appendFileSync(path.join(hosted, 'declarations.mjs'), '\n'); + expect(() => assertMathBuildAgentTools(manifest, hosted)).toThrow('math_build_artifact_changed'); + + fs.unlinkSync(path.join(root, 'node_modules')); + const help = spawnSync('bun', ['bin/math.ts', 'declarations', '--help'], { + cwd: root, + encoding: 'utf8', + timeout: 10_000, + }); + expect(help.status, help.stderr).toBe(0); + expect(help.stdout).toContain('Usage: theorem-os declarations'); + expect(verify().bundleRoot).toBe(bundleRoot); + + const legacy = temp(); + const v2File = path.join(legacy, 'v2.json'); + const v3File = path.join(legacy, 'v3.json'); + const bundles = MATH_RUNTIME_BUNDLES.map(name => { + const bundle = path.join(bundleRoot, name); + if (!fs.existsSync(bundle)) fs.writeFileSync(bundle, '// legacy tool fixture'); + return mathBuildFile(bundle); + }); + const { agentTools: _agentTools, ...v2 } = manifest; + writeMathJsonDurable(v2File, { ...v2, bundles, schema: 'deepscientist.math.build-manifest.v2' }, 0o400); + writeMathJsonDurable(v3File, { ...manifest, bundles, schema: 'deepscientist.math.build-manifest.v3' }, 0o400); + expect(readMathBuildManifest(v3File, root, bundleRoot).schema).toBe('deepscientist.math.build-manifest.v3'); + const declarations = path.join(tools, 'declarations.mjs'); + const declarationsBytes = fs.readFileSync(declarations); + fs.unlinkSync(declarations); + expect(() => verify()).toThrow('math_build_artifact_changed'); + expect(() => readMathBuildManifest(v3File, root, bundleRoot)).toThrow('math_build_artifact_changed'); + expect(readMathBuildManifest(v2File, root, bundleRoot).schema).toBe('deepscientist.math.build-manifest.v2'); + fs.writeFileSync(declarations, declarationsBytes); + + fs.writeFileSync(path.join(root, 'scripts', 'standalone-report.ts'), '// A local reporting script'); + expect(verify().bundleRoot).toBe(bundleRoot); + expect(() => readMathBuildManifest(buildManifestRef, root, bundleRoot)).toThrow('math_build_source_changed'); + + const resource = 'resources/theorem-os-library/search-data.json'; + const copy = path.join(bundleRoot, resource); + const contents = fs.readFileSync(copy); + fs.appendFileSync(copy, '\n'); + expect(verify).toThrow('math_build_artifact_changed'); + fs.writeFileSync(copy, contents); + for (const relative of [ + resource, + 'src/solver/run.ts', + 'skills/theoremos-research/references/lean.md', + 'scripts/mathematics/library.ts', + 'src/solver/declarationSearch.ts', + ]) { + const file = path.join(root, relative); + const contents = fs.readFileSync(file); + fs.appendFileSync(file, '\n'); + expect(verify, relative).toThrow('math_build_source_changed'); + fs.writeFileSync(file, contents); + } + }); + + it('runs the local and isolated Lean environment probes through the same packaged checker', () => { + const { root, bundleRoot } = buildCheckout(); + const project = path.join(temp(), 'lean project'); + fs.mkdirSync(project); + const projection = path.join(project, 'environment.json'); + fs.writeFileSync(projection, '{}'); + const hosted = path.join(temp(), 'agent-tools'); + fs.cpSync(path.join(bundleRoot, 'agent-tools'), hosted, { recursive: true }); + const local = researchLeanHealthCheck(root, project); + const isolated = researchLeanHealthCheck(root, project, path.join(hosted, 'math.mjs')); + for (const { arguments: args } of [local, isolated]) { + const result = spawnSync('bun', args, { + cwd: hosted, + env: { ...process.env, DEEPSCIENTIST_MATH_ENV_FILE: projection }, + encoding: 'utf8', + timeout: 10_000, + }); + expect(result.stderr).toBe(''); + expect(result.status).toBe(1); + expect(JSON.parse(result.stdout)).toMatchObject({ + schema: 'theoremos.lean-environment-health.v1', + projectRoot: project, + status: 'infrastructure-error', + error: { stage: 'environment' }, + }); + } + expect(local.arguments[0]).toBe(path.join(bundleRoot, 'agent-tools/math.mjs')); + }); }); describe('standalone CLI', () => { const cli = path.resolve('bin/math.ts'); - it('runs the packaged Lean diagnostic when the shell has no source tree or dependencies', () => { - const checkout = temp(); - const entry = path.join(checkout, 'bin/math.ts'); - const bundle = path.join(checkout, 'out/main/check-lean.js'); - fs.mkdirSync(path.dirname(entry)); - fs.mkdirSync(path.dirname(bundle), { recursive: true }); - fs.copyFileSync(cli, entry); - fs.writeFileSync(bundle, 'console.log(JSON.stringify(process.argv.slice(2))); process.exitCode = 1;'); - const args = ['--file', 'folder with spaces/Submission.lean']; - const result = spawnSync('bun', [entry, 'check-lean', ...args], { cwd: checkout, encoding: 'utf8' }); - expect(result.stderr).toBe(''); - expect(result.status).toBe(1); - expect(JSON.parse(result.stdout)).toEqual(args); - }); + it.each(['out/main/agent-tools/check-lean.mjs', 'out/main/check-lean.js'])( + 'runs the packaged Lean diagnostic at %s without a source tree or dependencies', + bundlePath => { + const checkout = temp(); + const entry = path.join(checkout, 'bin/math.ts'); + const bundle = path.join(checkout, bundlePath); + fs.mkdirSync(path.dirname(entry)); + fs.mkdirSync(path.dirname(bundle), { recursive: true }); + fs.copyFileSync(cli, entry); + fs.writeFileSync(bundle, 'console.log(JSON.stringify(process.argv.slice(2))); process.exitCode = 1;'); + const args = ['--file', 'folder with spaces/Submission.lean']; + const result = spawnSync('bun', [entry, 'check-lean', ...args], { cwd: checkout, encoding: 'utf8' }); + expect(result.stderr).toBe(''); + expect(result.status).toBe(1); + expect(JSON.parse(result.stdout)).toEqual(args); + }, + ); it('shows run help before building but directs proof runs to build the frozen bundle', () => { const checkout = temp(); const entry = path.join(checkout, 'bin/math.ts'); @@ -171,7 +340,7 @@ describe('standalone CLI', () => { const help = spawnSync('bun', [cli, '--help'], { encoding: 'utf8', timeout: 10_000, maxBuffer: 16_384 }); expect(help.status).toBe(0); expect(help.stdout).toContain('bootstrap-imo'); - for (const command of ['doctor', 'example', 'component']) { + for (const command of ['doctor', 'example', 'formalize']) { expect(help.stdout).toContain(command); const commandHelp = spawnSync('bun', [cli, command, '--help'], { encoding: 'utf8', diff --git a/tests/webAgentActions.test.ts b/tests/webAgentActions.test.ts index bb2c3149..c6018208 100644 --- a/tests/webAgentActions.test.ts +++ b/tests/webAgentActions.test.ts @@ -13,6 +13,7 @@ import type { SolverProblem } from '../src/solver/problem'; import type { SolverRunState } from '../src/solver/archive'; import { canonicalMathJson, mathDigest } from '../src/math/mathRuntimeIo'; import { writeWorkerProject } from '../src/solver/workerProject'; +import { researchLeanHealthCheck } from '../src/solver/researchToolGuide'; import { temporaryDirectory } from './helpers/files'; const { opened, turns } = vi.hoisted(() => ({ @@ -1087,13 +1088,16 @@ describe('Agent actions as the run owner sees them', () => { void modules.M1.open({ workspace: own, hiddenRoots: [hostCache], - leanHealthCheck: { executable: 'bun', arguments: ['checkLean.ts', '--health'] }, + leanHealthCheck: researchLeanHealthCheck(app, own, modules.M4.tools), environment: { DEEPSCIENTIST_MATH_WORKER_ID: 'engineer' }, } as unknown as MathAgentOptions); expect(opened[0]!.leanHealthCheck).toEqual( native - ? { executable: tools, arguments: ['check-lean', '--health'] } - : { executable: 'bun', arguments: [tools, 'check-lean', '--health'] }, + ? { executable: tools, arguments: ['check-lean', '--workspace', own, '--health', '--timeout-seconds', '0'] } + : { + executable: process.execPath, + arguments: [tools, 'check-lean', '--workspace', own, '--health', '--timeout-seconds', '0'], + }, ); expect(opened[0]!.hiddenRoots).toEqual([hostCache, app, builds]); opened[0]!.onItem!('completed', { diff --git a/tests/webLibraryResearch.test.ts b/tests/webLibraryResearch.test.ts index a65e9b9c..6ccd009d 100644 --- a/tests/webLibraryResearch.test.ts +++ b/tests/webLibraryResearch.test.ts @@ -11,7 +11,11 @@ import { formalizationDigest, readFormalizationArtifact } from '../src/math/form import { LIBRARY_PACK_SCHEMA, type LibraryPack } from '../src/math/libraryPacks'; import { mathDigest, readMathJson, readMathText, writeMathJsonDurable } from '../src/math/mathRuntimeIo'; import { writeSolverRunState } from '../src/solver/archive'; -import { readContinuationInput } from '../src/solver/continuationInput'; +import { + MAX_CONTINUATION_ATTACHMENT_BYTES, + MAX_CONTINUATION_TOTAL_BYTES, + readContinuationInput, +} from '../src/solver/continuationInput'; import { writeLibraryCatalog } from '../src/solver/libraryCatalog'; import { publishNativeApprovalPlan } from '../src/solver/planApproval'; import { git, readSolverProblem } from '../src/solver/problem'; @@ -457,9 +461,10 @@ describe('Web library research supervision without provider calls', () => { const f = fixture(), original = readSolverProblem(f.seed.workspaceRoot, f.seed.activeProblemPath); const taskDigest = mathDigest(readMathText(f.seed.taskFile)); - const references = Array.from( - { length: 32 }, - (_, index) => `Original reference ${index}: preserve this distinct body [reference-${index}].`, + const references = Array.from({ length: 32 }, (_, index) => + index === 0 + ? 'A'.repeat(MAX_CONTINUATION_ATTACHMENT_BYTES) + : `Original reference ${index}: preserve this distinct body [reference-${index}].`, ); const continuationFile = path.join(f.directory, 'full-continuation.json'); writeMathJsonDurable(continuationFile, { @@ -512,6 +517,55 @@ describe('Web library research supervision without provider calls', () => { expect(result.raw).toMatchObject({ status: 'incomplete' }); }); + it('starts the next library round with the original material when newly collected notes exceed the total byte limit', async () => { + const f = fixture(); + const problem = readSolverProblem(f.seed.workspaceRoot, f.seed.activeProblemPath); + const taskDigest = mathDigest(readMathText(f.seed.taskFile)); + const continuationFile = path.join(f.directory, 'full-continuation.json'); + const attachments = ['A', 'B', 'C', 'D'].map((letter, index) => { + const text = letter.repeat(MAX_CONTINUATION_ATTACHMENT_BYTES - 1_000); + const file = `reference-${index}.txt`; + fs.writeFileSync(path.join(f.directory, file), text); + return { + id: `reference-${index}`, + kind: 'reference', + path: file, + sha256: mathDigest(text), + bytes: Buffer.byteLength(text), + provenance: { source: `Reference ${index}`, evidence: 'unverified' }, + }; + }); + writeMathJsonDurable(continuationFile, { + schema: 'theorem-os.continuation-input.v1', + taskDigest, + problemReceiptDigest: problem.receiptDigest, + attachments, + }); + const run = vi.fn(async (round: WebLibraryRound) => { + const saved = finishRound(f, round, round.round === 0 ? ['Research.desired'] : undefined); + if (round.round === 0) { + fs.writeFileSync(path.join(saved.state.worktree, 'RESEARCH.md'), 'A long research note.\n'.repeat(300)); + return; + } + const continued = readContinuationInput(round.continuationFile!, { + taskDigest, + problemReceiptDigest: saved.problem.receiptDigest, + }); + expect(continued.manifest.attachments).toEqual( + expect.arrayContaining( + attachments.map(({ sha256, bytes, provenance }) => expect.objectContaining({ sha256, bytes, provenance })), + ), + ); + expect(continued.manifest.attachments.map(item => item.kind)).toContain('proof-source'); + expect(continued.manifest.attachments.reduce((total, item) => total + item.bytes, 0)).toBeLessThanOrEqual( + MAX_CONTINUATION_TOTAL_BYTES, + ); + }); + const result = await runWebLibraryResearch({ ...f, continuationFile, run }); + expect(run).toHaveBeenCalledTimes(2); + expect(result.raw.status).toBe('incomplete'); + }); + it.each([ ['turns', { maxTurns: 2 }, { turns: 2 }, 'math_turn_limit_reached'], ['time', { maxRunSeconds: 2 }, { solveWallMs: 2000 }, 'math_run_stopped'],