From 3a8be43cb8e0e1c1314c12193bf4b1059401638a Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Sat, 5 Dec 2026 03:58:29 +0800 Subject: [PATCH 1/2] Simplify the TypeScript harness and preserve resumable runs --- apps/web/auth.ts | 24 +- apps/web/community.ts | 430 +++++++----------- apps/web/explain.ts | 3 - apps/web/explanations.ts | 6 - apps/web/formalizations.ts | 9 - apps/web/jobs.ts | 140 ++---- apps/web/keyVault.ts | 13 - apps/web/libraryResearch.ts | 56 ++- apps/web/moduleRegistry.ts | 23 +- apps/web/nativeWeb.ts | 82 ---- apps/web/operations.ts | 2 - apps/web/paperDrafts.ts | 3 - apps/web/precheck.ts | 5 - apps/web/problemDraftSubmission.ts | 12 +- apps/web/researchMode.ts | 3 +- apps/web/server.ts | 360 ++------------- apps/web/staticFiles.ts | 17 - apps/web/storage.ts | 8 - apps/web/worker.ts | 92 ++-- bin/math-help.txt | 1 - bin/math.ts | 1 - docs/usage.md | 5 +- docs/web-workbench.md | 2 +- package.json | 7 - scripts/build-agent-tools.ts | 2 + scripts/mathematics/autoLibrary.ts | 18 +- scripts/mathematics/autoLibraryHostReplay.ts | 2 +- .../mathematics/continuationSeedCommand.ts | 7 +- scripts/mathematics/planCommand.ts | 63 --- scripts/mathematics/planValidate.ts | 3 - scripts/mathematics/runMathProof.ts | 2 +- src/math/mathBuildManifest.ts | 15 + src/solver/autoLibrary.ts | 37 +- src/solver/continuationSeed.ts | 1 + src/solver/modules/organization.ts | 16 - src/solver/modules/policy.ts | 5 + src/solver/planTool.ts | 123 ----- src/solver/run.ts | 84 ++-- src/solver/singleContinuationSeed.ts | 13 +- tests/agentTools.test.ts | 1 - tests/autoLibraryCli.test.ts | 10 + tests/autoLibraryHost.test.ts | 33 ++ tests/moduleExperiment.test.ts | 12 +- tests/singleContinuationSeed.test.ts | 4 +- tests/skillSolver.test.ts | 105 +++++ tests/solver.test.ts | 4 + tests/solverAtomicPlanApply.test.ts | 119 ----- tests/standalone.test.ts | 61 ++- tests/webArtifact.test.ts | 106 ++--- tests/webAuth.test.ts | 49 ++ tests/webCommunity.test.ts | 222 ++------- tests/webContinuation.test.ts | 19 +- tests/webJobs.test.ts | 10 + tests/webKnowledgeApi.test.ts | 7 +- tests/webLibraryNative.test.ts | 7 +- tests/webLibraryResearch.test.ts | 72 +++ tests/webPersistence.test.ts | 15 +- tests/webResearchApi.test.ts | 32 +- tests/webServer.test.ts | 35 +- 59 files changed, 1002 insertions(+), 1616 deletions(-) delete mode 100644 apps/web/nativeWeb.ts delete mode 100644 scripts/mathematics/planCommand.ts delete mode 100644 scripts/mathematics/planValidate.ts delete mode 100644 src/solver/planTool.ts delete mode 100644 tests/solverAtomicPlanApply.test.ts diff --git a/apps/web/auth.ts b/apps/web/auth.ts index 0fc68be3..f49a3b60 100644 --- a/apps/web/auth.ts +++ b/apps/web/auth.ts @@ -145,7 +145,6 @@ export class WebAuth { private readonly storage: WebStorage, private readonly mailer: WebMailer = smtpMailer(config), private readonly answer: () => string = () => String(crypto.randomInt(0, 100_000)).padStart(5, '0'), - private readonly writer?: (message: object) => WebAccount, ) {} /** Sliding-window counter; returns false once `max` events already fall inside `windowMs`. */ @@ -215,17 +214,13 @@ export class WebAuth { const version = this.checkTerms(body, account); return this.recordTerms(account, version); } - invalidateLoginCode(login: string) { + private invalidateLoginCode(login: string) { this.codes.delete(login); for (const delivery of this.sending) if (delivery.email === login) this.sending.delete(delivery); } /** Suspension keeps records for restoration, blocks both login methods and invalidates admission on the next request. */ setSuspended(value: unknown, suspended: boolean): WebAccount { const login = normalizeLogin(value); - if (this.writer) { - if (suspended) this.invalidateLoginCode(login); - return this.writer({ op: 'account', action: 'suspend', login, data: { suspended } }); - } const account = this.getAccount(login); if (!account) throw new WebAuthError(404, '账号不存在。'); if (this.isAdmin(login) && suspended) throw new WebAuthError(400, '管理员账号不能暂停。'); @@ -275,7 +270,6 @@ export class WebAuth { this.fileLines().filter(line => line.replace(/#.*/u, '').trim().toLowerCase() !== email), ); this.invalidateLoginCode(email); - this.writer?.({ op: 'invalidateCode', login: email }); } allowlistWritable(): boolean { return Boolean(this.config.allowlistFile); @@ -339,7 +333,7 @@ export class WebAuth { return { email, expiresInSeconds: codeTtlMs / 1000, resendAfterSeconds: resendAfterMs / 1000 }; } - sendLoginCode(email: string, code: string) { + private sendLoginCode(email: string, code: string) { return this.mailer({ to: email, subject: `TheoremOS 登录验证码 ${code}`, @@ -527,15 +521,6 @@ export class WebAuth { /** Stamps a milestone the first time it happens; later runs leave the first time unchanged. */ markMilestone(accountId: string, milestone: WebMilestone, at = new Date().toISOString()) { const account = this.listAccounts().find(item => item.id === accountId); - if (account && this.writer) { - this.writer({ - op: 'account', - action: 'milestone', - login: accountLogin(account), - data: { id: accountId, field: milestone, at }, - }); - return; - } if (account && !account[milestone]) this.storage.saveRecord(this.accountPath(accountLogin(account)), { ...account, [milestone]: at }); } @@ -557,11 +542,6 @@ export class WebAuth { await this.mailer({ to, ...message }); } deleteAccount(login: string) { - if (this.writer) { - this.writer({ op: 'account', action: 'delete', login, data: {} }); - this.codes.delete(login); - return; - } // Keep the account retryable if credential deletion fails; a recreated account must never inherit its password. this.storage.deleteRecord(this.passwordPath(login)); this.storage.deleteRecord(this.accountPath(login)); diff --git a/apps/web/community.ts b/apps/web/community.ts index db1a5308..7a1305c6 100644 --- a/apps/web/community.ts +++ b/apps/web/community.ts @@ -6,7 +6,6 @@ import { inspectScopedLeanDeclarations } from '../../src/math/leanSource'; import { mathConstructionImports } from '../../src/math/mathConstructionSources'; import { leanDiagnostics, type WebPrecheckRunner } from './precheck'; import { WebStorage, WebStorageError } from './storage'; -import { nativeWeb } from './nativeWeb'; import type { WebEnvironment } from './shared'; /** @@ -155,64 +154,15 @@ export class WebCommunity { constructor( private readonly storage: WebStorage, private readonly runner?: WebPrecheckRunner, - private readonly options: { concurrency?: number; now?: () => number; externalWorker?: boolean } = {}, + private readonly options: { concurrency?: number; now?: () => number } = {}, ) { - if (options.externalWorker) return; // A restart re-checks what was waiting; a check cut off mid-run is simply run again. - this.write(() => { - const root = this.storage.root, - backend = root && nativeWeb(); - if (root && backend) { - this.queue.length = 0; - for (const id of backend.pendingCommunitySubmissions(root)) this.queue.push(id); - } else { - for (const file of this.storage.listRecords(['community', 'submissions'])) { - const item = this.storage.getRecord(['community', 'submissions', file]); - if (item && (item.status === 'queued' || item.status === 'checking')) this.queue.push(item.id); - } - this.queue.sort(); - } - }); - this.pump(); - } - /** Read the current records after the HTTP layer has authenticated the actor. */ - readPersistedRoute(path: string, actor?: CommunityActor) { - if (!this.storage.root) return; - return nativeWeb()?.readCommunity({ - root: this.storage.root, - path, - now: this.now(), - ...(actor && { actor: actor.key }), - admin: Boolean(actor?.admin), - checker: Boolean(this.runner), - locale: Intl.Collator().resolvedOptions().locale, - limits: communityLimits, - }); - } - private writing = false; - /** Hold the same record lock as the Rust listener only during synchronous commits. */ - private write(commit: () => T): T { - if (!this.storage.root || this.writing) return commit(); - const backend = nativeWeb(); - if (!backend) return commit(); - const guard = new backend.CommunityWriteLock(this.storage.root); - this.writing = true; - try { - const recovered = backend.recoverCommunityAdmission(this.storage.root); - if ( - !this.options.externalWorker && - recovered && - !this.checking.has(recovered) && - !this.queue.includes(recovered) - ) { - this.queue.push(recovered); - queueMicrotask(() => this.pump()); - } - return commit(); - } finally { - this.writing = false; - guard.release(); + for (const file of this.storage.listRecords(['community', 'submissions'])) { + const item = this.storage.getRecord(['community', 'submissions', file]); + if (item && (item.status === 'queued' || item.status === 'checking')) this.queue.push(item.id); } + this.queue.sort(); + this.pump(); } private now() { return this.options.now?.() ?? Date.now(); @@ -414,47 +364,41 @@ export class WebCommunity { }; } setProfile(actor: CommunityActor, raw: unknown) { - return this.write(() => { - const name = parse(z.object({ handle }).strict(), raw, '名称需为 2–24 个字母、数字、下划线或连字符。').handle; - const previous = this.profile(actor.key), - slot = (value: string) => ['community', 'handles', `${mathDigest(value.normalize('NFKC').toLowerCase())}.json`]; - if (previous?.handle === name) return this.me(actor); - if (!this.storage.createRecord(slot(name), { owner: actor.key })) { - if (this.storage.getRecord<{ owner: string }>(slot(name))?.owner !== actor.key) fail(409, '这个名称已被使用。'); - } - if (previous && slot(previous.handle)[2] !== slot(name)[2]) this.storage.deleteRecord(slot(previous.handle)); - this.storage.saveRecord(['community', 'profiles', `${actor.key}.json`], { - ...previous, - handle: name, - createdAt: previous?.createdAt ?? this.iso(), - } satisfies Profile); - return this.me(actor); - }); + const name = parse(z.object({ handle }).strict(), raw, '名称需为 2–24 个字母、数字、下划线或连字符。').handle; + const previous = this.profile(actor.key), + slot = (value: string) => ['community', 'handles', `${mathDigest(value.normalize('NFKC').toLowerCase())}.json`]; + if (previous?.handle === name) return this.me(actor); + if (!this.storage.createRecord(slot(name), { owner: actor.key })) { + if (this.storage.getRecord<{ owner: string }>(slot(name))?.owner !== actor.key) fail(409, '这个名称已被使用。'); + } + if (previous && slot(previous.handle)[2] !== slot(name)[2]) this.storage.deleteRecord(slot(previous.handle)); + this.storage.saveRecord(['community', 'profiles', `${actor.key}.json`], { + ...previous, + handle: name, + createdAt: previous?.createdAt ?? this.iso(), + } satisfies Profile); + return this.me(actor); } /** A personal agent token, shown once. Only its digest is stored; issuing a new one revokes the previous. */ issueToken(actor: CommunityActor) { - return this.write(() => { - const profile = this.requireProfile(actor), - token = `tosc_${crypto.randomBytes(32).toString('hex')}`, - digest = mathDigest(token); - if (profile.tokenDigest) this.storage.deleteRecord(['community', 'tokens', `${profile.tokenDigest}.json`]); - this.storage.saveRecord(['community', 'tokens', `${digest}.json`], { owner: actor.key }); - this.storage.saveRecord(['community', 'profiles', `${actor.key}.json`], { - ...profile, - tokenDigest: digest, - tokenCreatedAt: this.iso(), - } satisfies Profile); - return { token }; - }); + const profile = this.requireProfile(actor), + token = `tosc_${crypto.randomBytes(32).toString('hex')}`, + digest = mathDigest(token); + if (profile.tokenDigest) this.storage.deleteRecord(['community', 'tokens', `${profile.tokenDigest}.json`]); + this.storage.saveRecord(['community', 'tokens', `${digest}.json`], { owner: actor.key }); + this.storage.saveRecord(['community', 'profiles', `${actor.key}.json`], { + ...profile, + tokenDigest: digest, + tokenCreatedAt: this.iso(), + } satisfies Profile); + return { token }; } revokeToken(actor: CommunityActor) { - return this.write(() => { - const profile = this.requireProfile(actor); - if (profile.tokenDigest) this.storage.deleteRecord(['community', 'tokens', `${profile.tokenDigest}.json`]); - const { tokenDigest: _digest, tokenCreatedAt: _created, ...rest } = profile; - this.storage.saveRecord(['community', 'profiles', `${actor.key}.json`], rest satisfies Profile); - return this.me(actor); - }); + const profile = this.requireProfile(actor); + if (profile.tokenDigest) this.storage.deleteRecord(['community', 'tokens', `${profile.tokenDigest}.json`]); + const { tokenDigest: _digest, tokenCreatedAt: _created, ...rest } = profile; + this.storage.saveRecord(['community', 'profiles', `${actor.key}.json`], rest satisfies Profile); + return this.me(actor); } actorForToken(token: string): CommunityActor | undefined { if (!communityTokenPattern.test(token)) return undefined; @@ -463,7 +407,7 @@ export class WebCommunity { return saved && this.profile(saved.owner)?.tokenDigest === digest ? { key: saved.owner } : undefined; } /** The checker only sees the frozen task source. Publication and account state belong to the caller. */ - async reviewTask(id: string, environment: WebEnvironment, prelude: string, statement: string) { + private async reviewTask(id: string, environment: WebEnvironment, prelude: string, statement: string) { for (const part of [prelude, statement]) { const reason = communityLeanGuard(part, { allowedImports: () => false, allowNamespace: 'task' }) ?? @@ -488,25 +432,15 @@ export class WebCommunity { } return built; } - reviewSubmission(task: Pick, source: string) { - if (!this.runner) fail(503, '证明校验服务暂不可用。'); - const reason = communitySubmissionReason(task, source); - if (reason) fail(400, reason); - } /** Publishing compiles the frozen module once, so a task that cannot even state its goal never opens. */ async createTask(actor: CommunityActor, raw: unknown) { if (!actor.admin) fail(403, '只有管理员可以发布社区题目。'); const input = parse(createTaskInput, raw, '题目字段无效。'); - const root = this.storage.root, - backend = root && nativeWeb(); - const id = - root && backend - ? this.write(() => backend.nextCommunityTask(root)) - : `T${ - this.storage - .listRecords(['community', 'tasks']) - .reduce((max, id) => (taskId.safeParse(id).success ? Math.max(max, Number(id.slice(1))) : max), 0) + 1 - }`; + const id = `T${ + this.storage + .listRecords(['community', 'tasks']) + .reduce((max, id) => (taskId.safeParse(id).success ? Math.max(max, Number(id.slice(1))) : max), 0) + 1 + }`; const built = await this.reviewTask(id, input.environment, input.prelude, input.statement); const task: CommunityTask = { id, @@ -522,135 +456,101 @@ export class WebCommunity { tags: input.tags, submissions: 0, }; - return this.write(() => { - if (root && backend) { - const result = backend.publishCommunityTask(root, Boolean(actor.admin), task, this.activityFile()); - if ('error' in result) fail(result.status, result.error); - } else { - if (!this.storage.createRecord(this.taskPath(id), task)) fail(409, '题目编号冲突,请重试。'); - this.log({ kind: 'published', taskId: id }); - } - return { task: this.publicTask(task) }; - }); + if (!this.storage.createRecord(this.taskPath(id), task)) fail(409, '题目编号冲突,请重试。'); + this.log({ kind: 'published', taskId: id }); + return { task: this.publicTask(task) }; } withdrawTask(actor: CommunityActor, id: string) { - return this.write(() => { - if (!actor.admin) fail(403, '只有管理员可以撤下社区题目。'); - const task = this.readTask(id); - if (task.status !== 'open') fail(409, '只能撤下仍在开放的题目。'); - this.storage.saveRecord(this.taskPath(id), { ...task, status: 'withdrawn' } satisfies CommunityTask); - return { ok: true }; - }); + if (!actor.admin) fail(403, '只有管理员可以撤下社区题目。'); + const task = this.readTask(id); + if (task.status !== 'open') fail(409, '只能撤下仍在开放的题目。'); + this.storage.saveRecord(this.taskPath(id), { ...task, status: 'withdrawn' } satisfies CommunityTask); + return { ok: true }; } /** Claims are not exclusive: they tell others who is working, expire on their own and can be renewed. */ claim(actor: CommunityActor, id: string) { - return this.write(() => { - this.requireProfile(actor); - const task = this.readTask(id); - if (task.status !== 'open') fail(409, '这道题已经关闭。'); - const held = this.tasks().filter( - item => item.id !== id && this.claims(item.id).some(claim => claim.owner === actor.key), - ).length; - if (held >= communityLimits.claimsPerPerson) - fail(429, `最多同时认领 ${communityLimits.claimsPerPerson} 道题,请先放弃或完成一道。`); - const path = ['community', 'tasks', id, 'claims', `${actor.key}.json`], - renewed = this.storage.getRecord(path); - const claim: Claim = { - owner: actor.key, - claimedAt: renewed && Date.parse(renewed.expiresAt) > this.now() ? renewed.claimedAt : this.iso(), - expiresAt: new Date(this.now() + communityLimits.claimHours * 3_600_000).toISOString(), - }; - this.storage.saveRecord(path, claim); - if (!renewed || Date.parse(renewed.expiresAt) <= this.now()) - this.log({ kind: 'claimed', owner: actor.key, taskId: id }); - return this.task(id); - }); + this.requireProfile(actor); + const task = this.readTask(id); + if (task.status !== 'open') fail(409, '这道题已经关闭。'); + const held = this.tasks().filter( + item => item.id !== id && this.claims(item.id).some(claim => claim.owner === actor.key), + ).length; + if (held >= communityLimits.claimsPerPerson) + fail(429, `最多同时认领 ${communityLimits.claimsPerPerson} 道题,请先放弃或完成一道。`); + const path = ['community', 'tasks', id, 'claims', `${actor.key}.json`], + renewed = this.storage.getRecord(path); + const claim: Claim = { + owner: actor.key, + claimedAt: renewed && Date.parse(renewed.expiresAt) > this.now() ? renewed.claimedAt : this.iso(), + expiresAt: new Date(this.now() + communityLimits.claimHours * 3_600_000).toISOString(), + }; + this.storage.saveRecord(path, claim); + if (!renewed || Date.parse(renewed.expiresAt) <= this.now()) + this.log({ kind: 'claimed', owner: actor.key, taskId: id }); + return this.task(id); } release(actor: CommunityActor, id: string) { - return this.write(() => { - this.readTask(id); - const path = ['community', 'tasks', id, 'claims', `${actor.key}.json`]; - if (this.storage.getRecord(path)) { - this.storage.deleteRecord(path); - this.log({ kind: 'released', owner: actor.key, taskId: id }); - } - return this.task(id); - }); + this.readTask(id); + const path = ['community', 'tasks', id, 'claims', `${actor.key}.json`]; + if (this.storage.getRecord(path)) { + this.storage.deleteRecord(path); + this.log({ kind: 'released', owner: actor.key, taskId: id }); + } + return this.task(id); } submit(actor: CommunityActor, raw: unknown) { - const id = this.write(() => { - this.requireProfile(actor); - if (!this.runner) fail(503, '证明校验服务暂不可用。'); - const input = parse(submitInput, raw, '提交字段无效。'), - task = this.readTask(input.taskId); - if (task.status !== 'open') fail(409, task.status === 'solved' ? '这道题已经有人先解出。' : '这道题已经关闭。'); - const now = this.now(), - root = this.storage.root, - backend = root && nativeWeb(); - if (root && backend) { - const result = backend.enqueueCommunitySubmission( - root, - actor.key, - input, - now, - this.activityFile(), - () => communitySubmissionReason(task, input.source) ?? '', - ); - return 'error' in result ? fail(result.status, result.error) : result.id; - } - const mine = this.ownSubmissions(actor.key); - if ( - mine.filter(item => item.status === 'queued' || item.status === 'checking').length >= - communityLimits.pendingPerPerson - ) - fail(429, `你已有 ${communityLimits.pendingPerPerson} 份提交在等待校验,请等它们出结果。`); - if ( - mine.filter(item => Date.parse(item.submittedAt) > now - 3_600_000).length >= communityLimits.submissionsPerHour - ) - fail(429, `每小时最多提交 ${communityLimits.submissionsPerHour} 次。`); - const reason = communitySubmissionReason(task, input.source); - if (reason) fail(400, reason); - const id = `s${now.toString(36).padStart(9, '0')}${crypto.randomBytes(6).toString('hex')}`; - const item: CommunitySubmission = { - id, - taskId: task.id, - owner: actor.key, - model: input.model, - harness: input.harness, - source: input.source, - submittedAt: this.iso(), - points: this.points(task, now), - status: 'queued', - }; - this.storage.saveRecord(['community', 'submissions', `${id}.json`], item); - this.storage.saveRecord(['community', 'tasks', task.id, 'submissions', `${id}.json`], { id }); - this.storage.saveRecord(['community', 'people', actor.key, 'submissions', `${id}.json`], { id }); - this.storage.saveRecord(this.taskPath(task.id), { - ...task, - submissions: task.submissions + 1, - } satisfies CommunityTask); - this.log({ - kind: 'submitted', - owner: actor.key, - taskId: task.id, - submissionId: id, - model: item.model || undefined, - harness: item.harness || undefined, - }); - return id; + this.requireProfile(actor); + if (!this.runner) fail(503, '证明校验服务暂不可用。'); + const input = parse(submitInput, raw, '提交字段无效。'), + task = this.readTask(input.taskId); + if (task.status !== 'open') fail(409, task.status === 'solved' ? '这道题已经有人先解出。' : '这道题已经关闭。'); + const now = this.now(); + const mine = this.ownSubmissions(actor.key); + if ( + mine.filter(item => item.status === 'queued' || item.status === 'checking').length >= + communityLimits.pendingPerPerson + ) + fail(429, `你已有 ${communityLimits.pendingPerPerson} 份提交在等待校验,请等它们出结果。`); + if ( + mine.filter(item => Date.parse(item.submittedAt) > now - 3_600_000).length >= communityLimits.submissionsPerHour + ) + fail(429, `每小时最多提交 ${communityLimits.submissionsPerHour} 次。`); + const reason = communitySubmissionReason(task, input.source); + if (reason) fail(400, reason); + const id = `s${now.toString(36).padStart(9, '0')}${crypto.randomBytes(6).toString('hex')}`; + const item: CommunitySubmission = { + id, + taskId: task.id, + owner: actor.key, + model: input.model, + harness: input.harness, + source: input.source, + submittedAt: this.iso(), + points: this.points(task, now), + status: 'queued', + }; + this.storage.saveRecord(['community', 'submissions', `${id}.json`], item); + this.storage.saveRecord(['community', 'tasks', task.id, 'submissions', `${id}.json`], { id }); + this.storage.saveRecord(['community', 'people', actor.key, 'submissions', `${id}.json`], { id }); + this.storage.saveRecord(this.taskPath(task.id), { + ...task, + submissions: task.submissions + 1, + } satisfies CommunityTask); + this.log({ + kind: 'submitted', + owner: actor.key, + taskId: task.id, + submissionId: id, + model: item.model || undefined, + harness: item.harness || undefined, }); - this.wakeSubmission(id); - return this.submission(actor, id); - } - wakeSubmission(id: string) { - if (this.checking.has(id) || this.queue.includes(id)) return; this.queue.push(id); this.pump(); + return this.submission(actor, id); } private pump() { while ( this.runner && - !this.options.externalWorker && !this.controller.signal.aborted && this.checking.size < Math.max(1, this.options.concurrency ?? 1) && this.queue.length @@ -669,20 +569,6 @@ export class WebCommunity { private save(item: CommunitySubmission) { this.storage.saveRecord(['community', 'submissions', `${item.id}.json`], item); } - private nativeVerdict(id: string, passed: boolean, reason?: string) { - const backend = this.storage.root && nativeWeb(); - if (!backend || !this.storage.root) return false; - const root = this.storage.root; - this.write(() => { - backend.finishCommunitySubmission(root, id, passed, reason?.slice(0, 1500), this.iso(), this.activityFile()); - }); - return true; - } - /** Read the frozen inputs. The native worker owns scheduling and every receipt write. */ - async checkPersisted(id: string) { - const item = this.submissionRecord(id); - return this.checkProof(this.readTask(item.taskId), item); - } private async checkProof(before: CommunityTask, item: CommunitySubmission) { // The static rules are re-applied so a rule tightened after submission still holds for queued work. let reason = communitySubmissionReason(before, item.source); @@ -725,49 +611,45 @@ export class WebCommunity { if (item.status !== 'queued' && item.status !== 'checking') return; const before = this.readTask(item.taskId); if (before.status !== 'open') { - if (this.nativeVerdict(id, false)) return; this.save({ ...item, status: 'late', reason: '校验前这道题已被先解出或关闭。', checkedAt: this.iso() }); this.log({ kind: 'late', owner: item.owner, taskId: item.taskId, submissionId: id }); return; } this.save({ ...item, status: 'checking' }); const { passed, reason } = await this.checkProof(before, item); - if (this.nativeVerdict(id, passed, reason)) return; - this.write(() => { - const task = this.readTask(item.taskId), - checkedAt = this.iso(); - if (!passed) { - this.save({ ...item, status: 'rejected', reason: reason!.slice(0, 1_500), checkedAt }); - this.log({ kind: 'rejected', owner: item.owner, taskId: item.taskId, submissionId: id }); - return; - } - if (task.status !== 'open') { - this.save({ ...item, status: 'late', reason: '证明通过,但这道题已被先解出。', checkedAt }); - this.log({ kind: 'late', owner: item.owner, taskId: item.taskId, submissionId: id }); - return; - } - this.save({ ...item, status: 'accepted', checkedAt }); - this.storage.saveRecord(this.taskPath(task.id), { - ...task, - status: 'solved', - solvedBy: item.owner, - solvedAt: checkedAt, - solution: id, - points: item.points, - ...(item.model ? { model: item.model } : {}), - ...(item.harness ? { harness: item.harness } : {}), - } satisfies CommunityTask); - for (const file of this.storage.listRecords(['community', 'tasks', task.id, 'claims'])) - this.storage.deleteRecord(['community', 'tasks', task.id, 'claims', file]); - this.log({ - kind: 'accepted', - owner: item.owner, - taskId: item.taskId, - submissionId: id, - points: item.points, - model: item.model || undefined, - harness: item.harness || undefined, - }); + const task = this.readTask(item.taskId), + checkedAt = this.iso(); + if (!passed) { + this.save({ ...item, status: 'rejected', reason: reason!.slice(0, 1_500), checkedAt }); + this.log({ kind: 'rejected', owner: item.owner, taskId: item.taskId, submissionId: id }); + return; + } + if (task.status !== 'open') { + this.save({ ...item, status: 'late', reason: '证明通过,但这道题已被先解出。', checkedAt }); + this.log({ kind: 'late', owner: item.owner, taskId: item.taskId, submissionId: id }); + return; + } + this.save({ ...item, status: 'accepted', checkedAt }); + this.storage.saveRecord(this.taskPath(task.id), { + ...task, + status: 'solved', + solvedBy: item.owner, + solvedAt: checkedAt, + solution: id, + points: item.points, + ...(item.model ? { model: item.model } : {}), + ...(item.harness ? { harness: item.harness } : {}), + } satisfies CommunityTask); + for (const file of this.storage.listRecords(['community', 'tasks', task.id, 'claims'])) + this.storage.deleteRecord(['community', 'tasks', task.id, 'claims', file]); + this.log({ + kind: 'accepted', + owner: item.owner, + taskId: item.taskId, + submissionId: id, + points: item.points, + model: item.model || undefined, + harness: item.harness || undefined, }); } /** Resolves once nothing is queued or running; tests and shutdown use it. */ @@ -813,10 +695,6 @@ export async function handleCommunityRequest( return write(); }; let found: RegExpExecArray | null; - if (method === 'GET') { - const result = community.readPersistedRoute(path, actor); - if (result) return result; - } if (method === 'GET' && path === '/api/community/overview') return { status: 200, body: community.overview() }; if (method === 'GET' && (found = match(/^\/api\/community\/tasks\/([^/]+)$/u))) return { status: 200, body: community.task(found[1]!) }; diff --git a/apps/web/explain.ts b/apps/web/explain.ts index 41caad4c..b2791897 100644 --- a/apps/web/explain.ts +++ b/apps/web/explain.ts @@ -260,7 +260,6 @@ export class WebExplainer { private readonly busy = new Set(); private readonly asked = new Map(); constructor(private readonly timeoutMs = 0) {} - onQueueChange?: () => void; queueState() { return { running: this.busy.size, waiting: [] }; } @@ -274,13 +273,11 @@ export class WebExplainer { if (this.busy.has(owner)) throw new WebExplainError(429, '上一个问题还在回答,请等它结束或先停止。'); if (recent.length >= pace.questions) throw new WebExplainError(429, '提问太频繁,请过几分钟再问。'); this.busy.add(owner); - this.onQueueChange?.(); this.asked.set(owner, [...recent, now]); try { return await askProvider({ ...call, timeoutMs: this.timeoutMs }, signal); } finally { this.busy.delete(owner); - this.onQueueChange?.(); } } prune() { diff --git a/apps/web/explanations.ts b/apps/web/explanations.ts index f9e315e1..21f93146 100644 --- a/apps/web/explanations.ts +++ b/apps/web/explanations.ts @@ -75,7 +75,6 @@ export class WebExplanations { } } - onQueueChange?: () => void; queueState() { const waiting = [...this.jobs.values()] .filter(job => job.explanation.status === 'queued') @@ -174,7 +173,6 @@ export class WebExplanations { } } } - this.onQueueChange?.(); queueMicrotask(() => this.pump()); } private capacity(owner: string) { @@ -257,7 +255,6 @@ export class WebExplanations { this.release(job); throw error; } - this.onQueueChange?.(); queueMicrotask(() => this.pump()); return this.view(job); } @@ -317,7 +314,6 @@ export class WebExplanations { return this.jobs.get(this.id(job.owner, job.run.id, job.key)) === job; } private release(job: Job) { - this.onQueueChange?.(); if (this.current(job)) this.jobs.delete(this.id(job.owner, job.run.id, job.key)); job.input.apiKey = ''; delete job.input.checkpoint; @@ -354,7 +350,6 @@ export class WebExplanations { ); if (!job) break; this.running++; - this.onQueueChange?.(); const now = new Date().toISOString(); Object.assign(job.explanation, { status: 'running', @@ -363,7 +358,6 @@ export class WebExplanations { }); void this.execute(job).finally(() => { this.running--; - this.onQueueChange?.(); this.pump(); }); } diff --git a/apps/web/formalizations.ts b/apps/web/formalizations.ts index 090c3143..8ce85f60 100644 --- a/apps/web/formalizations.ts +++ b/apps/web/formalizations.ts @@ -238,7 +238,6 @@ export class WebFormalizations { }) .sort((a, b) => b.createdAt.localeCompare(a.createdAt)); } - onQueueChange?: () => void; queueState() { const waiting = [ ...[...this.jobs.values()] @@ -544,7 +543,6 @@ export class WebFormalizations { this.release(job); throw error; } - this.onQueueChange?.(); queueMicrotask(() => this.pump()); return this.view(formalization); } @@ -688,7 +686,6 @@ export class WebFormalizations { this.storage.saveRecord([...recordPath(record.owner, record.formalization.id), 'record.json'], record); } private release(job: Job) { - this.onQueueChange?.(); if (this.current(job)) this.jobs.delete(this.key(job.record.owner, job.record.formalization.id)); job.input.apiKey = ''; } @@ -760,7 +757,6 @@ export class WebFormalizations { maxTotalTokens, maxRunSeconds: 0, }; - this.onQueueChange?.(); this.auditJobs.set(this.key(job.record.owner, value.id), { record: job.record, input, @@ -774,7 +770,6 @@ export class WebFormalizations { return this.auditJobs.get(this.key(job.record.owner, job.record.formalization.id)) === job; } private releaseAudit(job: AuditJob) { - this.onQueueChange?.(); if (this.currentAudit(job)) this.auditJobs.delete(this.key(job.record.owner, job.record.formalization.id)); job.input.apiKey = ''; } @@ -811,10 +806,8 @@ export class WebFormalizations { job.record.formalization.updatedAt = now; this.save(job.record); this.auditsRunning++; - this.onQueueChange?.(); void this.executeAudit(job).finally(() => { this.auditsRunning--; - this.onQueueChange?.(); this.pumpAudits(); }); } @@ -880,14 +873,12 @@ export class WebFormalizations { const job = [...this.jobs.values()].find(item => item.record.formalization.status === 'queued'); if (!job) break; this.running++; - this.onQueueChange?.(); Object.assign(job.record.formalization, { status: 'running', progress: { phase: 'preparing', updatedAt: new Date().toISOString() }, }); void this.execute(job).finally(() => { this.running--; - this.onQueueChange?.(); this.pump(); }); } diff --git a/apps/web/jobs.ts b/apps/web/jobs.ts index e58d2c62..e8505171 100644 --- a/apps/web/jobs.ts +++ b/apps/web/jobs.ts @@ -1,5 +1,4 @@ import { queueCounts } from './queueCounts'; -import { nativeWeb } from './nativeWeb'; import { webProviderExecutionDigest, webHarnessResearchError } from './harness'; import crypto from 'node:crypto'; import type { WebConfig } from './config'; @@ -21,7 +20,8 @@ import { personalExpertCardsDigest } from '../../src/solver/personalExperts'; import { isProgressEvent, parseWebFailure, webAgentActionLimits, webLimits, webRunEventLimit } from './shared'; import { recordWebModuleEvent, sanitizeWebEventDetails } from './moduleTelemetry'; import type { WebCommand, WebCommandResult, WebLibraryRestart, WebObservation } from './collaboration'; -import { canonicalMathJson } from '../../src/math/mathRuntimeIo'; +import { canonicalMathJson, mathDigest } from '../../src/math/mathRuntimeIo'; +import { currentResearchModulePlan } from '../../src/solver/modules/policy'; import { WebStorage, type WebCreation } from './storage'; import { WebKnowledgeService } from './knowledgeService'; import { freezeModuleConfiguration } from './moduleRegistry'; @@ -120,7 +120,6 @@ export class WebJobs { } } - onQueueChange?: () => void; queueState() { const waiting = [...this.jobs.values()].filter(job => job.run.status === 'queued').map(job => job.run.createdAt); return { running: this.running, waiting }; @@ -138,17 +137,6 @@ export class WebJobs { const job = this.jobs.get(id); return job?.owner === owner ? job.run : undefined; } - private sessionLists?: (owner: string, runs: WebRun[], version: string) => void; - private actionTallies?: (owner: string, runId: string, actions: NonNullable) => void; - sessionVersionId() { - return this.versionId; - } - publishSessionLists(callback: NonNullable, tallies?: NonNullable) { - this.actionTallies = tallies; - this.sessionLists = callback; - for (const owner of new Set([...this.jobs.values()].map(job => job.owner))) - callback(owner, this.list(owner), this.version(owner)); - } version(owner: string): string { const identity = `${this.versionId}/${owner}/${this.revisions.get(owner) ?? 0}`; return `"${crypto.createHash('sha256').update(identity).digest('hex')}"`; @@ -169,8 +157,6 @@ export class WebJobs { baseUrl: provider.baseUrl, ...(provider.harness || provider.execution ? { executionDigest: webProviderExecutionDigest(provider) } : {}), }; - const native = nativeWeb(); - if (native) return native.runCreationIdentity(visible, providerIdentity, requestId); return { schema: 'theorem-os.web-creation.v1', requestId, @@ -232,28 +218,14 @@ export class WebJobs { if (modeError) throw new WebStorageError(400, modeError); const previous = this.replay(owner, creationInput, provider, requestId); if (previous) return previous; - const native = nativeWeb(); - if (native) { - const error = native.queueAdmission( - this.closing, - [...this.jobs.values()].map(j => j.run.status), - this.list(owner).length, - this.config.queueLimit, - webLimits.maxRuns, - ); - if (error) throw new Error(error); - } else { - if (this.closing) throw new Error('服务正在停止,请稍后重试。'); - const count = (status: string) => [...this.jobs.values()].filter(job => job.run.status === status).length; - const active = count('running'), - waiting = count('queued'); - if (active + waiting >= this.config.queueLimit) - throw new Error( - `运行队列已满:${active} 个任务正在运行,${waiting} 个在排队。草稿已保留,请等几分钟后再提交。`, - ); - if (this.list(owner).length >= webLimits.maxRuns) - throw new Error(`已达到 ${webLimits.maxRuns} 条运行记录的上限。请先下载需要的档案,删除已结束的记录后重试。`); - } + if (this.closing) throw new Error('服务正在停止,请稍后重试。'); + const count = (status: string) => [...this.jobs.values()].filter(job => job.run.status === status).length; + const active = count('running'), + waiting = count('queued'); + if (active + waiting >= this.config.queueLimit) + throw new Error(`运行队列已满:${active} 个任务正在运行,${waiting} 个在排队。草稿已保留,请等几分钟后再提交。`); + if (this.list(owner).length >= webLimits.maxRuns) + throw new Error(`已达到 ${webLimits.maxRuns} 条运行记录的上限。请先下载需要的档案,删除已结束的记录后重试。`); const now = new Date().toISOString(); const knowledgeDigest = input.knowledgeDigest === undefined @@ -269,8 +241,14 @@ export class WebJobs { autoExplain: input.autoExplain ?? true, explanationLanguage: input.explanationLanguage ?? 'zh', }; - if (researchConfiguration && !input.nativeTeamCapacity) - pinnedInput.modulePlan = structuredClone(researchConfiguration.modulePlan); + if (researchConfiguration && !input.nativeTeamCapacity) { + const modulePlan = currentResearchModulePlan(researchConfiguration.modulePlan); + if (modulePlan !== researchConfiguration.modulePlan) { + const { digest: _oldDigest, ...configuration } = { ...researchConfiguration, modulePlan }; + researchConfiguration = { ...configuration, digest: mathDigest(canonicalMathJson(configuration)) }; + } + pinnedInput.modulePlan = structuredClone(modulePlan); + } else if (pinnedInput.modulePlan) pinnedInput.modulePlan = currentResearchModulePlan(pinnedInput.modulePlan); if (input.researchMode === 'skill') pinnedInput.skillLoading ??= 'native'; if (knowledgeDigest) pinnedInput.knowledgeDigest = knowledgeDigest; else delete pinnedInput.knowledgeDigest; @@ -282,20 +260,18 @@ export class WebJobs { ...(formalization ? { formalization: formalization.provenance } : {}), environment, }; - const run: WebRun = native - ? native.initialRun(fields, now) - : { - ...fields, - id: crypto.randomUUID(), - title: (formalization?.provenance.original.trim() || fields.task).split('\n')[0].slice(0, 60) || 'Lean 研究', - status: 'queued', - phase: 'queued', - createdAt: now, - updatedAt: now, - timings: {}, - events: [], - modules: {}, - }; + const run: WebRun = { + ...fields, + id: crypto.randomUUID(), + title: (formalization?.provenance.original.trim() || fields.task).split('\n')[0].slice(0, 60) || 'Lean 研究', + status: 'queued', + phase: 'queued', + createdAt: now, + updatedAt: now, + timings: {}, + events: [], + modules: {}, + }; if (input.continueFrom && continuation) run.continueFrom = clean( { @@ -317,7 +293,7 @@ export class WebJobs { const creation = requestId ? this.creation(normalizeWebTeamPreferences(creationInput), provider, requestId) : undefined; - if (!native) this.event(run, 'queued', '任务已进入队列'); + this.event(run, 'queued', '任务已进入队列'); // Persist the identity and initial run atomically before a worker can be queued. this.storage.saveRun(owner, run, creation); if (creation) this.creations.set(JSON.stringify([owner, requestId]), { ...creation, runId: run.id }); @@ -390,24 +366,14 @@ export class WebJobs { cancel(owner: string, id: string): WebRun | undefined { const job = this.jobs.get(id); if (!job || job.owner !== owner) return undefined; - const native = nativeWeb(); + if (terminal(job.run) || job.run.result?.status === 'evaluated_passed') return job.run; const queued = job.run.status === 'queued'; - const now = new Date().toISOString(); - const cancelled = native?.cancelRun(job.run, now, webRunEventLimit); - if (native ? !cancelled : terminal(job.run) || job.run.result?.status === 'evaluated_passed') return job.run; try { - if (cancelled) { - Object.assign(job.run, cancelled); - delete job.run.queue; - if (!job.run.modules) recordWebModuleEvent(job.run, job.run.events.at(-1)!); - this.persist(job.run); - } else { - job.run.status = 'cancelled'; - job.run.phase = 'cancelled'; - job.run.finishedAt = now; - delete job.run.queue; - this.event(job.run, 'cancelled', '运行已取消'); - } + job.run.status = 'cancelled'; + job.run.phase = 'cancelled'; + job.run.finishedAt = new Date().toISOString(); + delete job.run.queue; + this.event(job.run, 'cancelled', '运行已取消'); } finally { job.controller.abort(); job.input.apiKey = ''; @@ -508,12 +474,11 @@ export class WebJobs { } private changed(owner: string) { this.revisions.set(owner, (this.revisions.get(owner) ?? 0) + 1); - if ((!this.listeners.has(owner) && !this.sessionLists) || this.pendingNotifications.has(owner)) return; + if (!this.listeners.has(owner) || this.pendingNotifications.has(owner)) return; this.pendingNotifications.add(owner); queueMicrotask(() => { this.pendingNotifications.delete(owner); const version = this.version(owner); - this.sessionLists?.(owner, this.list(owner), version); for (const listener of this.listeners.get(owner) ?? []) listener(version); }); } @@ -767,19 +732,10 @@ export class WebJobs { } private pump() { if (this.closing) return; - const native = nativeWeb(); - if (native) { - const waiting = [...this.jobs.values()].filter(j => j.run.status === 'queued').map(j => j.run.id); - for (const id of native.planWebQueue(waiting, this.running, this.config.concurrency, true).start) { - const job = this.jobs.get(id); - if (job?.run.status === 'queued') this.startWorker(job); - } - } else { - while (!this.closing && this.running < this.config.concurrency) { - const job = [...this.jobs.values()].find(j => j.run.status === 'queued'); - if (!job) break; - this.startWorker(job); - } + while (!this.closing && this.running < this.config.concurrency) { + const job = [...this.jobs.values()].find(job => job.run.status === 'queued'); + if (!job) break; + this.startWorker(job); } this.reindex(); } @@ -790,22 +746,14 @@ export class WebJobs { delete job.run.queue; void this.execute(job).finally(() => { this.running--; - this.onQueueChange?.(); this.pump(); }); } /** Queue positions are global and first-in first-out; only counts are shown, never other owners' runs. */ private reindex() { - this.onQueueChange?.(); const queued = [...this.jobs.values()].filter(job => job.run.status === 'queued'); - const positions = nativeWeb()?.planWebQueue( - queued.map(j => j.run.id), - this.running, - this.config.concurrency, - false, - ).waiting; queued.forEach((job, index) => { - const queue = positions?.[index]?.queue ?? { + const queue = { position: index + 1, ahead: index, running: this.running, @@ -855,6 +803,7 @@ export class WebJobs { try { const message = clean(raw, key); if (message.type === 'progress') { + if (message.event === 'library_continuation_started') delete job.run.artifact; job.run.phase = message.event; this.event(job.run, message.event, message.message, message.details); // The solver asks once per run, when its first plan is accepted; the owner may be away from the page. @@ -877,7 +826,6 @@ export class WebJobs { }); tally.count = sequence; } - this.actionTallies?.(job.owner, job.run.id, tally); this.actionsChanged(job.run); } else if (message.type === 'artifact') { if (job.run.result) return; diff --git a/apps/web/keyVault.ts b/apps/web/keyVault.ts index a7f0db16..f8a02b4b 100644 --- a/apps/web/keyVault.ts +++ b/apps/web/keyVault.ts @@ -15,7 +15,6 @@ export class WebKeyVault { constructor( private readonly secret: Buffer, private readonly storage: WebStorage, - private readonly writer?: (message: object) => unknown, ) {} private path(accountId: string) { @@ -50,10 +49,6 @@ export class WebKeyVault { }); } save(accountId: string, providerId: string, baseUrl: string, key: string) { - if (this.writer) { - this.writer({ op: 'vault', account: accountId, provider: providerId, url: baseUrl, key }); - return; - } const iv = crypto.randomBytes(12), cipher = crypto.createCipheriv('aes-256-gcm', this.secret, iv); cipher.setAAD(this.aad(accountId, providerId, baseUrl)); @@ -68,10 +63,6 @@ export class WebKeyVault { this.storage.saveRecord(this.path(accountId), record); } forget(accountId: string, providerId: string) { - if (this.writer) { - this.writer({ op: 'vault', account: accountId, provider: providerId }); - return; - } const record = this.read(accountId); if (!record.providers[providerId]) return; delete record.providers[providerId]; @@ -79,10 +70,6 @@ export class WebKeyVault { else this.storage.deleteRecord(this.path(accountId)); } forgetAccount(accountId: string) { - if (this.writer) { - this.writer({ op: 'vault', account: accountId }); - return; - } this.storage.deleteRecord(this.path(accountId)); } } diff --git a/apps/web/libraryResearch.ts b/apps/web/libraryResearch.ts index 4a2b3fda..e212e7dd 100644 --- a/apps/web/libraryResearch.ts +++ b/apps/web/libraryResearch.ts @@ -2,7 +2,8 @@ import fs from 'node:fs'; 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 { assertAgentTeamProcessesStopped } from '../../src/solver/agentTeam'; +import { readSolverRunState, type SolverRunState } from '../../src/solver/archive'; import { MAX_CONTINUATION_ATTACHMENT_BYTES, MAX_CONTINUATION_ATTACHMENTS, @@ -108,22 +109,45 @@ function writeResearchContinuation(directory: string, seed: Seed, materials: Att return file; } -function readAdvisoryFile(file: string, maxBytes: number) { +function readAdvisoryFile(file: string, maxBytes: number, optional = false) { assertMathCanonicalPath(file); try { return readMathText(file, maxBytes); } catch (error) { - if (error instanceof Error && error.message === 'math_runtime_file_too_large') return; + if ( + error instanceof Error && + (error.message === 'math_runtime_file_too_large' || + (optional && (error as NodeJS.ErrnoException).code === 'ENOENT')) + ) + 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)])]; +function roundParticipants(state: SolverRunState) { + const nativeTeam = state.agentTeam?.transport === 'native-agent-control' ? state.agentTeam : undefined; + const workers = nativeTeam?.workers ?? state.workers ?? []; + return { + native: Boolean(nativeTeam), + trees: [...new Set([state.worktree, ...workers.map(worker => worker.worktree)])], + usageRecords: nativeTeam || !workers.length ? [state, ...workers] : workers, + }; +} + +function collectResearch( + state: SolverRunState, + directory: string, + participants: ReturnType, + remember: (item: Material) => void, +) { + if (participants.native) assertAgentTeamProcessesStopped(state); const files = state.problem.ownedFiles.filter(file => !state.problem.frozenFiles?.[file]); - for (const [index, tree] of trees.entries()) { + for (const [index, tree] of participants.trees.entries()) { if (!isMathPathWithin(directory, tree)) throw new Error('math_library_request_worktree_outside_run'); assertMathCanonicalPath(tree); + const member = participants.native && tree !== state.worktree; + // A native spawn can be recorded before the host creates its worktree. + if (member && !fs.existsSync(tree)) continue; const commit = git(tree, ['rev-parse', 'HEAD']); const provenance: Material['provenance'] = { source: `Library continuation, worker ${index}; saved draft, not proof evidence`, @@ -135,14 +159,11 @@ function collectResearch(state: SolverRunState, directory: string, remember: (it 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)); + const text = readAdvisoryFile(full, MAX_CONTINUATION_ATTACHMENT_BYTES - Buffer.byteLength(header), member); if (text !== undefined) remember({ kind: 'proof-source', text: header + text, provenance }); } - const notesFile = path.join(tree, 'RESEARCH.md'); - if (fs.existsSync(notesFile)) { - const notes = readAdvisoryFile(notesFile, MAX_CONTINUATION_ATTACHMENT_BYTES); - if (notes) remember({ kind: 'research-notes', text: notes, provenance }); - } + const notes = readAdvisoryFile(path.join(tree, 'RESEARCH.md'), MAX_CONTINUATION_ATTACHMENT_BYTES, true); + if (notes) remember({ kind: 'research-notes', text: notes, provenance }); } } @@ -193,7 +214,7 @@ export async function runWebLibraryResearch(options: { let turns = 0, solveWallMs = 0, solveExecutionMs = 0; - const records: (SolverRunState | SolverWorkerState)[] = []; + const records: ReturnType['usageRecords'][number][] = []; const rounds: { round: number; runId?: string; @@ -234,7 +255,8 @@ export async function runWebLibraryResearch(options: { turns += usedTurns; solveWallMs += usedMs; solveExecutionMs += executedMs; - if (state) records.push(...(state.workers?.length ? state.workers : [state])); + const participants = state && roundParticipants(state); + if (participants) records.push(...participants.usageRecords); rounds.push({ round: current.round, runId: state?.runId, @@ -264,13 +286,13 @@ export async function runWebLibraryResearch(options: { return { seed: current.seed, output: current.output, raw: report }; }; if (raw.status !== 'library_requested') return finish(); - if (!options.libraryCatalog || !state || !state.solveStartedAt || !state.solveFinishedAt) + if (!options.libraryCatalog || !state || !participants || !state.solveStartedAt || !state.solveFinishedAt) throw new Error('math_library_request_run_incomplete'); const value = raw.libraryRequest as { request?: unknown; worktree?: unknown } | undefined; if ( !value || typeof value.worktree !== 'string' || - ![state.worktree, ...(state.workers ?? []).map(worker => worker.worktree)].includes(value.worktree) || + !participants.trees.includes(value.worktree) || !isMathPathWithin(options.directory, value.worktree) ) throw new Error('math_library_request_worker_changed'); @@ -316,7 +338,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, remember); + collectResearch(state, options.directory, participants, 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/moduleRegistry.ts b/apps/web/moduleRegistry.ts index 95cf28dd..e6c84b1d 100644 --- a/apps/web/moduleRegistry.ts +++ b/apps/web/moduleRegistry.ts @@ -6,6 +6,7 @@ import { solverIdentityMethodDigest, } from '../../src/solver/modules/moduleIdentity'; import { + currentResearchModulePlan, defaultResearchModulePlan, researchModulePlanSchema, type ResearchModulePlan, @@ -58,16 +59,16 @@ export function registeredWebModules() { outputs: ['bound-check-receipt'], fixed: true, }, - ...(['plan', 'critical-path', 'continuation'] as const).map(scheduler => ({ - id: `M3:${scheduler}`, - slot: 'M3' as const, - name: { plan: '计划顺序', 'critical-path': '关键路径', continuation: '延续证明前沿' }[scheduler], - version: configuredResearchModuleIdentity({ scheduler, context: 'full', custom: [] }).identity.versions.M3!, + { + id: 'M3:plan', + slot: 'M3', + name: '计划顺序', + version: directSolverModuleIdentity.versions.M3!, inputs: ['task-graph', 'proof-frontier', 'budgets'], outputs: ['ready-task-ranking'], - fixed: false, - configuration: { scheduler }, - })), + fixed: true, + configuration: { scheduler: 'plan' }, + }, ...(['full', 'essential'] as const).map(context => ({ id: `M4:${context}`, slot: 'M4' as const, @@ -116,7 +117,7 @@ export function freezeModuleConfiguration( const ids = new Set([ 'M1:direct', 'M2:lean-kernel', - `M3:${selected.scheduler}`, + 'M3:plan', `M4:${selected.context}`, 'M5:cooperation', 'S3:independent-final', @@ -134,7 +135,7 @@ export function freezeModuleConfiguration( .entries.filter(entry => ids.has(entry.id)) .map(entry => ({ slot: entry.slot, - id: entry.id, + id: entry.slot === 'M3' ? `M3:${selected.scheduler}` : entry.id, version: configuration.versions[entry.slot] ?? entry.version, })), }, @@ -181,7 +182,7 @@ export class WebModuleRegistry { const name = input.name.trim(); if (plans.some(plan => plan.id !== previous?.id && plan.name.toLowerCase() === name.toLowerCase())) throw new WebStorageError(409, '已有同名方案,请更换名称。'); - const plan = input.plan as ResearchModulePlan; + const plan = currentResearchModulePlan(input.plan as ResearchModulePlan); const now = new Date(Math.max(Date.now(), previous ? Date.parse(previous.updatedAt) + 1 : 0)).toISOString(); const saved: WebSavedModulePlan = { id: previous?.id ?? crypto.randomUUID(), diff --git a/apps/web/nativeWeb.ts b/apps/web/nativeWeb.ts deleted file mode 100644 index 65d32f57..00000000 --- a/apps/web/nativeWeb.ts +++ /dev/null @@ -1,82 +0,0 @@ -import type { WebCreation } from './storage'; -import type { WebRun } from './shared'; -type StaticFiles = { - serve( - root: string, - relative: string, - acceptEncoding: string, - ifNoneMatch: string, - head: boolean, - ): { status: number; headers: Record; body?: Buffer; error?: string }; -}; - -type AdmissionError = { status: number; error: string }; -type WebBackend = { - persistRun(root: string, owner: string, summary: unknown, observation?: number, creation?: WebCreation): void; - planWebQueue( - queued: string[], - running: number, - slots: number, - dispatch: boolean, - ): { start: string[]; waiting: { id: string; queue: NonNullable }[] }; - runCreationIdentity(input: unknown, provider: unknown, requestId: string): WebCreation; - queueAdmission( - closing: boolean, - statuses: string[], - owned: number, - queueLimit: number, - ownerLimit: number, - ): string | undefined; - initialRun(fields: unknown, at: string): WebRun; - cancelRun(run: WebRun, at: string, eventLimit: number): WebRun | undefined; - recoverCommunityAdmission(root: string): string | undefined; - pendingCommunitySubmissions(root: string): string[]; - nextCommunityTask(root: string): string; - publishCommunityTask( - root: string, - admin: boolean, - task: unknown, - activityFile: string, - ): { status: 201 } | AdmissionError; - enqueueCommunitySubmission( - root: string, - owner: string, - input: unknown, - now: number, - activityFile: string, - checkSource: () => string, - ): { status: 202; id: string } | AdmissionError; - finishCommunitySubmission( - root: string, - id: string, - passed: boolean, - reason: string | undefined, - checkedAt: string, - activityFile: string, - ): unknown; - CommunityWriteLock: new (root: string) => { release(): void }; - WebSessionWriter: new (socket: string) => { update(message: string): string }; - WorkbenchStatic: new () => StaticFiles; - readCommunity(request: { - root: string; - path: string; - now: number; - actor?: string; - admin: boolean; - checker: boolean; - locale: string; - limits: Record; - }): { status: number; body: unknown }; -}; - -let loaded: WebBackend | undefined; -export function nativeWeb(): WebBackend | undefined { - const library = process.env.THEOREMOS_WEB_STATIC_ADDON; - if (!library) return; - if (!loaded) { - const handle = { exports: {} as WebBackend }; - process.dlopen(handle, library); - loaded = handle.exports; - } - return loaded; -} diff --git a/apps/web/operations.ts b/apps/web/operations.ts index 8669fa1b..0b4f6865 100644 --- a/apps/web/operations.ts +++ b/apps/web/operations.ts @@ -4,7 +4,6 @@ import type { WebStorage } from './storage'; const maintenanceFile = ['operations', 'maintenance.json']; /** Shared with the host operations CLI so maintenance does not require impersonating a user's login. */ export class WebOperations { - onMailFailure?: () => void; private smtp = 0; private lastSmtpFailureAt?: string; constructor( @@ -20,7 +19,6 @@ export class WebOperations { mailFailed() { this.smtp++; this.lastSmtpFailureAt = new Date().toISOString(); - this.onMailFailure?.(); } failures() { return { smtp: this.smtp, ...(this.lastSmtpFailureAt ? { lastSmtpFailureAt: this.lastSmtpFailureAt } : {}) }; diff --git a/apps/web/paperDrafts.ts b/apps/web/paperDrafts.ts index 4d51ffdc..16c8136b 100644 --- a/apps/web/paperDrafts.ts +++ b/apps/web/paperDrafts.ts @@ -18,7 +18,6 @@ export class WebPaperDrafts { this.storage.interruptPaperDrafts(); } - onQueueChange?: () => void; queueState() { return { running: this.active.size, waiting: [] }; } @@ -127,10 +126,8 @@ export class WebPaperDrafts { }) .finally(() => { this.active.delete(owner); - this.onQueueChange?.(); }); this.active.set(owner, { id: job.id, runId: run.id, done, controller }); - this.onQueueChange?.(); return job; } diff --git a/apps/web/precheck.ts b/apps/web/precheck.ts index 1bc26936..f42fb09c 100644 --- a/apps/web/precheck.ts +++ b/apps/web/precheck.ts @@ -162,7 +162,6 @@ export class WebPrechecker { private readonly limits = { concurrency: 2, queue: 6, perMinute: 20, cache: 200 }, ) {} - onQueueChange?: () => void; queueState() { return { running: this.running, waiting: this.waiting.map(item => item.createdAt) }; } @@ -226,16 +225,13 @@ export class WebPrechecker { }; const leave = () => { this.waiting.splice(this.waiting.indexOf(turn), 1); - this.onQueueChange?.(); reject(controller.signal.reason); }; this.waiting.push(turn); - this.onQueueChange?.(); controller.signal.addEventListener('abort', leave, { once: true }); }); } else { this.running++; - this.onQueueChange?.(); } try { controller.signal.throwIfAborted(); @@ -259,7 +255,6 @@ export class WebPrechecker { const next = this.waiting.shift(); if (next) next.start(); else this.running--; - this.onQueueChange?.(); } } finally { signal.removeEventListener('abort', stop); diff --git a/apps/web/problemDraftSubmission.ts b/apps/web/problemDraftSubmission.ts index c695bcd0..8eeee731 100644 --- a/apps/web/problemDraftSubmission.ts +++ b/apps/web/problemDraftSubmission.ts @@ -1,5 +1,9 @@ import { canonicalMathJson, mathDigest } from '../../src/math/mathRuntimeIo'; -import { defaultResearchModulePlan } from '../../src/solver/modules/policy'; +import { + currentResearchModulePlan, + defaultResearchModulePlan, + type ResearchModulePlan, +} from '../../src/solver/modules/policy'; import type { ProblemDraftValue } from './problemDraftTypes'; import type { WebFormalization } from './formalizationTypes'; import type { WebRun } from './shared'; @@ -84,7 +88,9 @@ export function matchesProblemRun(value: ProblemDraftValue, run: WebRun): boolea if (refs.some(ref => !selected.some(item => sameRef(item, ref)))) return false; const expectedPlan = draft.modulePlan ?? config?.agent?.content.modulePlan ?? defaultResearchModulePlan(); const actualPlan = run.modulePlan ?? defaultResearchModulePlan(); - if (equal(expectedPlan, actualPlan)) return true; + const matchesPlan = (plan: ResearchModulePlan) => + equal(expectedPlan, plan) || (plan.scheduler === 'plan' && equal(currentResearchModulePlan(expectedPlan), plan)); + if (matchesPlan(actualPlan)) return true; const skillIds = new Set( config?.skills.flatMap(item => item.content.slots.map( @@ -92,5 +98,5 @@ export function matchesProblemRun(value: ProblemDraftValue, run: WebRun): boolea ), ), ); - return equal(expectedPlan, { ...actualPlan, custom: actualPlan.custom.filter(item => !skillIds.has(item.id)) }); + return matchesPlan({ ...actualPlan, custom: actualPlan.custom.filter(item => !skillIds.has(item.id)) }); } diff --git a/apps/web/researchMode.ts b/apps/web/researchMode.ts index 3eda9360..dac0fdff 100644 --- a/apps/web/researchMode.ts +++ b/apps/web/researchMode.ts @@ -44,9 +44,10 @@ export function webResearchModeError( | 'portfolioExploration' | 'portfolioSeconds' >, + canDefaultToNativeTeam = false, ): string | undefined { if (requestsRetiredPortfolio(input)) return retiredPortfolioMessage; - if (input.nativeTeamPreferredProfiles?.length && input.nativeTeamCapacity === undefined) + if (input.nativeTeamPreferredProfiles?.length && input.nativeTeamCapacity === undefined && !canDefaultToNativeTeam) return '角色偏好仅适用于 Codex 原生团队。'; if (input.nativeTeamCapacity !== undefined) { if (!nativeTeamCapacitySchema.safeParse(input.nativeTeamCapacity).success) diff --git a/apps/web/server.ts b/apps/web/server.ts index f389538a..df4e5151 100644 --- a/apps/web/server.ts +++ b/apps/web/server.ts @@ -1,4 +1,3 @@ -import { nativeWeb } from './nativeWeb'; import { publicWebProvider, webHarnessResearchError } from './harness'; import { nativeTeamCapacitySchema, @@ -45,12 +44,16 @@ import { type WebSession, workbenchReturn, } from './shared'; -import { researchModulePlanSchema, type ResearchModulePlan } from '../../src/solver/modules/policy'; +import { + currentResearchModulePlan, + researchModulePlanSchema, + type ResearchModulePlan, +} from '../../src/solver/modules/policy'; import { WebStorage, WebStorageError } from './storage'; import { WebKnowledgeService, type WebKnowledgeDetailOptions } from './knowledgeService'; import { WebModuleRegistry } from './moduleRegistry'; import { webPlanApprovalSchema } from './collaborationValidation'; -import { normalizeEmail, WebAuth, WebAuthError, type WebAccount, type WebMailer, type WebMilestone } from './auth'; +import { WebAuth, WebAuthError, type WebMailer, type WebMilestone } from './auth'; import { WebSessionAdmission, WebAdmissionError } from './admission'; import { WebOperations } from './operations'; import { checkWebProvider, WebProviderCheckError } from './providerCheck'; @@ -506,40 +509,11 @@ export function createWebService( const knowledge = new WebKnowledgeService(storage); const registry = new WebModuleRegistry(storage); const sessions = new Map(storage.listSessions().map(session => [session.id, session])); - const writerSocket = process.env.THEOREMOS_WEB_SESSION_SOCKET; - const Writer = writerSocket && nativeWeb()?.WebSessionWriter; - const identityWriter = Writer ? new Writer(writerSocket!) : undefined; - const identity = (message: object): T => { - const result = JSON.parse(identityWriter!.update(JSON.stringify(message))); - if (result?.failed === true) throw new Error('Session storage operation failed'); - return result; - }; - const persistSession = (session: Session) => { - if (!identityWriter) { - storage.saveSession(session); - return; - } - if (!identity({ op: 'save', session })) throw new HttpError(401, '会话已过期,请刷新页面。'); - }; - const touchSession = (s: Session) => { - s.touchedAt = Date.now(); - if (identityWriter && !identity({ op: 'touch', session: s })) throw new HttpError(401, '会话已过期,请刷新页面。'); + const persistSession = (session: Session) => storage.saveSession(session); + const touchSession = (session: Session) => { + session.touchedAt = Date.now(); }; - const auth = config.auth - ? new WebAuth( - config.auth, - storage, - options.mailer, - options.captchaAnswer, - identityWriter - ? message => { - const reply = identity(message); - if (reply?.status && reply.error) throw new WebAuthError(reply.status, reply.error); - return reply; - } - : undefined, - ) - : undefined; + const auth = config.auth ? new WebAuth(config.auth, storage, options.mailer, options.captchaAnswer) : undefined; const quota = auth && config.quota ? new WebQuota(storage, config.quota) : undefined; const providersFor = (session: Session) => webProvidersForAccount(config, session.account?.id); // With login enabled, records belong to the account; otherwise to the anonymous browser session. @@ -556,10 +530,7 @@ export function createWebService( return ids.length ? ids : undefined; }; // Each account reads and replaces only its own saved keys. - const vault = - auth && config.keySecret - ? new WebKeyVault(config.keySecret, storage, identityWriter ? identity : undefined) - : undefined; + const vault = auth && config.keySecret ? new WebKeyVault(config.keySecret, storage) : undefined; const savedKeysFor = (session: Session) => vault && session.account ? vault.list(session.account.id, providersFor(session)) : []; // What an empty key field stands for: the account's saved key, then the server's key for admins. @@ -792,47 +763,7 @@ export function createWebService( }, ); const prechecker = runner.check ? new WebPrechecker(runner.check.bind(runner)) : undefined; - const checkerSocket = process.env.THEOREMOS_WEB_CHECKER_SOCKET; - const community = new WebCommunity(storage, runner.check?.bind(runner), { externalWorker: Boolean(checkerSocket) }); - // Only the Rust listener can reach this Unix socket. It carries Lean source review and isolated proof checks, - // never an account, permission, or public request forwarded for publication. - const checkerServer = checkerSocket - ? http - .createServer(async (req, res) => { - try { - const raw = await readJson(req); - if (req.method === 'POST' && req.url === '/task') { - const spec = z - .object({ - id: z.string().regex(/^T[1-9][0-9]{0,5}$/u), - environment: z.enum(['standard', 'mathlib']), - prelude: z.string(), - statement: z.string(), - }) - .strict() - .parse(raw); - json(res, 200, await community.reviewTask(spec.id, spec.environment, spec.prelude, spec.statement)); - } else if (req.method === 'POST' && req.url === '/submission') { - const spec = z - .object({ module: z.string(), environment: z.enum(['standard', 'mathlib']), source: z.string() }) - .strict() - .parse(raw); - community.reviewSubmission({ module: spec.module, environment: spec.environment }, spec.source); - json(res, 200, { ok: true }); - } else if (req.method === 'POST' && req.url === '/check') { - const { id } = z - .object({ id: z.string().regex(/^s[0-9a-z]{8,40}$/u) }) - .strict() - .parse(raw); - json(res, 200, await community.checkPersisted(id)); - } else json(res, 404, { error: '接口不存在。' }); - } catch (e) { - if (e instanceof WebStorageError || e instanceof HttpError) json(res, e.status, { error: e.message }); - else json(res, 503, { error: '证明校验服务暂不可用。' }); - } - }) - .listen(checkerSocket) - : undefined; + const community = new WebCommunity(storage, runner.check?.bind(runner)); const communityActor = (session?: Session): CommunityActor | undefined => { const owner = session && ownerOf(session); return owner @@ -861,82 +792,6 @@ export function createWebService( }, (owner, call, signal) => explainer.ask(owner, call, signal), ); - if (identityWriter) - identity({ - op: 'start', - settings: { - ...(sample && { sample }), - ttl: config.sessionTtlMs, - locale: Intl.Collator().resolvedOptions().locale, - ...(config.auth - ? { - auth: { - admins: config.auth.admins || [], - smtpUrl: config.auth.smtpUrl, - from: config.auth.from, - allowlist: config.auth.allowlist, - allowlistFile: config.auth.allowlistFile, - signup: config.auth.signup || 'allowlist', - }, - } - : {}), - context: { - base: { - providers: config.providers.map(publicWebProvider), - environments: getWebEnvironments(), - templates: webTemplates, - defaults: webDefaults, - limits: webLimits, - ...(sample ? { sample: { id: sample.run.id, title: sample.run.title } } : {}), - ...(prechecker ? { precheck: true } : {}), - ...(auth?.termsVersion ? { termsVersion: auth.termsVersion } : {}), - ...(auth?.signup() === 'open' ? { signup: 'open' } : {}), - }, - accountUrls: config.accountProviderUrls, - adminKeyIds: Object.keys(config.adminKeys || {}), - quota: config.quota, - dataRoot: config.dataRoot, - workerImage: config.workerImage, - runVersionId: jobs.sessionVersionId(), - vault: Boolean(vault), - }, - }, - sessions: [...sessions.values()], - }); - if (identityWriter) - jobs.publishSessionLists( - (owner, runs, version) => identity({ op: 'runs', owner, runs, version }), - (owner, id, actions) => identity({ op: 'runActions', owner, id, actions }), - ); - if (identityWriter) { - // The schedulers own their live slots. Send only counts and waiting timestamps after each transition. - const publish = () => - identity({ - op: 'operations', - queues: { - research: jobs.queueState(), - formalization: formalizations.queueState(), - explanation: explanations.queueState(), - precheck: prechecker?.queueState() ?? { running: 0, waiting: [] }, - conversation: explainer.queueState(), - paper: papers.queueState(), - }, - failures: operations.failures(), - }); - let pending = false; - const changed = () => { - if (pending) return; - pending = true; - queueMicrotask(() => { - pending = false; - publish(); - }); - }; - for (const source of [jobs, formalizations, explanations, prechecker, explainer, papers]) - if (source) source.onQueueChange = changed; - operations.onMailFailure = changed; - publish(); - } const rates = new Map(); const runStreams = new Map void>>(); const origin = new URL(config.publicUrl); @@ -961,15 +816,13 @@ export function createWebService( response.setHeader('Set-Cookie', auth ? [value, cookieValue(bootstrapCookie, '', 0)] : value); }; const startSession = (account?: Session['account'], verifiedByEmail = false) => { - const session: Session = identityWriter - ? identity({ op: 'create', account, verified: verifiedByEmail }) - : { - id: crypto.randomBytes(32).toString('hex'), - csrf: crypto.randomBytes(32).toString('hex'), - touchedAt: Date.now(), - ...(account ? { account } : {}), - ...(verifiedByEmail ? { passwordResetUntil: Date.now() + 10 * 60_000 } : {}), - }; + const session: Session = { + id: crypto.randomBytes(32).toString('hex'), + csrf: crypto.randomBytes(32).toString('hex'), + touchedAt: Date.now(), + ...(account ? { account } : {}), + ...(verifiedByEmail ? { passwordResetUntil: Date.now() + 10 * 60_000 } : {}), + }; sessions.set(session.id, session); return session; }; @@ -978,13 +831,6 @@ export function createWebService( // Revocation must take effect even when deleting persisted records fails. sessions.delete(id); let failure: unknown; - if (identityWriter) { - try { - identity({ op: 'remove', id }); - } catch (e) { - failure = e; - } - } for (const stop of runStreams.get(id) ?? []) stop(); if (!auth) { conversations.forget(id); @@ -1005,7 +851,7 @@ export function createWebService( trajectories.forgetOwner(id); } try { - if (!identityWriter) storage.deleteSession(id); + storage.deleteSession(id); } catch (error) { failure ??= error; } @@ -1013,7 +859,7 @@ export function createWebService( }; const endSessions = (matches: (session: Session) => boolean) => { let failure: unknown; - for (const session of identityWriter ? identity({ op: 'list' }) : sessions.values()) + for (const session of sessions.values()) if (matches(session)) { const id = session.id; try { @@ -1029,14 +875,11 @@ export function createWebService( quota?.prune(); let failure: unknown; try { - if (identityWriter) { - for (const id of identity({ op: 'expired', now: Date.now() })) endSession(id); - } else - endSessions(session => { - // Login-page sessions without an account only need to outlive one sign-in attempt. - const ttl = auth && !session.account ? Math.min(config.sessionTtlMs, 60 * 60_000) : config.sessionTtlMs; - return Date.now() - session.touchedAt > ttl; - }); + endSessions(session => { + // Login-page sessions without an account only need to outlive one sign-in attempt. + const ttl = auth && !session.account ? Math.min(config.sessionTtlMs, 60 * 60_000) : config.sessionTtlMs; + return Date.now() - session.touchedAt > ttl; + }); } catch (error) { failure = error; } @@ -1049,11 +892,6 @@ export function createWebService( const maintenance = setInterval(() => { try { prune(); - if (identityWriter && sessions.size) { - // Drop backend object references for sessions logged out directly at the Rust listener. - const active = new Set(identity({ op: 'ids' })); - for (const id of sessions.keys()) if (!active.has(id)) sessions.delete(id); - } } catch { console.error('[web_cleanup_failed] background cleanup failed'); } @@ -1063,22 +901,7 @@ export function createWebService( const cookies = header?.split(';').map(value => value.trim()) ?? []; const read = (name: string) => { const value = cookies.find(value => value.startsWith(`${name}=`))?.slice(name.length + 1); - if (!value) return; - const prior = sessions.get(value); - if (!identityWriter) return prior; - const live = identity({ op: 'get', id: value }); - if (!live) { - sessions.delete(value); - return; - } - // Other requests can revoke a session while an upload is in flight. - if (prior) { - if (live.passwordResetUntil === undefined) delete prior.passwordResetUntil; - Object.assign(prior, live); - return prior; - } - sessions.set(value, live); - return live; + return value ? sessions.get(value) : undefined; }; let session = read(sessionCookie); if (!auth) return session; @@ -1155,9 +978,9 @@ export function createWebService( if (retiredInput) throw new HttpError(400, retiredInput, retiredResearchCoordinationCode); const harnessError = webHarnessResearchError(provider, creationInput); if (harnessError) throw new HttpError(400, harnessError); - const researchModeError = webResearchModeError(creationInput); - if (researchModeError) throw new HttpError(400, researchModeError); const teamEligible = submitted.researchMode !== 'legacy' && !submitted.modulePlan; + const researchModeError = webResearchModeError(creationInput, teamEligible); + if (researchModeError) throw new HttpError(400, researchModeError); if (submitted.planApproval && !teamEligible) throw new HttpError(400, '先审计划需要 Codex 原生团队。'); // A typed key wins; an empty one uses the account's saved key, then the server's key for admins. const apiKey = typed || heldKey(session, provider); @@ -1168,7 +991,10 @@ export function createWebService( return { status: 200, body: { run: raced, ...submissionKeys() } }; } if (!readiness.ready) throw new HttpError(503, '运行环境尚未就绪,请先构建 worker 镜像。'); - if ((submitted.nativeTeamCapacity || submitted.planApproval) && !readiness.nativeTeam) + if ( + (submitted.nativeTeamCapacity || submitted.planApproval || submitted.nativeTeamPreferredProfiles?.length) && + !readiness.nativeTeam + ) throw new HttpError(503, '当前运行镜像未安装原生团队后端。'); // Preserve explicit module experiments and expert assets submitted for the classic solo runner. const customSolo = @@ -1187,6 +1013,7 @@ export function createWebService( if (origin.run.source !== input.source || origin.run.environment !== input.environment) throw new HttpError(409, '运行的原题或环境与陈述版本不一致。'); } + const modulePlan = input.modulePlan as ResearchModulePlan | undefined; const frozenResearch = !input.researchSelection ? undefined : input.nativeTeamCapacity @@ -1199,13 +1026,14 @@ export function createWebService( owner, input.researchSelection as ResearchConfigurationSelection, input.environment, - input.researchSelection.agent ? undefined : (input.modulePlan as ResearchModulePlan | undefined), + input.researchSelection.agent ? undefined : modulePlan, ); if ( frozenResearch && input.researchSelection?.agent && - input.modulePlan && - JSON.stringify(input.modulePlan) !== JSON.stringify(frozenResearch.modulePlan) + modulePlan && + canonicalMathJson(currentResearchModulePlan(modulePlan)) !== + canonicalMathJson(currentResearchModulePlan(frozenResearch.modulePlan)) ) throw new HttpError(409, '所选 Agent 的方案与当前自定义方案不同,请清除自定义方案后重新提交。'); if (frozenResearch) { @@ -1315,77 +1143,6 @@ export function createWebService( for (const item of formalizations.list(owner)) formalizations.cancel(owner, item.id); for (const item of conversations.list(owner)) conversations.stop(owner, item.id); }; - const jobSocket = process.env.THEOREMOS_WEB_JOBS_SOCKET; - const jobServer = jobSocket - ? http - .createServer(async (request, response) => { - try { - const input = objectBody(await readJson(request, 192 * 1024)); - if (request.method === 'POST' && request.url === '/mail/code') { - if (!auth || typeof input.code !== 'string' || !/^\d{6}$/u.test(input.code)) - throw new HttpError(400, '验证码格式无效。'); - await auth.sendLoginCode(normalizeEmail(input.email), input.code); - json(response, 200, { delivered: true }); - return; - } - if (request.method === 'POST' && request.url === '/suspend') { - const { login, accountId } = input; - const account = typeof login === 'string' ? auth?.getAccount(login) : undefined; - if (!auth || !account || account.id !== accountId || !account.suspendedAt) - throw new HttpError(409, '账号状态已变更,请重新读取。'); - auth.invalidateLoginCode(accountLogin(account)); - cancelAccountWork(account.id); - for (const cached of sessions.values()) { - if (cached.account?.id !== account.id) continue; - sessions.delete(cached.id); - for (const stop of runStreams.get(cached.id) ?? []) stop(); - } - json(response, 200, { stopped: true }); - return; - } - if (request.method !== 'POST' || !['/create', '/cancel'].includes(request.url || '')) - throw new HttpError(404, '页面或运行不存在。'); - const sessionId = input.session; - if (typeof sessionId !== 'string' || !/^[a-f0-9]{64}$/u.test(sessionId)) - throw new HttpError(401, '会话已过期,请刷新页面。'); - const cookie = sessionCookie + '=' + sessionId; - const session = fromCookies(cookie); - const owner = session && ownerOf(session); - if (!session || session.id !== sessionId || !owner) throw new HttpError(401, '会话已过期,请刷新页面。'); - const admitWork = () => { - if (fromCookies(cookie) !== session) throw new HttpError(401, '会话已过期,请刷新页面。'); - checkWork(session); - }; - if (auth && session.account && auth.needsTerms(accountLogin(session.account))) - throw new HttpError(428, '使用条款已更新,请先确认后继续。'); - if (request.url === '/cancel') { - const id = input.id; - if (typeof id !== 'string' || !/^[a-f0-9-]{36}$/u.test(id)) - throw new HttpError(404, '页面或运行不存在。'); - const run = jobs.cancel(owner, id); - if (!run) throw new HttpError(404, '运行不存在或不属于当前会话。'); - json(response, 200, { run }); - } else { - admitWork(); - const result = await createRun( - session, - owner, - input.body, - typeof input.requestId === 'string' ? input.requestId : undefined, - admitWork, - ); - json(response, result.status, result.body); - } - } catch (e) { - const known = e instanceof WebStorageError || e instanceof HttpError || e instanceof WebAuthError; - json(response, known ? e.status : 500, { - error: known ? e.message : '服务暂时不可用。', - ...(e instanceof HttpError && e.code ? { code: e.code } : {}), - }); - } - }) - .listen(jobSocket) - : undefined; const server = http.createServer(async (request, response) => { const encoding = acceptedEncoding(request.headers['accept-encoding']); if (encoding) jsonEncodings.set(response, encoding); @@ -1434,22 +1191,16 @@ export function createWebService( // Behind a tunnel every request comes from the proxy, so the configured proxy header names the visitor. const forwarded = config.clientIpHeader ? request.headers[config.clientIpHeader] : undefined; const ip = - (typeof forwarded === 'string' && forwarded.trim().slice(0, 64)) || - (process.env.THEOREMOS_WEB_BACKEND_SOCKET ? String(request.headers['x-theoremos-socket-peer'] || '') : '') || - request.socket.remoteAddress || - ''; - // The production listener counts native reads and forwarded routes in the same window. - if (!process.env.THEOREMOS_WEB_BACKEND_SOCKET) { - let rate = rates.get(ip); - if (!rate) { - if (rates.size >= 2_000) throw new HttpError(429, '请求较多,请稍后重试。'); - rates.set(ip, (rate = { count: 0, expiresAt: Date.now() + 60_000 })); - } - if (++rate.count > 600) { - response.setHeader('Retry-After', Math.max(1, Math.ceil((rate.expiresAt - Date.now()) / 1000))); - response.setHeader('X-Theoremos-Rate-Limit-Scope', 'api'); - throw new HttpError(429, '请求过于频繁,请稍后重试。'); - } + (typeof forwarded === 'string' && forwarded.trim().slice(0, 64)) || request.socket.remoteAddress || ''; + let rate = rates.get(ip); + if (!rate) { + if (rates.size >= 2_000) throw new HttpError(429, '请求较多,请稍后重试。'); + rates.set(ip, (rate = { count: 0, expiresAt: Date.now() + 60_000 })); + } + if (++rate.count > 600) { + response.setHeader('Retry-After', Math.max(1, Math.ceil((rate.expiresAt - Date.now()) / 1000))); + response.setHeader('X-Theoremos-Rate-Limit-Scope', 'api'); + throw new HttpError(429, '请求过于频繁,请稍后重试。'); } // Share links are public read-only snapshots: no session, no cookie, nothing beyond the stored whitelist. const shared = /^\/api\/share\/([^/]+)$/u.exec(url.pathname); @@ -1672,7 +1423,6 @@ export function createWebService( requireSession, ); session.passwordResetUntil = undefined; - if (identityWriter) identity({ op: 'consumeReset', id: session.id }); let failure: unknown; try { persistSession(session); @@ -1761,13 +1511,7 @@ export function createWebService( maintenance: operations.maintenance, ready, ...(disk ? { disk } : {}), - failures: (() => { - const hosted = operations.failures(); - if (!identityWriter) return hosted; - const native = identity<{ smtp: number; lastSmtpFailureAt?: string }>({ op: 'mailFailures' }); - const last = [hosted.lastSmtpFailureAt, native.lastSmtpFailureAt].filter(Boolean).sort().at(-1); - return { smtp: hosted.smtp + native.smtp, ...(last ? { lastSmtpFailureAt: last } : {}) }; - })(), + failures: operations.failures(), queues: { research: jobs.counts(), formalization: formalizations.counts(), @@ -2867,8 +2611,6 @@ export function createWebService( formalizations.close(), conversations.close(), communityClosed, - jobServer && new Promise(resolve => jobServer.close(() => resolve())), - checkerServer && new Promise(resolve => checkerServer.close(() => resolve())), new Promise(resolve => server.close(() => resolve())), ]); for (const result of closed) if (result.status === 'rejected') throw result.reason; @@ -2895,9 +2637,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.ar }); const service = createWebService(config); const listening = () => console.log(`TheoremOS workbench: ${config.publicUrl}`); - if (process.env.THEOREMOS_WEB_BACKEND_SOCKET) - service.server.listen(process.env.THEOREMOS_WEB_BACKEND_SOCKET, listening); - else service.server.listen(config.port, config.host, listening); + service.server.listen(config.port, config.host, listening); let stopping = false; const stop = () => { if (!stopping) { diff --git a/apps/web/staticFiles.ts b/apps/web/staticFiles.ts index 3deeda87..cc1a0cee 100644 --- a/apps/web/staticFiles.ts +++ b/apps/web/staticFiles.ts @@ -3,7 +3,6 @@ import fs from 'node:fs'; import path from 'node:path'; import type http from 'node:http'; import zlib from 'node:zlib'; -import { nativeWeb } from './nativeWeb'; /** * Built workbench files, read once per change and kept in memory with their compressed forms. Text is sent as Brotli or @@ -109,22 +108,6 @@ export function sendStatic( } export function createStaticResponder(root: string) { - const native = nativeWeb(); - if (native) { - const files = new native.WorkbenchStatic(); - return (request: http.IncomingMessage, response: http.ServerResponse, relative: string) => { - const reply = files.serve( - root, - relative, - request.headers['accept-encoding'] ?? '', - String(request.headers['if-none-match'] ?? ''), - request.method === 'HEAD', - ); - if (reply.error) return reply.error; - response.writeHead(reply.status, reply.headers); - response.end(reply.body); - }; - } return (request: http.IncomingMessage, response: http.ServerResponse, relative: string) => { const file = path.resolve(root, relative); if (!file.startsWith(root + path.sep) || !fs.existsSync(file) || !fs.lstatSync(file).isFile()) diff --git a/apps/web/storage.ts b/apps/web/storage.ts index 2c20507f..54a29a2e 100644 --- a/apps/web/storage.ts +++ b/apps/web/storage.ts @@ -1,5 +1,4 @@ import fs from 'node:fs'; -import { nativeWeb } from './nativeWeb'; import path from 'node:path'; import crypto from 'node:crypto'; import { canonicalMathJson, mathDigest, syncMathDirectory, writeMathFrozen } from '../../src/math/mathRuntimeIo'; @@ -308,13 +307,6 @@ export class WebStorage { saveRun(owner: string, run: WebRun, creation?: WebCreation): void { const directory = this.runPath(owner, run.id); - const native = this.root && nativeWeb(); - if (native && this.root) { - const { observation, ...summary } = run; - if (observation) this.saveObservation(owner, observation); - native.persistRun(this.root, owner, summary, observation?.sequence, creation); - return; - } this.saveRecord([...this.ownerPath(owner), 'owner.json'], { owner }, true); if (run.observation) this.saveObservation(owner, run.observation); for (const event of run.events) this.saveRecord([...directory, 'events', `${event.sequence}.json`], event, true); diff --git a/apps/web/worker.ts b/apps/web/worker.ts index ce624f6b..2b746ab6 100644 --- a/apps/web/worker.ts +++ b/apps/web/worker.ts @@ -13,7 +13,6 @@ import { isMathPathWithin } from '../../src/math/paths'; import { sub2apiModelCatalog } from '../../src/runtime/sub2api'; import { configurableRuntimeModules, type RuntimeSolverModules } from '../../src/solver/modules/runtime'; import { solverModuleConfiguration } from '../../src/solver/modules/moduleIdentity'; -import { researchWorkers } from '../../src/solver/modules/organization'; import { readSolverProblem } from '../../src/solver/problem'; import { runSolver } from '../../src/solver/run'; import { readKnowledgeCatalog } from '../../src/solver/theoremKnowledgeStore'; @@ -40,11 +39,10 @@ import { webHarnessResearchError } from './harness'; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..'); type WebWorkerState = { worktree: string; - workers?: { id: string; worktree: string }[]; check?: { passed: boolean; verification?: { status?: string; results?: Record[] } }; }; -function readCandidateSource(directory: string, file: string): { source: string; modifiedAt: number } | undefined { +function readCandidateSource(directory: string, file: string): string | undefined { let descriptor: number | undefined; try { if (!file.startsWith(directory + path.sep)) return; @@ -85,10 +83,7 @@ function readCandidateSource(directory: string, file: string): { source: string; openedPath() !== file ) return; - return { - source: new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(0, bytes)), - modifiedAt: after.mtimeMs, - }; + return new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(0, bytes)); } catch { return undefined; } finally { @@ -99,33 +94,27 @@ function readCandidateSource(directory: string, file: string): { source: string; export function createWebArtifactSampler(options: { directory: string; output: string; - workers: number; source: string; apiKey: string; onArtifact(artifact: WebArtifact): void; }) { const directory = fs.realpathSync(options.directory); - const workers = researchWorkers(path.join(options.output + '.runtime', 'worktree'), [], options.workers); - const previous = new Map(workers.map(worker => [worker.id, options.source])); + const file = path.join(`${options.output}.runtime`, 'worktree', 'generated/problem/Submission.lean'); let lastSource = options.source; - return () => { - let latest: { workerId: string; source: string; modifiedAt: number } | undefined; - for (const worker of workers) { - const candidate = readCandidateSource(directory, path.join(worker.worktree, 'generated/problem/Submission.lean')); - if (!candidate || candidate.source === previous.get(worker.id)) continue; - previous.set(worker.id, candidate.source); - if (!latest || candidate.modifiedAt >= latest.modifiedAt) latest = { ...candidate, workerId: worker.id }; - } - if (!latest || latest.source === lastSource) return; - const source = options.apiKey ? latest.source.replaceAll(options.apiKey, '[REDACTED]') : latest.source; - if (Buffer.byteLength(source) > webArtifactMaxBytes) return; - lastSource = latest.source; - options.onArtifact({ - source, - workerId: latest.workerId, - capturedAt: new Date().toISOString(), - status: 'candidate', - }); + let latest: WebArtifact | undefined; + return { + get latest() { + return latest; + }, + sample() { + const candidate = readCandidateSource(directory, file); + if (candidate === undefined || candidate === lastSource) return; + const source = options.apiKey ? candidate.replaceAll(options.apiKey, '[REDACTED]') : candidate; + if (Buffer.byteLength(source) > webArtifactMaxBytes) return; + lastSource = candidate; + latest = { source, workerId: 'solver', capturedAt: new Date().toISOString(), status: 'candidate' }; + options.onArtifact(latest); + }, }; } @@ -133,18 +122,13 @@ export function readWebResultProof(options: { directory: string; workspace: string; status: unknown; - winningWorker: unknown; state?: WebWorkerState; artifact?: WebArtifact; }): string { const accepted = options.status === 'evaluated_passed'; - const selected = typeof options.winningWorker === 'string' && options.winningWorker.length > 0; - // A parallel attempt can finish before any winner exists while another worker has useful live source. - if (!accepted && !selected && !options.state?.check?.passed && options.artifact) return options.artifact.source; + if (!accepted && !options.state?.check?.passed && options.artifact) return options.artifact.source; if (!options.state) return ''; - const tree = accepted - ? options.workspace - : (options.state.workers?.find(worker => worker.id === options.winningWorker)?.worktree ?? options.state.worktree); + const tree = accepted ? options.workspace : options.state.worktree; const file = path.resolve(tree, 'generated/problem/Submission.lean'); if (file.startsWith(options.directory + path.sep)) { try { @@ -390,6 +374,22 @@ export function webSolverModules( }; } +/** Rejections before result publication must reach the worker's error handler. */ +export async function runWebProofSolver( + args: string[], + solverRoot: string, + modules?: RuntimeSolverModules, + signal?: AbortSignal, +): Promise { + let rejection: string | undefined; + await runSolver(args, solverRoot, modules, signal, { + onRejected: reason => { + rejection = reason; + }, + }); + if (rejection !== undefined) throw new Error(rejection); +} + async function main(watchdog: ReturnType, controlledStdin: boolean) { let bytes = 0; const chunks: Buffer[] = []; @@ -460,7 +460,7 @@ async function main(watchdog: ReturnType process.env.DEEPSCIENTIST_MATH_ENV_FILE = path.join(directory, 'math.env'); fs.writeFileSync(process.env.DEEPSCIENTIST_MATH_ENV_FILE, '', { mode: 0o400, flag: 'wx' }); const originalLog = console.log; - let sampleArtifact: (() => void) | undefined; + let artifactSampler: ReturnType | undefined; let observationTimer: ReturnType | undefined; let capturePending: Promise | undefined; const capture = (final = false) => @@ -478,7 +478,6 @@ async function main(watchdog: ReturnType .finally(() => { capturePending = undefined; })); - let latestArtifact: WebArtifact | undefined; let solverRunId: string | undefined; const forwardProgress = createWebProgressForwarder(send); console.log = (...args: unknown[]) => { @@ -491,7 +490,7 @@ async function main(watchdog: ReturnType if ( ['turn_checkpoint', 'proof_check_started', 'candidate_selected', 'evaluation_started'].includes(event.event) ) - sampleArtifact?.(); + artifactSampler?.sample(); } catch { /* Unstructured runtime output stays private to this disposable container. */ } @@ -521,7 +520,7 @@ async function main(watchdog: ReturnType receiptFile: receipt.activeProblemPath, }); observationTimer = setInterval(() => { - sampleArtifact?.(); + artifactSampler?.sample(); void capture(); }, 1_500); const buildState = path.dirname(path.dirname(path.dirname(buildIndex.buildManifestRef))); @@ -573,16 +572,12 @@ async function main(watchdog: ReturnType }; writeWebActiveRun(active, path.join(workspaceRoot, 'active-run.json')); bridge = createWebWorkerBridge({ ...active, apiKey: key, onMessage: send }); - sampleArtifact = createWebArtifactSampler({ + artifactSampler = createWebArtifactSampler({ directory, output, - workers: request.input.workers, source: request.input.source, apiKey: key, - onArtifact: artifact => { - latestArtifact = artifact; - send({ type: 'artifact', artifact }); - }, + onArtifact: artifact => send({ type: 'artifact', artifact }), }); if (round.round) send({ @@ -590,7 +585,7 @@ async function main(watchdog: ReturnType event: 'library_continuation_started', message: `已装入请求的库依赖,保留原题与研究材料,开始第 ${round.round + 1} 轮。`, }); - await runSolver( + await runWebProofSolver( [ '--workspace', round.seed.workspaceRoot, @@ -648,7 +643,7 @@ async function main(watchdog: ReturnType modules, watchdog.signal, ); - sampleArtifact(); + artifactSampler.sample(); await capturePending; await capture(true); }, @@ -719,9 +714,8 @@ async function main(watchdog: ReturnType directory, workspace: completed.seed.workspaceRoot, status: raw.status, - winningWorker: raw.winningWorker, state, - artifact: latestArtifact, + artifact: artifactSampler?.latest, }); send({ type: 'result', result: { status: String(raw.status || 'runtime_error'), proof, report } }); } catch (error) { diff --git a/bin/math-help.txt b/bin/math-help.txt index 4df19871..51fa90ca 100644 --- a/bin/math-help.txt +++ b/bin/math-help.txt @@ -16,7 +16,6 @@ theorem-os [arguments] hub Export frozen results and import private HuggingMath drafts check-lean Check changed Lean files with bounded diagnostics checkpoint Save the acknowledgment requested by the active host - plan-validate Check a cooperative Lead plan and report field-level issues check-finite Replay finite Boolean constraints and return witnesses kernel-certificate Generate chunked decide +kernel certificate modules library-pack Extract checked run modules or backport upstream files as a frozen library diff --git a/bin/math.ts b/bin/math.ts index 735fe6d6..a6f3f3a2 100644 --- a/bin/math.ts +++ b/bin/math.ts @@ -13,7 +13,6 @@ export const agentToolCommands = { 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', diff --git a/docs/usage.md b/docs/usage.md index b917899a..bb77bebb 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -202,7 +202,7 @@ bun run math inspect --run "$MATH_RUN_ROOT/result.json" \ 报告还会分别记录数学义务闭合、原题前沿变化、替代路线与局部障碍重开。局部阻塞、必需上下文与省略清单、`proofRoutes` 的 AND/OR 规则见[协作路线、上下文与数学进展](cooperative-proof-routes.md)。 -启用原生团队路线审批时,用 `inspect --format plan` 读取待审路线和版本,再用 `edit --run RESULT --approve-plan VERSION` 提交批准。旧宿主计划与证明导入记录仍可通过 `inspect --format json` 查看。复现旧任务图编辑(`plan-apply`)、证明导入(`import-proof`)和固定探路实验(`--portfolio-exploration`)时,使用对应历史版本。要把旧研究带入新运行,可以通过 `--continuation-source-run` 附入保存的源码和笔记,由新运行重新检查可用的 Lean 声明。 +启用原生团队路线审批时,用 `inspect --format plan` 读取待审路线和版本,再用 `edit --run RESULT --approve-plan VERSION` 提交批准。旧宿主计划与证明导入记录仍可通过 `inspect --format json` 查看。使用对应历史版本验证和编辑旧任务图(`plan-validate`、`plan-apply`)、导入证明(`import-proof`)或复现固定探路实验(`--portfolio-exploration`)。要把旧研究带入新运行,可以通过 `--continuation-source-run` 附入保存的源码和笔记,由新运行重新检查可用的 Lean 声明。 ### 6. 同时求解多道题 @@ -374,7 +374,6 @@ bun run math bootstrap-lean-eval --help | `build` | 构建求解器与检查 / 检索工具,生成构建清单 | | `doctor` | 检查工具、登录、沙箱和指定项目环境,支持 JSON 报告 | | `example` | 准备、回放或求解不依赖 Mathlib 的小型 Lean 题目 | -| `component` | 生成 M3 排序组件模板,检查基本任务约束 | | `bootstrap-imo` | 从固定公开提交准备 IMO2026 题目 | | `bootstrap-lean-eval` | 准备 Lean-Eval 题目与评测绑定;`--library-pack PACK` 安装冻结库模块 | | `first-proof` | 固定第三批 10 题,审核形式化后离线准备,汇总原始目标 S3 证据;见 [First Proof 接入](../examples/first-proof/README.md) | @@ -453,7 +452,7 @@ bun run math check-lean \ [index.ts](../src/solver/modules/index.ts) 记录模块契约和版本。宿主继续执行源码边界检查、总预算限制和独立验收。S2 跨任务学习尚未实现。 -历史 `--scheduler critical-path` 和 `--scheduler continuation` 用于比较两种固定任务选择策略。各实验记录保留模型、预算、模块版本和用量缺口。复现步骤见[三组对照实验](../examples/imo2026/COMPARISON.md)。 +新运行使用默认调度。Web 收到旧方案中的 `critical-path` 或 `continuation` 时,会按默认调度创建运行,保留原方案的上下文和自定义规则。历史实验记录仍保留原调度、模块版本和用量,可用固定版本[复现](../examples/imo2026/COMPARISON.md)。 Codex stdio 协议适配在 [codexSession.ts](../src/runtime/codexSession.ts)。 diff --git a/docs/web-workbench.md b/docs/web-workbench.md index 3e718346..a1a73841 100644 --- a/docs/web-workbench.md +++ b/docs/web-workbench.md @@ -357,7 +357,7 @@ Lean 标准库模板保留自然数加法和命题逻辑示例。网页默认 Ma ## 无模型费用的验证 -旧调度和模块编辑的浏览器检查使用迁移前的 TheoremOS 提交 `ef08987d6f686856c6fe9ecf86676ebbaa632546`。其中包括 `test:web-collaboration`、`test:web-plan-structure`、`test:web-collaboration-layers`、`test:web-preparation`、`test:web-module-plan`、`test:web-server-plans` 和 `test:web-drafts`。 +要复现旧调度和模块编辑的浏览器检查,请在迁移前的 TheoremOS 提交 `ef08987d6f686856c6fe9ecf86676ebbaa632546` 中运行。该版本保留 `test:web-collaboration`、`test:web-plan-structure`、`test:web-collaboration-layers`、`test:web-preparation`、`test:web-module-plan`、`test:web-server-plans` 和 `test:web-drafts`。 基础 worker 构建完成后,可执行: diff --git a/package.json b/package.json index 1c64e7f5..fcf8e619 100644 --- a/package.json +++ b/package.json @@ -57,11 +57,9 @@ "test:web-report": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-report.ts'", "test:web-onboarding": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-onboarding.ts'", "test:web-i18n": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-i18n.ts'", - "test:web-collaboration": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-collaboration.ts'", "test:web-task-source": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-task-source.ts'", "test:web-knowledge-context": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-knowledge-context.ts'", "test:web-plan-approval": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-plan-approval.ts'", - "test:web-plan-structure": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-plan-structure.ts'", "test:web-guidance-recovery": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-guidance-recovery.ts'", "test:web-research-progress": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-research-progress.ts'", "test:web-research-information": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-research-information.ts'", @@ -75,11 +73,9 @@ "test:web-task-browser": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-task-browser.ts'", "test:web-interaction-flow": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-interaction-flow.ts'", "test:web-live-sync": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-live-sync.ts'", - "test:web-preparation": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-preparation.ts'", "test:web-recovery": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-recovery.ts'", "test:web-results": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-results.ts'", "test:web-continuation-archive": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-continuation-archive.ts'", - "test:web-drafts": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-drafts.ts'", "test:web-draft-recovery": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-draft-recovery.ts'", "test:web-run-monitor": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-run-monitor.ts'", "test:web-history": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-history.ts'", @@ -91,15 +87,12 @@ "test:web-source-handoff": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-source-handoff.ts'", "test:web-activity": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-activity.ts'", "test:web-modules": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-modules.ts'", - "test:web-module-plan": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-module-plan.ts'", - "test:web-server-plans": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-server-plans.ts'", "test:web-performance": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-performance.ts'", "test:web-motion": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-motion.ts'", "test:web-preview": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-preview.ts'", "test:web-a11y": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-a11y.ts'", "test:web-precheck": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-precheck.ts'", "test:web-readable-results": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-readable-results.ts'", - "test:web-collaboration-layers": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-collaboration-layers.ts'", "test:web-key-memory": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-key-memory.ts'", "test:web-saved-key": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-saved-key.ts'", "test:web-load": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-load.ts'", diff --git a/scripts/build-agent-tools.ts b/scripts/build-agent-tools.ts index 5fe5382a..ea4f10d6 100644 --- a/scripts/build-agent-tools.ts +++ b/scripts/build-agent-tools.ts @@ -26,6 +26,8 @@ export async function buildAgentTools( ): Promise { const { native } = options; const migrated = new Set(native ? execFileSync(native, ['--list'], { encoding: 'utf8' }).trim().split('\n') : []); + // Historical Rust dispatchers still advertise this host scheduling command. + migrated.delete('plan-validate'); 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}`); diff --git a/scripts/mathematics/autoLibrary.ts b/scripts/mathematics/autoLibrary.ts index d5b4a921..e78910ae 100644 --- a/scripts/mathematics/autoLibrary.ts +++ b/scripts/mathematics/autoLibrary.ts @@ -25,12 +25,7 @@ import { readLibraryPack, summarizeLibraryPack } from '../../src/math/libraryPac import { readMathBuildManifest } from '../../src/math/mathBuildManifest'; import { mathDigest, readMathText, writeMathJsonDurable } from '../../src/math/mathRuntimeIo'; import { assertMathCanonicalPath, isMathPathWithin } from '../../src/math/paths'; -import { - inspectAutoLibraryBuild, - prepareAutoLibraryBuild, - readAutoLibraryRequest, - runAutoLibraryBuild, -} from '../../src/solver/autoLibrary'; +import { inspectAutoLibraryBuild, prepareAutoLibraryBuild, runAutoLibraryBuild } from '../../src/solver/autoLibrary'; import { captureAutoLibraryDemand, readAutoLibraryDemand } from '../../src/solver/autoLibraryDemand'; import { readSolverRunState } from '../../src/solver/archive'; @@ -90,10 +85,9 @@ const readFile = (value: string, limit: number) => { function prepare(flags: ReadonlyMap, directory: string) { const workers = integerFlag(flags, 'workers', 1); - if (workers !== 1 || flags.get('coordination') === 'cooperative') - throw new Error( - 'New automatic library builds use one prover. Prepare legacy multi-worker builds from their pinned historical revision.', - ); + const coordination = flags.get('coordination') ?? 'independent'; + if (coordination !== 'cooperative' && coordination !== 'independent') + throw new Error('--coordination must be cooperative or independent'); const buildManifestRef = path.resolve(required(flags, 'build-manifest')); readMathBuildManifest(buildManifestRef, root, path.join(root, 'out/main')); const codex = flags.get('codex') ?? process.env.DEEPSCIENTIST_MATH_CODEX_EXECUTABLE ?? 'codex'; @@ -122,9 +116,6 @@ function prepare(flags: ReadonlyMap, directory: string) { undefined, 'prover-', ); - const coordination = flags.get('coordination') ?? 'independent'; - if (coordination !== 'cooperative' && coordination !== 'independent') - throw new Error('--coordination must be cooperative or independent'); const request = prepareAutoLibraryBuild(directory, root, { challengeId: required(flags, 'challenge-id'), challengeSource: readFile(required(flags, 'challenge-file'), LEAN_TASK_SOURCE_MAX_BYTES), @@ -327,7 +318,6 @@ export async function autoLibrary(argv: string[], nativeHost?: string): Promise< throw new Error('Use the migration/rust branch and the original build to replay a Rust library run.'); } else { const directory = externalPath(required(flags, 'directory')); - readAutoLibraryRequest(directory); const controller = new AbortController(), interrupt = () => controller.abort(); process.once('SIGINT', interrupt); diff --git a/scripts/mathematics/autoLibraryHostReplay.ts b/scripts/mathematics/autoLibraryHostReplay.ts index 829befb4..db62813a 100644 --- a/scripts/mathematics/autoLibraryHostReplay.ts +++ b/scripts/mathematics/autoLibraryHostReplay.ts @@ -67,7 +67,7 @@ export async function replayHostAutoLibrary(directory: string, host?: { configPa effort: 'none', executable: 'preset', workers: 1, - coordination: 'cooperative', + coordination: 'independent', maxRunSeconds: 300, maxTurns: 3, maxTurnSeconds: 120, diff --git a/scripts/mathematics/continuationSeedCommand.ts b/scripts/mathematics/continuationSeedCommand.ts index 6a770518..f390dc2d 100644 --- a/scripts/mathematics/continuationSeedCommand.ts +++ b/scripts/mathematics/continuationSeedCommand.ts @@ -1,7 +1,11 @@ import { parseFlags, required } from './arguments'; import { seedSingleSolverContinuation } from '../../src/solver/singleContinuationSeed'; -export async function continuationSeedCommand(argv: string[], root: string): Promise { +export async function continuationSeedCommand( + argv: string[], + root: string, + buildScope: 'runtime' | 'source' = 'source', +): Promise { const flags = parseFlags(argv, ['source-run', 'run', 'build-manifest', 'timeout-seconds']); if (flags.has('help')) console.log( @@ -19,6 +23,7 @@ export async function continuationSeedCommand(argv: string[], root: string): Pro sourceRun: required(flags, 'source-run'), run: required(flags, 'run'), buildManifest: required(flags, 'build-manifest'), + buildScope, root, signal: controller.signal, timeoutMs: timeout === 0 ? Infinity : timeout * 1000, diff --git a/scripts/mathematics/planCommand.ts b/scripts/mathematics/planCommand.ts deleted file mode 100644 index 2ec81d9a..00000000 --- a/scripts/mathematics/planCommand.ts +++ /dev/null @@ -1,63 +0,0 @@ -import fs from 'node:fs'; -import { parseArgs } from 'node:util'; -import { MAX_RESEARCH_NOTES_BYTES } from '../../src/solver/deliveries'; -import { validateCooperationPlanFile } from '../../src/solver/planTool'; - -function readStandardInput(): string { - const bytes = Buffer.alloc(MAX_RESEARCH_NOTES_BYTES + 1); - let length = 0; - while (length < bytes.length) { - const count = fs.readSync(0, bytes, length, bytes.length - length, null); - if (!count) break; - length += count; - } - if (length > MAX_RESEARCH_NOTES_BYTES) throw new Error('Keep the plan JSON at or below 1 MB.'); - return new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, length)); -} - -export function runPlanCommand(args: string[]): void { - const usage = 'theorem-os plan-validate [--file FILE] [--workspace DIR]'; - let field = 'arguments'; - try { - const { values } = parseArgs({ - args, - options: { - file: { type: 'string' }, - workspace: { type: 'string' }, - worktree: { type: 'string' }, - help: { type: 'boolean', short: 'h' }, - }, - }); - if (values.help) { - console.log( - JSON.stringify({ - usage, - description: - 'Read a complete plan or revision from --file or stdin. ' + - 'Use the Lead workspace with COOPERATION.json, or a prepared workspace with active-problem.json. ' + - 'Report validation issues.', - }), - ); - return; - } - if (values.worktree && values.workspace) throw new Error('Choose --workspace or --worktree.'); - const workspace = values.workspace ?? values.worktree ?? process.cwd(); - let input: { workspace: string; text: string } | { workspace: string; file: string }; - if (!values.file || values.file === '-') { - field = 'stdin'; - input = { workspace, text: readStandardInput() }; - } else input = { workspace, file: values.file }; - const result = validateCooperationPlanFile(input); - console.log(JSON.stringify(result)); - if (!result.ok) process.exitCode = 1; - } catch (error) { - console.log( - JSON.stringify({ - ok: false, - error: 'math_plan_cli_input_invalid', - issues: [{ path: field, message: error instanceof Error ? error.message : usage }], - }), - ); - process.exitCode = 1; - } -} diff --git a/scripts/mathematics/planValidate.ts b/scripts/mathematics/planValidate.ts deleted file mode 100644 index a899ccef..00000000 --- a/scripts/mathematics/planValidate.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { runPlanCommand } from './planCommand'; - -runPlanCommand(process.argv.slice(2)); diff --git a/scripts/mathematics/runMathProof.ts b/scripts/mathematics/runMathProof.ts index 9104d062..31e846c4 100644 --- a/scripts/mathematics/runMathProof.ts +++ b/scripts/mathematics/runMathProof.ts @@ -12,7 +12,7 @@ const owner = openResearchOwner(args[0]); if (owner) args.shift(); const operation = !owner && args[0] === '--theoremos-continuation-seed' - ? continuationSeedCommand(args.slice(1), root) + ? continuationSeedCommand(args.slice(1), root, 'runtime') : !owner && args[0] === '--theoremos-auto-replay' ? replayEffect(args.slice(1), root) : runSolver(args, root, undefined, undefined, 'cli', owner); diff --git a/src/math/mathBuildManifest.ts b/src/math/mathBuildManifest.ts index 281473e5..426d8b91 100644 --- a/src/math/mathBuildManifest.ts +++ b/src/math/mathBuildManifest.ts @@ -296,5 +296,20 @@ function verifyMathBuildManifest( } } assertMathBuildAgentTools(manifest); + if (manifest.schema === 'deepscientist.math.build-manifest.v4') { + // Native v4 builds package identical addons beside the solver and the agent tools. + const name = 'theoremos-process.node'; + const addon = manifest.agentTools.find( + entry => entry.path === path.join(bundleRoot, MATH_AGENT_TOOLS_DIRECTORY, name), + ); + const solverAddon = path.join(bundleRoot, name); + if ( + addon && + (!fs.existsSync(solverAddon) || + (fs.lstatSync(solverAddon).mode & 0o222) !== 0 || + !sameBuildBytes(addon, mathBuildFile(solverAddon))) + ) + throw new Error('math_build_artifact_changed'); + } return { manifest, bytes }; } diff --git a/src/solver/autoLibrary.ts b/src/solver/autoLibrary.ts index 562c3533..d6d55dc6 100644 --- a/src/solver/autoLibrary.ts +++ b/src/solver/autoLibrary.ts @@ -125,6 +125,13 @@ export const autoRequestSchema = z .strict(); export type AutoLibraryRequest = z.infer; +function assertIndependentProver(prover: AutoLibraryRequest['prover']): void { + if (prover.workers !== 1 || prover.coordination !== 'independent') + throw new Error( + 'Automatic library builds require one independent prover. Use the pinned historical revision for legacy builds.', + ); +} + /** Freeze one build: the triggering challenge, environment, hand library, pool, models and limits. */ export function prepareAutoLibraryBuild( directoryInput: string, @@ -134,6 +141,7 @@ export function prepareAutoLibraryBuild( 'schema' | 'buildId' | 'environmentDigest' | 'basePackDigest' | 'buildDigest' | 'libraryBinding' > & { basePack?: LibraryPack }, ): AutoLibraryRequest { + assertIndependentProver(input.prover); const directory = path.resolve(directoryInput), root = path.resolve(rootInput); assertMathCanonicalPath(directory); @@ -480,8 +488,9 @@ export async function runAutoLibraryBuild( assertMathCanonicalPath(directory); if (isMathPathWithin(root, directory) || isMathPathWithin(directory, root)) throw new Error('auto_library_directory_must_be_external'); - const { request, basePack } = readAutoLibraryRequest(directory), - requestDigest = mathDigest(canonicalMathJson(request)); + const { request, basePack } = readAutoLibraryRequest(directory); + assertIndependentProver(request.prover); + const requestDigest = mathDigest(canonicalMathJson(request)); const expectedBuild = { digest: request.buildDigest, mismatch: 'auto_library_build_changed' }; const assertBuildCurrent = () => readMathBuildManifestDigest(request.buildManifestRef, root, path.join(root, 'out/main'), undefined, 'source', { @@ -678,7 +687,7 @@ async function build(context: { }) : undefined; }; - const runArgs = (directoryOf: string, phase: 'check' | 'prove' | 'verify', extra: string[]) => [ + const runArgs = (directoryOf: string, extra: string[]) => [ '--workspace', path.join(directoryOf, 'workspace'), '--task-file', @@ -688,9 +697,9 @@ async function build(context: { '--build-manifest', request.buildManifestRef, '--workers', - String(phase === 'verify' ? 1 : request.prover.workers), + '1', '--coordination', - request.prover.coordination, + 'independent', '--model', request.prover.model, '--effort', @@ -1059,7 +1068,7 @@ async function build(context: { let result = readResult(output); if (result?.status !== 'prepared' && result?.reason !== 'math_statement_check_failed') { await context.solve( - runArgs(proveDirectory, 'check', [ + runArgs(proveDirectory, [ '--startup-only', '--check-statement', '--max-run-seconds', @@ -1100,7 +1109,7 @@ async function build(context: { (tokens === null || tokens > 0) ) { await context.solve( - runArgs(proveDirectory, 'prove', [ + runArgs(proveDirectory, [ '--resume', '--max-run-seconds', String(seconds ?? 0), @@ -1268,12 +1277,7 @@ async function build(context: { let result = readResult(output); if (result?.status !== 'prepared' && result?.reason !== 'math_library_pack_failed') { await context.solve( - runArgs(verifyDirectory, 'verify', [ - '--startup-only', - '--max-run-seconds', - '0', - ...resumeFlag(verifyDirectory), - ]), + runArgs(verifyDirectory, ['--startup-only', '--max-run-seconds', '0', ...resumeFlag(verifyDirectory)]), { phase: 'verify', module: module.index, round: round.round, name }, ); lease.signal.throwIfAborted(); @@ -1320,12 +1324,7 @@ async function build(context: { { mode: 0o400 }, ); await context.solve( - runArgs(consumerDirectory, 'verify', [ - '--startup-only', - '--max-run-seconds', - '0', - ...resumeFlag(consumerDirectory), - ]), + runArgs(consumerDirectory, ['--startup-only', '--max-run-seconds', '0', ...resumeFlag(consumerDirectory)]), { phase: 'verify', module: module.index, round: round.round, name }, ); if (readResult(path.join(consumerDirectory, 'result.json'))?.status !== 'prepared') diff --git a/src/solver/continuationSeed.ts b/src/solver/continuationSeed.ts index 004cc700..2948d5a2 100644 --- a/src/solver/continuationSeed.ts +++ b/src/solver/continuationSeed.ts @@ -11,6 +11,7 @@ export type ContinuationSeedOptions = { run: string; root: string; buildManifest: string; + buildScope?: 'runtime' | 'source'; signal: AbortSignal; timeoutMs?: number; onProgress?: (event: string, details: Record) => void; diff --git a/src/solver/modules/organization.ts b/src/solver/modules/organization.ts index 423cbcc5..b59ad4af 100644 --- a/src/solver/modules/organization.ts +++ b/src/solver/modules/organization.ts @@ -25,19 +25,3 @@ export function independentFeasibilityWorker( return input?.assignment?.workerId !== worker.id && input?.task.ownerId !== worker.id && engineerId !== worker.id; }); } - -export function researchWorkers(worktree: string, ownedFiles: readonly string[], count: number): ResearchWorker[] { - return Array.from({ length: count }, (_, index) => ({ - id: - index === 0 - ? 'solver' - : index === count - 1 - ? 'engineer' - : index <= 2 - ? `researcher-${index}` - : `prover-${index - 2}`, - role: index === 0 ? 'lead' : index === count - 1 ? 'engineer' : index <= 2 ? 'researcher' : 'prover', - worktree: index === 0 ? worktree : `${worktree}-${index + 1}`, - ownedFiles, - })); -} diff --git a/src/solver/modules/policy.ts b/src/solver/modules/policy.ts index c0251454..a7d9a769 100644 --- a/src/solver/modules/policy.ts +++ b/src/solver/modules/policy.ts @@ -89,3 +89,8 @@ export const researchModulePlanSchema = researchModulePlanDraftSchema.superRefin export function defaultResearchModulePlan(): ResearchModulePlan { return { scheduler: 'plan', context: 'full', custom: [] }; } + +/** Old presets remain readable. All new runs use the one implemented scheduler. */ +export function currentResearchModulePlan(plan: ResearchModulePlan): ResearchModulePlan { + return plan.scheduler === 'plan' ? plan : { ...plan, scheduler: 'plan' }; +} diff --git a/src/solver/planTool.ts b/src/solver/planTool.ts deleted file mode 100644 index 6c144d3e..00000000 --- a/src/solver/planTool.ts +++ /dev/null @@ -1,123 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { canonicalMathJson, mathDigest, readMathText } from '../math/mathRuntimeIo'; -import { assertMathCanonicalPath } from '../math/paths'; -import { leadPlanPublicationTarget, parseLeadPlan } from './cooperationShared'; -import { MAX_RESEARCH_NOTES_BYTES } from './deliveries'; -import type { GoalPathReview } from './goalPathReview'; -import { invalidPlanField, PlanValidationError, type PlanIssue } from './planDiagnostics'; -import { liftNestedPlanPatch, type PlanPatchBase } from './planPatch'; -import { readSolverProblem } from './problem'; -import type { CooperationPlanProblem } from './tasks'; - -/** Lead-only snapshot. The running host still validates every proposal against live state. */ -export type PlanToolContext = { - problem: CooperationPlanProblem; - base?: PlanPatchBase; - goalPath?: GoalPathReview; - publication?: ReturnType; -}; -type PlanValidation = { - ok: true; - planVersion: string; - baseVersion?: string; - summary: string; - tasksCount: number; - groupsCount: number; - retireRoutesCount: number; -}; -type PlanFailure = { ok: false; error: string; issues: PlanIssue[] }; -type PlanInput = { workspace: string; file: string } | { workspace: string; text: string }; - -function failure(error: unknown, field = '$'): PlanFailure { - if (error instanceof PlanValidationError) return { ok: false, error: error.code, issues: error.issues }; - const message = error instanceof Error ? error.message : 'Could not read the plan.'; - return { - ok: false, - error: /^math_[\w-]+/u.exec(message)?.[0] ?? 'math_plan_tool_failed', - issues: [{ path: field, message }], - }; -} - -function validated(value: unknown, context: PlanToolContext) { - const candidate = liftNestedPlanPatch(value); - if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) - throw invalidPlanField('math_plan_invalid', '$', 'Supply one JSON object containing a complete plan or revision.'); - const plan = parseLeadPlan(context.problem, candidate, context.base, { goalPath: context.goalPath }); - const result: PlanValidation = { - ok: true, - planVersion: mathDigest(canonicalMathJson(plan)), - baseVersion: context.base?.version, - summary: `Validated ${plan.tasks.length} tasks in ${plan.groups.length} groups.`, - tasksCount: plan.tasks.length, - groupsCount: plan.groups.length, - retireRoutesCount: plan.retireRoutes?.length ?? 0, - }; - return result; -} - -export function validateCooperationPlan(value: unknown, context: PlanToolContext): PlanValidation | PlanFailure { - try { - return validated(value, context); - } catch (error) { - return failure(error); - } -} - -function readCandidate(input: PlanInput): unknown { - let text: string; - try { - text = 'text' in input ? input.text : readMathText(input.file, MAX_RESEARCH_NOTES_BYTES); - } catch { - throw invalidPlanField('math_plan_file_unreadable', '--file', 'Use a readable regular JSON file of at most 1 MB.'); - } - if (Buffer.byteLength(text) > MAX_RESEARCH_NOTES_BYTES) - throw invalidPlanField('math_plan_file_too_large', '--file', 'Keep the plan JSON at or below 1 MB.'); - try { - return JSON.parse(text); - } catch (error) { - throw invalidPlanField( - 'math_plan_json_invalid', - '$', - 'Supply JSON without Markdown fences. ' + (error instanceof Error ? error.message : 'Invalid JSON.'), - ); - } -} - -function workspacePlanContext(worktree: string): PlanToolContext { - const cooperationFile = path.join(worktree, 'COOPERATION.json'); - assertMathCanonicalPath(cooperationFile); - if (fs.existsSync(cooperationFile)) { - const cooperation = JSON.parse(readMathText(cooperationFile, 32_000_000)) as { planTool?: PlanToolContext }; - if (cooperation.planTool) return cooperation.planTool; - throw invalidPlanField( - 'math_plan_workspace_context_missing', - '--workspace', - 'Run this command in the cooperative Lead worktree with its current COOPERATION.json.', - ); - } - const receipt = path.join(worktree, 'active-problem.json'); - assertMathCanonicalPath(receipt); - if (!fs.existsSync(receipt)) - throw invalidPlanField( - 'math_plan_workspace_context_missing', - '--workspace', - 'Use the cooperative Lead worktree or a prepared workspace containing active-problem.json.', - ); - return { problem: readSolverProblem(worktree, receipt) }; -} - -function prepare(input: PlanInput) { - const candidate = readCandidate(input); - const worktree = fs.realpathSync(input.workspace); - assertMathCanonicalPath(worktree); - return validated(candidate, workspacePlanContext(worktree)); -} - -export function validateCooperationPlanFile(input: PlanInput): PlanValidation | PlanFailure { - try { - return prepare(input); - } catch (error) { - return failure(error); - } -} diff --git a/src/solver/run.ts b/src/solver/run.ts index dec7953d..570eb531 100644 --- a/src/solver/run.ts +++ b/src/solver/run.ts @@ -114,10 +114,15 @@ export async function runSolver( root: string, customModules?: RuntimeSolverModules, hostSignal?: AbortSignal, - launch: 'internal' | 'cli' | { expectedBuild: { digest: string; mismatch: string }; leanOnly: boolean } = 'internal', + launch: + | 'internal' + | 'cli' + | { expectedBuild: { digest: string; mismatch: string }; leanOnly: boolean } + | { onRejected: (reason: string) => void } = 'internal', owner?: { drive: ResearchDriver; lockDescriptor: number; conclude: typeof concludeRun }, ): Promise { - const autoLibrary = typeof launch === 'object' ? launch : undefined; + const autoLibrary = typeof launch === 'object' && 'expectedBuild' in launch ? launch : undefined; + const onRejected = typeof launch === 'object' && 'onRejected' in launch ? launch.onRejected : undefined; const entryPoint = typeof launch === 'string' ? launch : 'internal'; const values = parseRunOptions(args, entryPoint); if (values.help) { @@ -169,6 +174,11 @@ export async function runSolver( ); return 0; } + const requireCurrentScheduler = (scheduler: string) => { + if (!values.resume && (scheduler === 'critical-path' || scheduler === 'continuation')) + throw new Error('math_scheduler_retired: omit --scheduler or use plan for new runs.'); + }; + requireCurrentScheduler(values.scheduler!); const specified = (key: string) => args.some(arg => arg === '--' + key || arg.startsWith('--' + key + '=')); const publicRun = entryPoint !== 'internal'; let savedConfiguration: SolverRunState | undefined; @@ -187,15 +197,15 @@ export async function runSolver( const options = resolveRunStrategy(strategyValues, savedConfiguration, specified('model'), Boolean(customModules)); values.model = options.model; const { coordination, researchMode, skillLoading, delegationMode, maxAgents } = options; + if (publicRun && values.workers === '1' && delegationMode === 'team') + throw new Error('--workers 1 requires a solo run. Use --agent-team N for a new team or omit --workers on resume.'); const skillMode = researchMode === 'skill'; const configured = configuredRuntimeModules(values.method!, values.scheduler!); - const modules = values['module-plan'] - ? configurableRuntimeModules( - researchModulePlanSchema.parse(readMathJson(values['module-plan'])) as ResearchModulePlan, - coordination, - 1, - ) - : (customModules ?? configured); + const modulePlan = + values['module-plan'] && + (researchModulePlanSchema.parse(readMathJson(values['module-plan'])) as ResearchModulePlan); + if (modulePlan) requireCurrentScheduler(modulePlan.scheduler); + const modules = modulePlan ? configurableRuntimeModules(modulePlan, coordination, 1) : (customModules ?? configured); const required = (key: keyof typeof values): string => { const value = values[key]; if (typeof value !== 'string' || !value.trim()) throw new Error(`--${key} is required`); @@ -233,8 +243,9 @@ export async function runSolver( let ownedState: SolverRunState | undefined; let proofEnvironment: Awaited> | undefined; let continuationSeeding = false; - let continuationSourceRun = + const requestedContinuationSource = values['continuation-source-run'] && continuationSourceStateFile(values['continuation-source-run']); + let continuationSourceRun = requestedContinuationSource; let ownsRun = false; let publishedExit: number | undefined; const emit = (event: string, details = {}) => @@ -252,6 +263,11 @@ export async function runSolver( : {}), }), ); + const reportRejection = (error: unknown) => { + const reason = error instanceof Error ? error.message : 'math_runtime_error'; + emit('rejected', { reason, ...(error instanceof MathGitError ? { git: error.diagnostic } : {}) }); + onRejected?.(reason); + }; const disposeProofEnvironment = async () => { const environment = proofEnvironment; proofEnvironment = undefined; @@ -309,7 +325,7 @@ export async function runSolver( : undefined; let continuation: ContinuationSnapshot | undefined; const worktree = path.join(directory, 'worktree'); - const profileArgument = values['harness-profile'] ?? savedConfiguration?.agentHarness?.profile; + const profileArgument = values['harness-profile'] ?? resumedState?.agentHarness?.profile; const profile = profileArgument ? fs.realpathSync(profileArgument) : process.env.CODEX_HOME || path.join(os.homedir(), '.config/deepscientist/math-sol-codex'); @@ -326,14 +342,15 @@ export async function runSolver( const executable = values['harness-executable'] ?? values.codex ?? - savedConfiguration?.agentHarness?.executable ?? + resumedState?.agentHarness?.executable ?? (nativeTeamRun ? process.env.THEOREMOS_CODEX_BACKEND_EXECUTABLE || path.join(root, 'out/codex-backend/codex') : process.env.DEEPSCIENTIST_MATH_CODEX_EXECUTABLE || 'codex'); const pinHarness = + (publicRun && !values.resume && specified('codex')) || specified('harness-executable') || specified('harness-profile') || - Boolean(savedConfiguration?.agentHarness) || + Boolean(resumedState?.agentHarness) || nativeTeamRun; const agentHarness = pinHarness ? bindResearchHarness('codex', executable, profile) : undefined; const assertHarnessCurrent = agentHarness ? () => assertResearchHarnessCurrent(agentHarness) : undefined; @@ -484,13 +501,15 @@ export async function runSolver( state = resumedState!; if (values['no-original-tactics'] && state.originalTacticsEnabled) throw new Error('math_resume_original_tactics_changed'); - if ( - continuationSourceRun && - state.pendingContinuationSource && - continuationSourceRun !== continuationSourceStateFile(state.pendingContinuationSource) - ) - throw new Error('math_resume_continuation_changed'); - continuationSourceRun ??= state.pendingContinuationSource; + const canContinueSeed = + state.phase === 'prepared' && + state.turns === 0 && + state.solveStartedAt === undefined && + state.solveFinishedAt === undefined; + continuationSourceRun = + canContinueSeed && state.pendingContinuationSource + ? continuationSourceStateFile(state.pendingContinuationSource) + : undefined; assertAgentTeamProcessesStopped(state); const frozen = frozenRunConfiguration(state, { agentHarness, @@ -518,6 +537,12 @@ export async function runSolver( if (continuationInput && continuationInput.digest !== state.continuationDigest) throw new Error('math_resume_continuation_changed'); } else if (continuationInput) throw new Error('math_resume_continuation_changed'); + // A repeated flag may identify an interrupted seed or a seed that already finished in startup-only mode. + const frozenContinuationSource = + continuationSourceRun ?? + continuation?.manifest.attachments.find(item => item.id === 'seed-canonical')?.provenance.source; + if (requestedContinuationSource && requestedContinuationSource !== frozenContinuationSource) + throw new Error('math_resume_continuation_changed'); // Use the current authoritative receipt instead of trusting nested archived source policy. state.problem = problem; leadSkill = prepareSkill(state.worktree); @@ -539,11 +564,18 @@ export async function runSolver( !solverProofIsCurrent(state.problem, workspace, state.check) ) throw new Error('math_resume_completed_proof_changed'); - if (result.status === 'evaluated_passed') await explainAccepted(state, result, state.worktree); + if (result.status === 'evaluated_passed' && !values['startup-only']) + await explainAccepted(state, result, state.worktree); return result.status === 'evaluated_passed' ? 0 : 2; } } if (codexWestlake && nativeTeamRun) throw new Error(westlakeTeamError); + // Older runtimes could record a new seed request on a run that was already underway. + if (state.pendingContinuationSource && !continuationSourceRun) { + delete state.pendingContinuationSource; + lease.assertOwned(); + writeSolverRunState(stateFile, state); + } } else { if (fs.existsSync(stateFile) || fs.existsSync(output)) throw new Error('math_run_exists_use_resume'); if (git(workspace, ['status', '--porcelain', '--untracked-files=no'])) @@ -882,14 +914,13 @@ export async function runSolver( return prepareAccess(accessId, workerWorktree, workerProject, workerCorpusFile, prepareSkill(workerWorktree)); }; if (continuationSourceRun) { - state.pendingContinuationSource = continuationSourceRun; - save(); continuationSeeding = true; await seedSingleSolverContinuation({ sourceRun: continuationSourceRun, run: stateFile, root, buildManifest: buildFile, + buildScope: 'runtime', signal, lease, preparedEnvironment: env, @@ -1042,10 +1073,7 @@ export async function runSolver( /* The original failure controls the checkpoint. */ } if (!ownsRun) { - emit('rejected', { - reason: error instanceof Error ? error.message : 'math_runtime_error', - ...(error instanceof MathGitError ? { git: error.diagnostic } : {}), - }); + reportRejection(error); return 1; } lease.assertOwned(); @@ -1120,7 +1148,7 @@ export async function runSolver( } catch (error) { // The lease has ended. A cancelled operation can already have published its final checkpoint. if (publishedExit !== undefined) return publishedExit; - emit('rejected', { reason: error instanceof Error ? error.message : 'math_runtime_error' }); + reportRejection(error); return controller.signal.aborted ? 4 : 1; } finally { executionClock?.stop(); diff --git a/src/solver/singleContinuationSeed.ts b/src/solver/singleContinuationSeed.ts index 547bdd82..ace38d89 100644 --- a/src/solver/singleContinuationSeed.ts +++ b/src/solver/singleContinuationSeed.ts @@ -2,7 +2,7 @@ import { nativeProcess } from '../math/nativeProcess'; import fs from 'node:fs'; import path from 'node:path'; import { z } from 'zod'; -import { readMathBuildManifest } from '../math/mathBuildManifest'; +import { readMathBuildManifestDigest } from '../math/mathBuildManifest'; import { bindLeanPackages } from '../math/leanDiagnostics'; import { MATH_PROOF_ENVIRONMENT_ENV, @@ -631,9 +631,14 @@ export async function seedSingleSolverContinuation(options: ContinuationSeedOpti throw new Error('math_research_skill_changed'); pinSolverResearchSkill(state.problem, state.worktree, skill); const buildFile = fs.realpathSync(options.buildManifest); - readMathBuildManifest(buildFile, options.root, path.join(options.root, 'out', 'main')); - if (mathDigest(readMathFile(buildFile).bytes) !== state.buildDigest) - throw new Error('math_continuation_seed_build_changed'); + const buildDigest = readMathBuildManifestDigest( + buildFile, + options.root, + path.join(options.root, 'out', 'main'), + undefined, + options.buildScope ?? 'source', + ); + if (buildDigest !== state.buildDigest) throw new Error('math_continuation_seed_build_changed'); let source: SingleSource; if (seeded) { assertMathCanonicalPath(sourceFile); diff --git a/tests/agentTools.test.ts b/tests/agentTools.test.ts index 76ffef1d..da15e39f 100644 --- a/tests/agentTools.test.ts +++ b/tests/agentTools.test.ts @@ -20,7 +20,6 @@ const commands = [ 'knowledge', 'library', 'checkpoint', - 'plan-validate', 'search-lean', ]; const fixture = path.resolve('examples/finite/old-b1-nine-constraints.json'); diff --git a/tests/autoLibraryCli.test.ts b/tests/autoLibraryCli.test.ts index a9efba00..6f3c9a7b 100644 --- a/tests/autoLibraryCli.test.ts +++ b/tests/autoLibraryCli.test.ts @@ -93,6 +93,16 @@ afterEach(() => { }); describe('auto-library CLI entry points', () => { + it.each([ + ['workers', 'one', '--workers must be an integer'], + ['coordination', 'parallel', '--coordination must be cooperative or independent'], + ])('reports a malformed --%s option before preparing a request', async (flag, value, message) => { + await expect( + autoLibrary(['--phase', 'prepare', '--directory', path.join(directory, 'build'), `--${flag}`, value]), + ).rejects.toThrow(message); + expect(host.prepare).not.toHaveBeenCalled(); + }); + 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'), diff --git a/tests/autoLibraryHost.test.ts b/tests/autoLibraryHost.test.ts index 3ab155dc..a457ee0d 100644 --- a/tests/autoLibraryHost.test.ts +++ b/tests/autoLibraryHost.test.ts @@ -610,6 +610,37 @@ describe('host-authorized Auto composition', () => { }); describe('Auto request and recovery', () => { + it.each([{ workers: 2 }, { coordination: 'cooperative' as const }])( + 'keeps a historical %j request inspectable and rejects it before opening a planner', + async legacy => { + vi.stubEnv('THEOREMOS_LIBRARY_HOST_CONFIG', undefined); + const { build, root, input, request } = prepare(); + const replacement = path.join(directory, 'replacement'); + const prover = { ...request.prover, ...legacy }; + expect(() => prepareAutoLibraryBuild(replacement, root, { ...input, prover })).toThrow( + 'require one independent prover', + ); + expect(fs.existsSync(replacement)).toBe(false); + + const historical = { ...request, prover }; + const file = path.join(build, 'request.json'); + fs.chmodSync(file, 0o600); + fs.writeFileSync(file, canonicalMathJson(historical)); + fs.chmodSync(file, 0o400); + expect(readAutoLibraryRequest(build).request).toEqual(historical); + expect(inspectAutoLibraryBuild(build)).toEqual({ directory: build, status: 'prepared' }); + + const openSession = vi.fn(); + const solve = vi.fn(); + await expect(runAutoLibraryBuild(build, root, { openSession, solve })).rejects.toThrow( + 'pinned historical revision', + ); + expect(openSession).not.toHaveBeenCalled(); + expect(solve).not.toHaveBeenCalled(); + expect(fs.readdirSync(build)).toEqual(['request.json']); + }, + ); + it('freezes the effective base and authenticates request bytes independently', () => { const { build, request } = prepare(); expect(readAutoLibraryRequest(build).request).toEqual(request); @@ -641,6 +672,8 @@ describe('Auto request and recovery', () => { const { build, root } = prepare({ model: 'fixture', executable, agentHarness }); const openSession = planPortable; const solve = vi.fn(async (args: string[]) => { + expect(args[args.indexOf('--workers') + 1]).toBe('1'); + expect(args[args.indexOf('--coordination') + 1]).toBe('independent'); expect(args).toContain('--harness'); expect(args[args.indexOf('--harness') + 1]).toBe('codex'); expect(args[args.indexOf('--harness-profile') + 1]).toBe(profile); diff --git a/tests/moduleExperiment.test.ts b/tests/moduleExperiment.test.ts index aafdf13f..4357147c 100644 --- a/tests/moduleExperiment.test.ts +++ b/tests/moduleExperiment.test.ts @@ -206,10 +206,14 @@ describe('CLI module-plan boundary', () => { expect(fs.readdirSync(directory)).toEqual(['module-plan.json']); }); - it('rejects a conflicting scheduler before reading a module plan', async () => { - await expect(runSolver(['--module-plan', '/unused.json', '--scheduler', 'critical-path'], root)).rejects.toThrow( - '--module-plan requires', - ); + it.each(['critical-path', 'continuation'])('rejects the retired %s scheduler for new runs', async scheduler => { + await expect(runSolver(['--scheduler', scheduler], root)).rejects.toThrow('math_scheduler_retired'); + + const directory = temporary(), + file = path.join(directory, 'module-plan.json'); + fs.writeFileSync(file, JSON.stringify({ ...example().variants[0].plan, scheduler })); + await expect(runSolver(['--module-plan', file], root)).rejects.toThrow('math_scheduler_retired'); + expect(fs.readdirSync(directory)).toEqual(['module-plan.json']); }); it('rejects the removed lemma method', async () => { diff --git a/tests/singleContinuationSeed.test.ts b/tests/singleContinuationSeed.test.ts index ef037739..fe6cfeb0 100644 --- a/tests/singleContinuationSeed.test.ts +++ b/tests/singleContinuationSeed.test.ts @@ -30,7 +30,7 @@ import { researchSkillIdentity } from '../src/solver/researchSkill'; const host = vi.hoisted(() => ({ verify: vi.fn(), build: vi.fn() })); vi.mock('../src/math/mathBuildManifest', async original => ({ ...(await original()), - readMathBuildManifest: host.build, + readMathBuildManifestDigest: host.build, })); vi.mock('../src/math/verifier', async original => ({ ...(await original()), @@ -267,7 +267,7 @@ function fixture(keyword = 'lemma', localPackages = false, bare = false) { } beforeEach(() => { - host.build.mockReset(); + host.build.mockReset().mockImplementation((file: string) => mathDigest(fs.readFileSync(file))); host.verify .mockReset() .mockImplementation((request: MathematicsVerifierBatchRequest) => diff --git a/tests/skillSolver.test.ts b/tests/skillSolver.test.ts index 74d1697b..0e4054cb 100644 --- a/tests/skillSolver.test.ts +++ b/tests/skillSolver.test.ts @@ -13,6 +13,8 @@ import { localExample } from './helpers/solver'; import { bindResearchHarness } from '../src/runtime/researchHarness'; import { prepareWestlakeProfile } from '../src/runtime/westlake'; import * as connectivity from '../src/runtime/codexConnectivity'; +import * as buildManifest from '../src/math/mathBuildManifest'; +import { mathDigest } from '../src/math/mathRuntimeIo'; vi.mock('../src/math/mathBuildManifest', async original => ({ ...(await original()), @@ -110,6 +112,89 @@ describe('opt-in skill research CLI and pinned identity', () => { expect(state()).toMatchObject({ runId: saved.runId, compactSoloResearch: true, savedEditChecks: true, turns: 0 }); }); + it('freezes an explicit solo --codex selection and can still resume an unbound historical run', async () => { + const profile = path.join(example.directory, 'offline-profile'); + fs.mkdirSync(profile); + vi.stubEnv('CODEX_HOME', profile); + const solo = [...args, '--workers', '1']; + const explicit = [...solo, `--codex=${process.execPath}`]; + expect(await runSolver(explicit, root, modules, undefined, 'cli')).toBe(0); + const saved = state(); + expect(saved.agentHarness).toMatchObject({ profile, executable: fs.realpathSync(process.execPath) }); + vi.stubEnv('DEEPSCIENTIST_MATH_CODEX_EXECUTABLE', '/missing-codex'); + expect(await runSolver([...solo, '--resume'], root, modules, undefined, 'cli')).toBe(0); + expect(state().agentHarness).toEqual(saved.agentHarness); + + delete saved.agentHarness; + writeSolverRunState(output + '.runtime/state.json', saved); + expect(await runSolver([...explicit, '--resume'], root, modules, undefined, 'cli')).toBe(0); + expect(state().agentHarness).toBeUndefined(); + expect(open).not.toHaveBeenCalled(); + }); + + it('rejects a newly supplied continuation seed on resume without changing the saved run', async () => { + const solo = [...args, '--workers', '1']; + expect(await runSolver(solo, root, modules, undefined, 'cli')).toBe(0); + const stateFile = output + '.runtime/state.json'; + writeSolverRunState(stateFile, { ...state(), phase: 'finished', turns: 1 }); + const original = fs.readFileSync(stateFile); + const previousResult = fs.readFileSync(output); + expect( + await runSolver( + [...solo, '--resume', '--continuation-source-run', path.join(example.directory, 'old.json')], + root, + modules, + undefined, + 'cli', + ), + ).toBe(1); + rejected('math_resume_continuation_changed'); + expect(fs.readFileSync(stateFile)).toEqual(original); + expect(fs.readFileSync(output)).toEqual(previousResult); + + // Older versions saved the unsupported seed request before failing the resume. + const staleSource = path.join(example.directory, 'old.json.runtime/state.json'); + writeSolverRunState(stateFile, { ...state(), pendingContinuationSource: staleSource }); + expect( + await runSolver([...solo, '--resume', '--continuation-source-run', staleSource], root, modules, undefined, 'cli'), + ).toBe(1); + expect(state().pendingContinuationSource).toBe(staleSource); + expect(await runSolver([...solo, '--resume'], root, modules, undefined, 'cli')).toBe(0); + expect(state().pendingContinuationSource).toBeUndefined(); + expect(open).not.toHaveBeenCalled(); + }); + + it('resumes a native team seed from the same path both before and after the seed completes', async () => { + vi.spyOn(buildManifest, 'readMathBuildManifestDigest').mockImplementation(file => + mathDigest(fs.readFileSync(file)), + ); + const profile = path.join(example.directory, 'offline-profile'); + fs.mkdirSync(profile); + vi.stubEnv('CODEX_HOME', profile); + const sourceOutput = path.join(example.directory, 'old.json'); + const sourceStateFile = `${sourceOutput}.runtime/state.json`; + const seed = [...args, '--continuation-source-run', sourceOutput]; + // The first attempt cannot capture a source until its state file exists. + expect(await runSolver(seed, root, modules, undefined, 'cli')).toBe(1); + expect(state()).toMatchObject({ phase: 'prepared', pendingContinuationSource: sourceStateFile, turns: 0 }); + + const source = args.map(arg => (arg === output ? sourceOutput : arg)); + expect(await runSolver(source, root, modules, undefined, 'cli')).toBe(0); + const resume = [...args, '--resume', '--continuation-source-run']; + expect(await runSolver([...resume, sourceStateFile], root, modules, undefined, 'cli')).toBe(0); + const seeded = state(); + expect(seeded).toMatchObject({ + agentTeam: { transport: 'native-agent-control' }, + continuationDigest: expect.any(String), + phase: 'prepared', + turns: 0, + }); + expect(seeded.pendingContinuationSource).toBeUndefined(); + expect(await runSolver([...resume, sourceOutput], root, modules, undefined, 'cli')).toBe(0); + expect(state().continuationDigest).toBe(seeded.continuationDigest); + expect(open).not.toHaveBeenCalled(); + }); + it('accepts a missing historical method digest on resume only with default module objects', async () => { vi.spyOn(connectivity, 'checkCodexProviderConnectivity').mockResolvedValue({ status: 'reachable' }); const profile = path.join(example.directory, 'offline-profile'); @@ -403,6 +488,26 @@ describe('opt-in skill research CLI and pinned identity', () => { expect(open).not.toHaveBeenCalled(); }); + it('rejects --workers 1 when new or saved public research delegates to a team', async () => { + for (const team of [ + ['--agent-team', '4'], + ['--skill-delegation', 'team'], + ]) + await expect(runSolver([...args, '--workers', '1', ...team], root, modules, undefined, 'cli')).rejects.toThrow( + '--workers 1 requires a solo run', + ); + const stateFile = output + '.runtime/state.json'; + expect(fs.existsSync(stateFile)).toBe(false); + + expect(await runSolver(args, root, modules, undefined, 'cli')).toBe(0); + const original = fs.readFileSync(stateFile); + await expect(runSolver([...args, '--resume', '--workers', '1'], root, modules, undefined, 'cli')).rejects.toThrow( + '--workers 1 requires a solo run', + ); + expect(fs.readFileSync(stateFile)).toEqual(original); + expect(open).not.toHaveBeenCalled(); + }); + it('keeps explicit native Skill loading for public solo runs', async () => { const flags = [...args, '--workers', '1', '--skill-loading', 'native']; expect(await runSolver(flags, root, modules, undefined, 'cli')).toBe(0); diff --git a/tests/solver.test.ts b/tests/solver.test.ts index edda1180..8de9d99e 100644 --- a/tests/solver.test.ts +++ b/tests/solver.test.ts @@ -476,6 +476,10 @@ describe('isolated solver and host acceptance', () => { }); host.createSession.mockClear(); host.explain.mockClear(); + expect(await runSolver([...args, '--resume', '--startup-only'], directory)).toBe(0); + expect(host.explain).not.toHaveBeenCalled(); + expect(JSON.parse(fs.readFileSync(output, 'utf8'))).toEqual(accepted); + expect(await runSolver([...args, '--resume'], directory)).toBe(0); expect(host.createSession).not.toHaveBeenCalled(); expect(host.explain).toHaveBeenCalledOnce(); diff --git a/tests/solverAtomicPlanApply.test.ts b/tests/solverAtomicPlanApply.test.ts deleted file mode 100644 index e03105d2..00000000 --- a/tests/solverAtomicPlanApply.test.ts +++ /dev/null @@ -1,119 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { spawnSync } from 'node:child_process'; -import { afterEach, describe, expect, it } from 'vitest'; -import { validateCooperationPlan, validateCooperationPlanFile } from '../src/solver/planTool'; -import { localExample } from './helpers/solver'; - -const roots: string[] = []; -const notes = '## Current argument\nKeep this explanation.\n\n```json\n{"example":42}\n```\n'; -const malformed = '```math-plan\n{ malformed }\n```\n'; - -afterEach(() => { - for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); -}); - -function fixture() { - const example = localExample('atomic-plan-apply-'); - roots.push(example.directory); - const { workspace, problem } = example; - const plan = { - tasks: problem.targets.map(({ proofPath, theoremName }, index) => ({ - id: `goal_${index}`, - kind: 'goal', - objective: `Prove ${theoremName}.`, - proofPath, - theoremName, - })), - }; - const file = path.join(workspace, 'RESEARCH.md'); - fs.writeFileSync(file, notes + '\n' + malformed); - return { example, workspace, problem, plan, file }; -} - -describe('validation of archived cooperative plans', () => { - it('leaves the notes byte-for-byte unchanged on invalid JSON, a graph violation, and invalid retirement fields', () => { - const { workspace, plan, file, problem } = fixture(); - const invalidTask = { tasks: [{ ...plan.tasks[0], status: 'verified' }] }; - const invalidRetirement = { ...plan, retireRoutes: [{ routeId: 'dead', reason: '', evidenceRefs: [0] }] }; - expect(validateCooperationPlan(invalidTask, { problem })).toMatchObject({ - ok: false, - error: 'math_plan_invalid_task', - issues: [ - { path: 'tasks[goal_0].status', message: expect.stringContaining('Host scheduling and proof-acceptance') }, - ], - }); - - const cases = [ - { text: '{"tasks": [}', error: 'math_plan_json_invalid', fields: ['$'] }, - { text: JSON.stringify(invalidTask), error: 'math_plan_invalid_task', fields: ['tasks[goal_0].status'] }, - { - text: JSON.stringify(invalidRetirement), - error: 'math_plan_invalid_retire_routes', - fields: ['retireRoutes[0].reason', 'retireRoutes[0].evidenceRefs[0]'], - }, - ]; - const candidate = path.join(workspace, 'candidate.json'); - for (const item of cases) { - fs.writeFileSync(candidate, item.text); - const input = { workspace, file: candidate }; - const result = validateCooperationPlanFile(input); - expect(result).toMatchObject({ - ok: false, - error: item.error, - issues: item.fields.map(field => ({ path: field, message: expect.any(String) })), - }); - expect(fs.readFileSync(file, 'utf8')).toBe(notes + '\n' + malformed); - } - }); - - it('identifies an oversized progress review reason in archived plan validation', () => { - const { workspace, plan, file } = fixture(); - const progressReview = { - id: 'review', - reason: 'x'.repeat(2001), - nextChecks: [ - { - action: 'construction-check', - targetTaskId: plan.tasks[0].id, - objective: 'Perform the base case check.', - expectedEvidence: 'A checked base case or the exact failed goal.', - }, - ], - }; - const validate = () => - validateCooperationPlanFile({ workspace, text: JSON.stringify({ ...plan, progressReview }) }); - expect(validate()).toEqual({ - ok: false, - error: 'math_plan_progress_review_invalid', - issues: [ - { path: 'progressReview.reason', message: 'Shorten the reason to at most 2000 characters (received 2001).' }, - ], - }); - progressReview.reason = 'x'.repeat(2000); - expect(validate()).toMatchObject({ ok: true }); - expect(fs.readFileSync(file, 'utf8')).toBe(notes + '\n' + malformed); - }); - - it('validates a plan from stdin without changing the archived notes', () => { - const { workspace, plan, file } = fixture(); - const original = fs.readFileSync(file, 'utf8'); - const invoke = (input: string) => - spawnSync('bun', ['bin/math.ts', 'plan-validate', '--workspace', workspace], { - input, - encoding: 'utf8', - timeout: 15_000, - }); - const rejected = invoke('{"tasks":['); - expect(rejected.status, rejected.stderr).toBe(1); - expect(JSON.parse(rejected.stdout)).toMatchObject({ ok: false, error: 'math_plan_json_invalid' }); - const checked = invoke(JSON.stringify(plan)); - expect(checked.status, checked.stderr).toBe(0); - expect(JSON.parse(checked.stdout)).toMatchObject({ - ok: true, - tasksCount: plan.tasks.length, - planVersion: expect.stringMatching(/^[a-f0-9]{64}$/u), - }); - expect(fs.readFileSync(file, 'utf8')).toBe(original); - }); -}); diff --git a/tests/standalone.test.ts b/tests/standalone.test.ts index 5d8e5d35..2ec4f80d 100644 --- a/tests/standalone.test.ts +++ b/tests/standalone.test.ts @@ -4,7 +4,7 @@ import path from 'node:path'; import crypto from 'node:crypto'; import { spawnSync } from 'node:child_process'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import { writeMathJsonDurable } from '../src/math/mathRuntimeIo'; +import { mathDigest, writeMathJsonDurable } from '../src/math/mathRuntimeIo'; import { assertMathBuildAgentTools, mathBuildFile, @@ -15,6 +15,11 @@ import { MATH_RUNTIME_BUNDLES, } from '../src/math/mathBuildManifest'; import { researchLeanHealthCheck } from '../src/solver/researchToolGuide'; +import { readMathAgentSkill } from '../src/runtime/agentSkills'; +import { writeSolverRunState } from '../src/solver/archive'; +import { git } from '../src/solver/problem'; +import { prepareResearchSkill, researchSkillIdentity } from '../src/solver/researchSkill'; +import { localExample, solverState } from './helpers/solver'; const roots: string[] = []; const temp = () => { @@ -147,7 +152,7 @@ describe('standalone build identity', () => { fs.chmodSync(f.file, 0o400); expect(() => readMathBuildManifest(f.file, f.root, f.bundleRoot)).toThrow('math_build_manifest_invalid'); }); - function buildCheckout() { + function buildCheckout(addon?: string) { const directory = temp(); const root = path.join(directory, 'source'); const state = path.join(directory, 'state'); @@ -156,7 +161,7 @@ describe('standalone build identity', () => { 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], { + spawnSync('bun', ['scripts/build.ts', '--state-root', state, ...(addon ? ['--native-process', addon] : [])], { cwd: root, encoding: 'utf8', timeout: 15_000, @@ -172,6 +177,56 @@ describe('standalone build identity', () => { return { root, state, rebuild, buildManifestRef, bundleRoot }; } + it.runIf(process.platform === 'linux')('checks the solver copy of the packaged native addon', () => { + const addon = path.join(temp(), 'native-fixture.node'); + fs.writeFileSync(addon, 'native payload fixture'); + const { root, buildManifestRef, bundleRoot } = buildCheckout(addon); + const solverAddon = path.join(bundleRoot, 'theoremos-process.node'); + const verify = () => readMathBuildManifest(buildManifestRef, root, bundleRoot, 'runtime'); + expect(verify().bundleRoot).toBe(bundleRoot); + + fs.unlinkSync(solverAddon); + expect(verify).toThrow('math_build_artifact_changed'); + fs.writeFileSync(solverAddon, 'differing native bytes', { mode: 0o444 }); + expect(verify).toThrow('math_build_artifact_changed'); + }); + + it('seeds a continuation through the frozen solver despite unrelated source changes', () => { + const { root, buildManifestRef } = buildCheckout(); + const { directory, workspace, problem } = localExample('standalone-seed-'); + roots.push(directory); + const taskDigest = mathDigest('Frozen task'); + const buildDigest = mathDigest(fs.readFileSync(buildManifestRef)); + const [archived, prepared] = ['archived', 'prepared'].map(runId => { + const runtime = path.join(directory, `${runId}.runtime`); + fs.mkdirSync(runtime, { mode: 0o700 }); + const worktree = path.join(runtime, 'worktree'); + git(workspace, ['worktree', 'add', '--quiet', '--detach', worktree, problem.baseCommit]); + const state = solverState(problem, worktree, { runId, phase: 'prepared', taskDigest, buildDigest }); + if (runId === 'prepared') { + state.researchMode = 'skill'; + state.coordination = 'independent'; + state.researchSkill = researchSkillIdentity( + readMathAgentSkill(path.join(root, 'skills/theoremos-research/SKILL.md')), + ); + prepareResearchSkill(root, worktree, state.researchSkill, problem); + } + const file = path.join(runtime, 'state.json'); + writeSolverRunState(file, state); + return file; + }); + fs.writeFileSync(path.join(root, 'scripts', 'standalone-report.ts'), '// An unrelated report'); + const args = ['--source-run', archived!, '--run', prepared!, '--build-manifest', buildManifestRef]; + const invoke = (...entry: string[]) => + spawnSync('bun', [...entry, ...args], { cwd: root, encoding: 'utf8', timeout: 10_000 }); + const source = invoke('scripts/mathematics/seedContinuation.ts'); + expect(source.status).toBe(1); + expect(source.stderr).toContain('math_build_source_changed'); + const bundled = invoke('bin/math.ts', 'continuation-seed'); + expect(bundled.status, bundled.stderr).toBe(0); + expect(JSON.parse(bundled.stdout.trim().split('\n').at(-1)!)).toMatchObject({ stage: 'complete' }); + }); + 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'); diff --git a/tests/webArtifact.test.ts b/tests/webArtifact.test.ts index a01bdab2..66bae0e5 100644 --- a/tests/webArtifact.test.ts +++ b/tests/webArtifact.test.ts @@ -17,19 +17,16 @@ describe('live web Lean candidates without model calls', () => { roots.push(root); return root; }; - const file = (index = 0, result = output) => - path.join(result + '.runtime', index ? `worktree-${index + 1}` : 'worktree', 'generated/problem/Submission.lean'); - const write = (text: string | Buffer, index = 0, result = output) => { - const target = file(index, result); + const file = (result = output) => path.join(`${result}.runtime`, 'worktree', 'generated/problem/Submission.lean'); + const write = (text: string | Buffer, target = file()) => { fs.mkdirSync(path.dirname(target), { recursive: true }); fs.writeFileSync(target, text); return target; }; - const sampler = (workers = 1, apiKey = 'sk-local-test-only', result = output) => + const sampler = (result = output, apiKey = 'sk-local-test-only') => createWebArtifactSampler({ directory, output: result, - workers, source, apiKey, onArtifact: artifact => artifacts.push(artifact), @@ -45,7 +42,7 @@ describe('live web Lean candidates without model calls', () => { }); it('publishes changed source once and always identifies it as an unaccepted candidate', () => { - const sample = sampler(); + const { sample } = sampler(); sample(); write(source); sample(); @@ -66,30 +63,12 @@ describe('live web Lean candidates without model calls', () => { expect(artifacts.every(artifact => artifact.status === 'candidate')).toBe(true); }); - it('keeps the most recently changed fixed worker source and deduplicates identical content across workers', () => { - const sample = sampler(3); - [0, 1, 2].forEach(index => write(source, index)); - sample(); - const lead = write(candidate, 0), - engineer = write(candidate + '-- Engineer\n', 2); - fs.utimesSync(lead, 1_700_000_000, 1_700_000_001); - fs.utimesSync(engineer, 1_700_000_000, 1_700_000_002); - sample(); - expect(artifacts.at(-1)).toMatchObject({ workerId: 'engineer', source: candidate + '-- Engineer\n' }); - write(candidate + '-- Researcher\n', 1); - sample(); - expect(artifacts.at(-1)?.workerId).toBe('researcher-1'); - write(candidate + '-- Researcher\n', 0); - sample(); - expect(artifacts).toHaveLength(2); - }); - - it('never searches arbitrary directories or unconfigured worker slots', () => { - write(candidate, 1); + it('never samples another worktree or arbitrary directory', () => { + write(candidate, path.join(`${output}.runtime`, 'worktree-2', 'generated/problem/Submission.lean')); const arbitrary = path.join(directory, 'unexpected/generated/problem'); fs.mkdirSync(arbitrary, { recursive: true }); fs.writeFileSync(path.join(arbitrary, 'Submission.lean'), candidate); - sampler()(); + sampler().sample(); expect(artifacts).toEqual([]); }); @@ -108,30 +87,30 @@ describe('live web Lean candidates without model calls', () => { const moved = path.join(directory, 'moved'); fs.renameSync(target, moved); fs.symlinkSync(moved, target, kind === 'file' ? 'file' : 'dir'); - sampler()(); + sampler().sample(); expect(artifacts).toEqual([]); }, ); it('rejects escaping paths, external symlinks and hardlinks', () => { const external = path.join(temporary(), 'result.json'); - const externalFile = write(candidate, 0, external); - sampler(1, 'sk-local-test-only', external)(); + const externalFile = write(candidate, file(external)); + sampler(external).sample(); expect(artifacts).toEqual([]); fs.mkdirSync(path.dirname(file()), { recursive: true }); fs.symlinkSync(externalFile, file()); - sampler()(); + sampler().sample(); expect(artifacts).toEqual([]); fs.unlinkSync(file()); fs.linkSync(externalFile, file()); - sampler()(); + sampler().sample(); expect(artifacts).toEqual([]); }); it('rejects a directory replaced by a symlink between inspection and opening the file', () => { write(candidate); const external = path.join(temporary(), 'result.json'); - write('-- private outside the run\n', 0, external); + write('-- private outside the run\n', file(external)); const localTree = path.join(output + '.runtime', 'worktree'); const externalTree = path.join(external + '.runtime', 'worktree'); const open = fs.openSync; @@ -142,14 +121,14 @@ describe('live web Lean candidates without model calls', () => { } return open(target, flags, mode); }); - sampler()(); + sampler().sample(); expect(artifacts).toEqual([]); }); it.each(['empty', 'invalid utf8', 'oversized ascii', 'oversized utf8', 'directory'] as const)( 'ignores %s files and preserves the latest usable candidate', kind => { - const sample = sampler(); + const { sample } = sampler(); write(candidate); sample(); if (kind === 'directory') { @@ -174,31 +153,30 @@ describe('live web Lean candidates without model calls', () => { it('redacts the key before publishing source and enforces the byte limit after redaction', () => { const key = 'sk-quote-"-slash-\\-secret'; write(`-- ${key}\n${candidate}`); - sampler(1, key)(); + sampler(output, key).sample(); expect(artifacts).toHaveLength(1); expect(artifacts[0].source).toBe(`-- [REDACTED]\n${candidate}`); expect(JSON.stringify(artifacts)).not.toContain(JSON.stringify(key).slice(1, -1)); artifacts = []; write('12345678'.repeat(webArtifactMaxBytes / 8)); - sampler(1, '12345678')(); + sampler(output, '12345678').sample(); expect(artifacts).toEqual([]); }); it.each(['incomplete', 'limit_reached', 'runtime_error'])( - "retains a parallel worker's last safe source when %s has no winner", + 'retains the current round’s last safe source when %s has no passing check', status => { - const key = 'sk-parallel-candidate-only'; - write(source); - write(`-- ${key}\n${candidate}`, 1); - sampler(2, key)(); - expect(artifacts.at(-1)?.workerId).toBe('engineer'); + const key = 'sk-candidate-only'; + const round = sampler(output, key); + write(`-- ${key}\n${candidate}`); + round.sample(); + fs.unlinkSync(file()); const proof = readWebResultProof({ directory, workspace: path.join(directory, 'workspace'), status, - winningWorker: undefined, - state: { worktree: path.join(output + '.runtime', 'worktree') }, - artifact: artifacts.at(-1), + state: { worktree: path.join(`${output}.runtime`, 'worktree') }, + artifact: round.latest, }); expect(proof).toBe(`-- [REDACTED]\n${candidate}`); expect(proof).not.toContain('sorry'); @@ -206,33 +184,35 @@ describe('live web Lean candidates without model calls', () => { }, ); - it('uses the selected worker proof over an unrelated live candidate', () => { - write('-- Lead\n' + source); - write(candidate, 1); - const state = { - worktree: path.join(output + '.runtime', 'worktree'), - workers: [{ id: 'engineer', worktree: path.join(output + '.runtime', 'worktree-2') }], - }; + it('returns the source of a library round that stopped before producing a candidate', () => { + const first = sampler(); + write(candidate); + first.sample(); + expect(first.latest?.source).toBe(candidate); + + const nextOutput = path.join(directory, 'rounds/1/result.json'); + const next = sampler(nextOutput); + write(source, file(nextOutput)); + next.sample(); + expect(artifacts.map(artifact => artifact.source)).toEqual([candidate]); expect( readWebResultProof({ directory, workspace: path.join(directory, 'workspace'), - status: 'runtime_error', - winningWorker: 'engineer', - state, - artifact: { source, workerId: 'solver', capturedAt: new Date().toISOString(), status: 'candidate' }, + status: 'limit_reached', + state: { worktree: path.join(`${nextOutput}.runtime`, 'worktree') }, + artifact: next.latest, }), - ).toBe(candidate); + ).toBe(source); }); - it("keeps a single worker's selected proof even without a winningWorker field", () => { + it('uses the worktree source when the candidate passed its check', () => { write(candidate); expect( readWebResultProof({ directory, workspace: path.join(directory, 'workspace'), status: 'limit_reached', - winningWorker: undefined, state: { worktree: path.join(output + '.runtime', 'worktree'), check: { passed: true } }, artifact: { source, workerId: 'solver', capturedAt: new Date().toISOString(), status: 'candidate' }, }), @@ -249,9 +229,8 @@ describe('live web Lean candidates without model calls', () => { directory, workspace, status: 'evaluated_passed', - winningWorker: undefined, state: { worktree: path.join(output + '.runtime', 'worktree') }, - artifact: { source, workerId: 'engineer', capturedAt: new Date().toISOString(), status: 'candidate' }, + artifact: { source, workerId: 'solver', capturedAt: new Date().toISOString(), status: 'candidate' }, }), ).toBe(candidate + '-- Integrated\n'); }); @@ -263,7 +242,6 @@ describe('live web Lean candidates without model calls', () => { directory, workspace: path.join(directory, 'workspace'), status: 'incomplete', - winningWorker: undefined, state: { worktree: path.join(output + '.runtime', 'worktree') }, }), ).toBe(candidate); diff --git a/tests/webAuth.test.ts b/tests/webAuth.test.ts index 9cb61ffa..13af4550 100644 --- a/tests/webAuth.test.ts +++ b/tests/webAuth.test.ts @@ -121,6 +121,55 @@ describe('email login with captcha, allowlist and account-owned records', () => return client; } + it('archives a Lean draft after submission migrates its legacy scheduler', async () => { + const alice = await login('alice@example.org'); + const submitted = { + ...input(), + environment: 'standard', + coordination: 'independent', + modulePlan: { scheduler: 'critical-path', context: 'essential', custom: [] }, + }; + const { apiKey: _apiKey, ...draft } = submitted; + const route = '/api/research/personal/drafts'; + const saved = await request(route, alice, { + requestId: 'save-legacy-plan', + expectedRevision: 0, + scope: { kind: 'problem', draftKey: 'legacy-plan' }, + value: { + mode: 'lean', + draft: { ...draft, templateId: '', maxTurns: '2', maxRunSeconds: '30', workers: '1' }, + }, + summary: 'Legacy module plan', + deviceId: 'test', + deviceName: 'Test', + clientUpdatedAt: new Date().toISOString(), + }); + expect(saved.status).toBe(201); + const { item } = await saved.json(); + const response = await request('/api/runs', alice, submitted); + expect(response.status).toBe(201); + const { run } = await response.json(); + expect(run.modulePlan.scheduler).toBe('plan'); + const archived = await request( + `${route}/${item.draft.id}`, + alice, + { + requestId: 'archive-legacy-plan', + versionId: item.version.id, + action: 'submitted', + submission: { kind: 'run', id: run.id }, + }, + 'PATCH', + ); + expect(archived.status).toBe(200); + const { item: completed } = await archived.json(); + expect(completed.version).toMatchObject({ + status: 'submitted', + submission: { id: run.id }, + value: { draft: { modulePlan: { scheduler: 'critical-path' } } }, + }); + }); + it('requires email login on a public address and keeps loopback previews anonymous', () => { expect(() => readWebConfig({ THEOREMOS_WEB_PUBLIC_URL: 'https://workbench.example' })).toThrow(/SMTP/u); expect(() => diff --git a/tests/webCommunity.test.ts b/tests/webCommunity.test.ts index aeff7e1b..539daf60 100644 --- a/tests/webCommunity.test.ts +++ b/tests/webCommunity.test.ts @@ -94,57 +94,6 @@ describe('community service', () => { const publish = (community: WebCommunity, statement = 'True') => community.createTask(admin, { title: 'A warm-up', environment: 'standard', statement, basePoints: 5 }); - it.skipIf(!process.env.THEOREMOS_WEB_STATIC_ADDON)( - 'matches all persisted community views including private rejected proofs and expired claims', - async () => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'theoremos-community-views-')); - const { community } = setup(new WebStorage(root)); - const guests = [undefined, alice, bob, admin]; - const current = (path: string, actor?: typeof alice) => - community.readPersistedRoute('/api/community/' + path, actor); - try { - const token = community.issueToken(alice).token; - await publish(community); - await publish(community); - community.claim(bob, 'T2'); - const rejected = community.submit(bob, { taskId: 'T1', source: bad(), model: 'Équipe', harness: 'codex' }) - .submission.id; - await community.settled(); - const accepted = community.submit(alice, { taskId: 'T1', source: good(), model: 'été', harness: 'codex' }) - .submission.id; - await community.settled(); - for (const path of ['overview', 'tasks/T1', 'tasks/T2']) { - const body = path === 'overview' ? community.overview() : community.task(path.slice(6)); - expect(current(path)).toEqual({ status: 200, body }); - expect(JSON.stringify(current(path))).not.toContain(token); - } - for (const actor of guests) { - expect(current('submissions/' + accepted, actor)).toEqual({ - status: 200, - body: community.submission(actor, accepted), - }); - expect(current('submissions/' + rejected, actor)).toEqual( - actor?.key === bob.key - ? { status: 200, body: community.submission(bob, rejected) } - : { status: 404, body: { error: '提交不存在。' } }, - ); - expect(current('me', actor)).toEqual( - actor ? { status: 200, body: community.me(actor) } : { status: 401, body: { error: '请先登录。' } }, - ); - } - clock += 8 * 86_400_000; - expect(current('overview')).toEqual({ status: 200, body: community.overview() }); - expect(current('me', bob)).toEqual({ status: 200, body: community.me(bob) }); - community.withdrawTask(admin, 'T2'); - expect(current('tasks/T2')).toEqual({ status: 404, body: { error: '社区题目不存在。' } }); - expect(current('tasks/T0')).toEqual({ status: 400, body: { error: '题目编号无效。' } }); - } finally { - await community.close(); - fs.rmSync(root, { recursive: true, force: true }); - } - }, - ); - it('only lets admins publish, and compiles the module first', async () => { const { community, calls } = setup(); await expect( @@ -159,146 +108,41 @@ describe('community service', () => { expect((await publish(community)).task.id).toBe('T2'); }); - it.skipIf(!process.env.THEOREMOS_WEB_STATIC_ADDON)( - 'restores the winning receipt after an interrupted award without checking again', - async () => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'theoremos-community-receipt-')); - try { - const store = new WebStorage(root); - const first = setup(store).community; - await publish(first); - const accepted = first.submit(alice, { taskId: 'T1', source: good() }).submission.id; + it('applies pending and rolling hourly limits to recovered records before inspecting source', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'theoremos-community-limits-')); + try { + const store = new WebStorage(root), + first = setup(store).community; + await publish(first); + for (let i = 0; i < 20; i++) { + first.submit(alice, { taskId: 'T1', source: bad() }); await first.settled(); - const original = first.submission(alice, accepted).submission; - const file = ['community', 'submissions', accepted + '.json']; - const interrupted = store.getRecord>(file)!; - delete interrupted.checkedAt; - store.saveRecord(file, { ...interrupted, status: 'checking' }); - await first.close(); - const checker = fakeRunner(); - const restored = new WebCommunity(store, checker.runner); - await restored.settled(); - expect(restored.submission(alice, accepted).submission).toEqual(original); - expect(checker.calls).toHaveLength(0); - expect(restored.overview().people[0]?.points).toEqual(original.points); - await restored.close(); - } finally { - fs.rmSync(root, { recursive: true, force: true }); - } - }, - ); - it.skipIf(!process.env.THEOREMOS_WEB_STATIC_ADDON)( - 'recovers an interrupted admission before checking it and counts it once', - async () => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'theoremos-community-admission-')); - try { - const store = new WebStorage(root), - first = setup(store).community; - await publish(first); - const activity = path.join(root, 'community', 'activity'); - fs.renameSync(activity, activity + '.saved'); - fs.writeFileSync(activity, 'block the activity write after both indexes and the counter'); - expect(() => first.submit(alice, { taskId: 'T1', source: good() })).toThrow(); - const journal = path.join(root, 'community', 'admission.json'); - const saved = fs.readFileSync(journal); - const [id] = first.me(alice).submissions.map(s => s.id); - expect(first.task('T1').task.submissions).toBe(1); - await first.close(); - fs.unlinkSync(activity); - fs.renameSync(activity + '.saved', activity); - const checker = fakeRunner(), - restored = new WebCommunity(store, checker.runner); - await restored.settled(); - expect(restored.submission(alice, id!).submission.status).toBe('accepted'); - expect(checker.calls).toHaveLength(1); - expect(fs.existsSync(journal)).toBe(false); - await restored.close(); - // Losing only the journal unlink on a crash must not undo the completed check or repeat its event. - fs.writeFileSync(journal, saved); - const reopened = new WebCommunity(store, checker.runner); - await reopened.settled(); - expect(checker.calls).toHaveLength(1); - expect(reopened.task('T1').task).toMatchObject({ status: 'solved', submissions: 1 }); - expect(reopened.me(alice).submissions).toHaveLength(1); - expect(reopened.overview().activity.filter(e => e.kind === 'submitted')).toHaveLength(1); - await reopened.close(); - } finally { - fs.rmSync(root, { recursive: true, force: true }); - } - }, - ); - it.skipIf(!process.env.THEOREMOS_WEB_STATIC_ADDON)( - 'publishes one compiled module per number, recovers its event after interruption', - async () => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'theoremos-community-publish-')); - try { - const store = new WebStorage(root), - first = setup(store).community; - const results = await Promise.allSettled([publish(first), publish(first)]); - expect(results.filter(r => r.status === 'fulfilled')).toHaveLength(1); - expect(results.find(r => r.status === 'rejected')).toMatchObject({ reason: { status: 409 } }); - const activity = path.join(root, 'community', 'activity'); - fs.renameSync(activity, activity + '.saved'); - fs.writeFileSync(activity, 'interrupt publication after the frozen task is written'); - await expect(publish(first)).rejects.toThrow(); - await first.close(); - fs.unlinkSync(activity); - fs.renameSync(activity + '.saved', activity); - const checker = fakeRunner(), - restored = new WebCommunity(store, checker.runner); - expect( - restored - .overview() - .activity.filter(e => e.kind === 'published') - .map(e => e.taskId) - .sort(), - ).toEqual(['T1', 'T2']); - expect(checker.calls).toHaveLength(0); - expect((await publish(restored)).task.id).toBe('T3'); - await restored.close(); - } finally { - fs.rmSync(root, { recursive: true, force: true }); } - }, - ); - it.skipIf(!process.env.THEOREMOS_WEB_STATIC_ADDON)( - 'applies pending and rolling hourly limits to recovered records before inspecting source', - async () => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'theoremos-community-limits-')); - try { - const store = new WebStorage(root), - first = setup(store).community; - await publish(first); - for (let i = 0; i < 20; i++) { - first.submit(alice, { taskId: 'T1', source: bad() }); - await first.settled(); - } - expect(() => first.submit(alice, { taskId: 'T1', source: '' })).toThrow(/每小时/u); - await first.close(); - let finish!: () => void; - const gate = new Promise(resolve => { - finish = resolve; - }); - const later = new WebCommunity( - store, - async () => { - await gate; - return { output: '', exitCode: 1, timedOut: false }; - }, - { now: () => clock + 3_600_000 }, - ); - later.submit(alice, { taskId: 'T1', source: good() }); - later.submit(alice, { taskId: 'T1', source: good() }); - expect(() => later.submit(alice, { taskId: 'T1', source: '' })).toThrow(/等待校验/u); - expect(later.task('T1').task.submissions).toBe(22); - finish(); - await later.settled(); - await later.close(); - } finally { - fs.rmSync(root, { recursive: true, force: true }); - } - }, - ); + expect(() => first.submit(alice, { taskId: 'T1', source: '' })).toThrow(/每小时/u); + await first.close(); + let finish!: () => void; + const gate = new Promise(resolve => { + finish = resolve; + }); + const later = new WebCommunity( + store, + async () => { + await gate; + return { output: '', exitCode: 1, timedOut: false }; + }, + { now: () => clock + 3_600_000 }, + ); + later.submit(alice, { taskId: 'T1', source: good() }); + later.submit(alice, { taskId: 'T1', source: good() }); + expect(() => later.submit(alice, { taskId: 'T1', source: '' })).toThrow(/等待校验/u); + expect(later.task('T1').task.submissions).toBe(22); + finish(); + await later.settled(); + await later.close(); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); it('awards the first accepted proof the points locked at submit time, and marks later ones late', async () => { const { community, calls } = setup(); await publish(community); diff --git a/tests/webContinuation.test.ts b/tests/webContinuation.test.ts index e1acddca..1b2b3ffd 100644 --- a/tests/webContinuation.test.ts +++ b/tests/webContinuation.test.ts @@ -6,7 +6,8 @@ import { bootstrapLeanTask } from '../src/math/leanTask'; import { mathDigest } from '../src/math/mathRuntimeIo'; import { readContinuationInput } from '../src/solver/continuationInput'; import { readSolverProblem } from '../src/solver/problem'; -import { writeWebContinuation } from '../apps/web/worker'; +import { classifyWebError } from '../apps/web/failure'; +import { runWebProofSolver, writeWebContinuation } from '../apps/web/worker'; const roots: string[] = []; afterEach(() => { @@ -14,6 +15,22 @@ afterEach(() => { }); describe('continuing a web run from a recorded version', () => { + it('passes a solver rejection to the Web error classifier when no result was written', async () => { + const directory = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'theoremos-web-rejected-'))); + roots.push(directory); + const output = path.join(directory, 'result.json'); + const build = path.join(directory, 'unfrozen-build.json'); + const workspace = path.join(directory, 'workspace'); + fs.mkdirSync(workspace); + fs.writeFileSync(build, '{}', { mode: 0o600 }); + await expect( + runWebProofSolver(['--workspace', workspace, '--output', output, '--build-manifest', build], directory).catch( + classifyWebError, + ), + ).resolves.toEqual({ kind: 'environment', reason: 'math_build_manifest_not_frozen' }); + expect(fs.existsSync(output)).toBe(false); + }); + it('writes a continuation input the solver accepts for the same task and problem, and only for them', () => { const directory = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'theoremos-web-continuation-'))); roots.push(directory); diff --git a/tests/webJobs.test.ts b/tests/webJobs.test.ts index ea8c15d6..960ec85a 100644 --- a/tests/webJobs.test.ts +++ b/tests/webJobs.test.ts @@ -271,6 +271,16 @@ describe('web job ownership, scheduling and secret lifetime without provider cal run = jobs.create('owner', input(), provider); await tick(); const send = runner.calls[0].send; + const artifact = { + source: 'theorem example : True := by trivial', + workerId: 'solver', + capturedAt: new Date().toISOString(), + status: 'candidate' as const, + }; + send({ type: 'artifact', artifact }); + expect(run.artifact).toEqual(artifact); + send({ type: 'progress', event: 'library_continuation_started', message: 'Library installed' }); + expect(run.artifact).toBeUndefined(); send({ type: 'library_restart', previousSolverRunId: 'unobserved-solver', solverRunId: 'solver-next', round: 1 }); expect(run.solverAttempt).toBeUndefined(); send({ type: 'observation', observation: observation(run.id, 'solver-next', 1) }); diff --git a/tests/webKnowledgeApi.test.ts b/tests/webKnowledgeApi.test.ts index c96c59a6..8bae2441 100644 --- a/tests/webKnowledgeApi.test.ts +++ b/tests/webKnowledgeApi.test.ts @@ -275,11 +275,12 @@ describe('knowledge and module configuration through the real HTTP service witho bob = await session(); const registry = await get(alice, '/api/module-registry'); expect(registry.scope).toBe('next-run'); - expect(registry.entries.filter((entry: { slot: string }) => entry.slot === 'M3')).toHaveLength(3); + expect(registry.entries.filter((entry: { slot: string }) => entry.slot === 'M3')).toHaveLength(1); const plan = { scheduler: 'critical-path', context: 'essential', custom: [] }; const response = await request(alice, '/api/module-plans', { name: 'HTTP scheme', plan }); expect(response.status).toBe(200); const saved = (await response.json()).plan; + expect(saved.plan.scheduler).toBe('plan'); expect((await get(bob, '/api/module-plans')).plans).toEqual([]); const run = service.jobs.create( alice.owner, @@ -308,9 +309,9 @@ describe('knowledge and module configuration through the real HTTP service witho await service.close(); service = createWebService(config, new ApiFixtureRunner()); await listen(); - expect((await get(alice, '/api/module-plans')).plans[0].plan.scheduler).toBe('continuation'); + expect((await get(alice, '/api/module-plans')).plans[0].plan.scheduler).toBe('plan'); const historical = (await get(alice, `/api/runs/${run.id}`)).run; - expect(historical.modulePlan.scheduler).toBe('critical-path'); + expect(historical.modulePlan.scheduler).toBe('plan'); expect(historical.moduleConfiguration.methodDigest).toBe(run.moduleConfiguration.methodDigest); const deletion = await request( alice, diff --git a/tests/webLibraryNative.test.ts b/tests/webLibraryNative.test.ts index 61e71dce..a7cbd81c 100644 --- a/tests/webLibraryNative.test.ts +++ b/tests/webLibraryNative.test.ts @@ -6,6 +6,7 @@ import { webDefaults } from '../apps/web/config'; import { prepareWebProblem } from '../apps/web/formalizationSeed'; import { runWebLibraryResearch } from '../apps/web/libraryResearch'; import type { WorkerInput } from '../apps/web/shared'; +import { runWebProofSolver } from '../apps/web/worker'; import { LIBRARY_PACK_SCHEMA } from '../src/math/libraryPacks'; import { readLeanTaskReceipt } from '../src/math/leanTask'; import { readMathJson } from '../src/math/mathRuntimeIo'; @@ -14,7 +15,6 @@ import { agentLibrary } from '../src/solver/libraryAccess'; import { writeLibraryCatalog } from '../src/solver/libraryCatalog'; import { knowledgeReferenceCoverage } from '../src/solver/knowledgeUsage'; import { directSolverModules } from '../src/solver/modules'; -import { runSolver } from '../src/solver/run'; import { newestLeanBinary } from './helpers/lean'; // This test exercises real preparation, M2 checks, references and independent S3 acceptance. @@ -123,7 +123,7 @@ describe('native Lean library request and Web continuation', () => { output: path.join(directory, 'result.json'), libraryCatalog: catalog, run: async round => { - const exit = await runSolver( + await runWebProofSolver( [ '--workspace', round.seed.workspaceRoot, @@ -159,9 +159,8 @@ describe('native Lean library request and Web continuation', () => { ); const raw = readMathJson(round.output) as Record; statuses.push(raw.status); - expect(exit, JSON.stringify(raw)).toBe(round.round ? 0 : 1); if (!round.round) - expect(raw).toMatchObject({ + expect(raw, JSON.stringify(raw)).toMatchObject({ status: 'library_requested', turns: 1, solveWallMs: expect.any(Number), diff --git a/tests/webLibraryResearch.test.ts b/tests/webLibraryResearch.test.ts index 6ccd009d..e0b31326 100644 --- a/tests/webLibraryResearch.test.ts +++ b/tests/webLibraryResearch.test.ts @@ -10,6 +10,7 @@ import type { WebRunInput, WorkerInput } from '../apps/web/shared'; import { formalizationDigest, readFormalizationArtifact } from '../src/math/formalization'; import { LIBRARY_PACK_SCHEMA, type LibraryPack } from '../src/math/libraryPacks'; import { mathDigest, readMathJson, readMathText, writeMathJsonDurable } from '../src/math/mathRuntimeIo'; +import type { AgentTeamWorker } from '../src/solver/agentTeamState'; import { writeSolverRunState } from '../src/solver/archive'; import { MAX_CONTINUATION_ATTACHMENT_BYTES, @@ -608,6 +609,77 @@ describe('Web library research supervision without provider calls', () => { }); }); + it('charges native members against the shared allowance and carries their saved research into the next library round', async () => { + const f = fixture({ ...webAgentTeamPreset(), maxTotalTokens: 100 }); + const memberTree = path.join(f.directory, 'member'); + const draft = source + '\n-- Research saved by the team member only.\n'; + const notes = 'Investigate using the requested declaration for the original goal.'; + const run = vi.fn(async (round: WebLibraryRound) => { + const saved = finishRound(f, round, [round.round === 0 ? 'Research.desired' : 'Research.final_hint'], { + tokens: 10, + }); + const { state, stateFile, problem } = saved; + const member: AgentTeamWorker = { + id: 'member', + role: 'researcher', + worktree: memberTree, + phase: 'finished', + status: 'stopped', + turns: 1, + usage: { totalTokens: 40 }, + usageAccounting: { startedTurns: 1, reportedTurns: 1, pending: false, incomplete: false }, + seedCommit: problem.baseCommit, + tasks: [], + cursor: 0, + }; + state.researchDelegation = { mode: 'team', maxAgents: 3 }; + state.agentTeam = { + schema: 'theorem-os.agent-team.v1', + transport: 'native-agent-control', + workers: [ + member, + { + ...member, + id: 'unprepared', + worktree: path.join(f.directory, 'unprepared'), + phase: 'prepared', + status: 'preparing', + turns: 0, + usage: undefined, + usageAccounting: undefined, + }, + ], + events: [], + deliveries: [], + adoptions: [], + operations: [], + }; + writeSolverRunState(stateFile, state); + if (round.round === 0) { + git(state.worktree, ['worktree', 'add', '--quiet', '--detach', memberTree, problem.baseCommit]); + fs.writeFileSync(path.join(memberTree, problem.projectRelative, 'Submission.lean'), draft); + fs.writeFileSync(path.join(memberTree, 'RESEARCH.md'), notes); + } else { + const continued = readContinuationInput(round.continuationFile!, { + taskDigest: mathDigest(readMathText(round.seed.taskFile)), + problemReceiptDigest: problem.receiptDigest, + }); + const contents = [...continued.contents.values()]; + expect(contents).toContain(notes); + expect(contents).toContainEqual(expect.stringContaining(draft)); + expect(readMathText(path.join(problem.workspace, problem.projectRelative, 'Submission.lean'))).toBe(source); + } + }); + const result = await runWebLibraryResearch({ ...f, run }); + expect(run.mock.calls.map(([round]) => round.limits.maxTotalTokens)).toEqual([100, 50]); + expect(result.raw).toMatchObject({ + status: 'limit_reached', + reason: 'math_total_token_limit', + usage: { totalTokens: 100 }, + tokenBudget: { status: 'exhausted', reportedTotalTokens: 100, usageComplete: true }, + }); + }); + it.each([ 'unknown worker', 'outside worker', diff --git a/tests/webPersistence.test.ts b/tests/webPersistence.test.ts index 2bbe3b08..c8ad64a1 100644 --- a/tests/webPersistence.test.ts +++ b/tests/webPersistence.test.ts @@ -510,12 +510,19 @@ describe('durable web evidence and registered research configuration without mod registry = new WebModuleRegistry(store); const plan = { scheduler: 'critical-path' as const, context: 'essential' as const, custom: [] }; const saved = registry.savePlan('alice', { name: 'Focused proof', plan }); - const configuration = freezeModuleConfiguration(saved.plan, 'cooperative', 2); - const oldRun = { ...run(), modulePlan: structuredClone(saved.plan), moduleConfiguration: configuration }; + expect(saved.plan).toEqual({ ...plan, scheduler: 'plan' }); + const configuration = freezeModuleConfiguration(plan, 'cooperative', 2); + const oldRun = { ...run(), modulePlan: plan, moduleConfiguration: configuration }; store.saveRun('alice', oldRun); expect(configuration.id).toContain('/web-byok-v1'); expect(configuration.versions.M1).toContain('/web-byok-v1'); - expect(registry.registry().entries.filter(entry => entry.slot === 'M3')).toHaveLength(3); + expect( + registry + .registry() + .entries.filter(entry => entry.slot === 'M3') + .map(entry => entry.id), + ).toEqual(['M3:plan']); + expect(configuration.selection.implementations.find(entry => entry.slot === 'M3')?.id).toBe('M3:critical-path'); expect( registry .registry() @@ -531,7 +538,7 @@ describe('durable web evidence and registered research configuration without mod expect(updated.configuration.methodDigest).not.toBe(configuration.methodDigest); const restartStore = new WebStorage(root), restarted = new WebModuleRegistry(restartStore); - expect(restarted.getPlan('alice', saved.id)?.plan.scheduler).toBe('continuation'); + expect(restarted.getPlan('alice', saved.id)?.plan.scheduler).toBe('plan'); expect(restarted.getPlan('bob', saved.id)).toBeUndefined(); expect(restartStore.getRun('alice', oldRun.id)?.modulePlan?.scheduler).toBe('critical-path'); expect(restartStore.getRun('alice', oldRun.id)?.moduleConfiguration).toEqual(configuration); diff --git a/tests/webResearchApi.test.ts b/tests/webResearchApi.test.ts index 0ff36dc1..deeb6f47 100644 --- a/tests/webResearchApi.test.ts +++ b/tests/webResearchApi.test.ts @@ -1734,6 +1734,34 @@ describe('collaborative research through the actual HTTP service', () => { ); }); + it('matches an explicit current scheduler to a frozen Agent published with a legacy scheduler', async () => { + const alice = await client('Alice'); + const release = await publish( + alice, + await createAsset(alice, 'agent', 'LegacyAgent', { + environment: 'standard', + modulePlan: { scheduler: 'critical-path', context: 'essential', custom: [] }, + }), + ); + const submitted = { + ...input(), + workers: 1, + coordination: 'independent', + modulePlan: { scheduler: 'plan', context: 'essential', custom: [] }, + researchSelection: { agent: { assetId: release.assetId, version: release.version } }, + }; + const differentContext = await request(alice, '/api/runs', { + ...submitted, + modulePlan: { ...submitted.modulePlan, context: 'full' }, + }); + expect(differentContext.status).toBe(409); + const response = await request(alice, '/api/runs', submitted); + expect(response.status).toBe(201); + const { run } = await response.json(); + expect(run.modulePlan).toEqual(submitted.modulePlan); + expect(run.researchConfiguration.agent.content.modulePlan.scheduler).toBe('critical-path'); + }); + it('freezes shared Skill, Agent and mathematics into the third user worker input and retains it after updates or withdrawal', async () => { const alice = await client('Alice'), bob = await client('Bob'), @@ -1759,7 +1787,9 @@ describe('collaborative research through the actual HTTP service', () => { const selection = { agent: { assetId: agentAsset.id, version: agentRelease.version, digest: agentRelease.digest } }; const created = await newRun(carol, { requestId: 'third-person-run', researchSelection: selection }); const worker = runner.calls.find(call => call.id === created.id)!; - expect(worker.input.modulePlan?.scheduler).toBe('critical-path'); + expect(worker.input.modulePlan?.scheduler).toBe('plan'); + expect(worker.researchConfiguration?.modulePlan.scheduler).toBe('plan'); + expect(worker.researchConfiguration?.agent?.content.modulePlan.scheduler).toBe('critical-path'); expect(worker.input.modulePlan?.custom.some(rule => rule.instructions.includes('FIRST_SKILL_INSTRUCTION'))).toBe( true, ); diff --git a/tests/webServer.test.ts b/tests/webServer.test.ts index 5d15d471..10f7616b 100644 --- a/tests/webServer.test.ts +++ b/tests/webServer.test.ts @@ -50,10 +50,12 @@ class HttpTestRunner implements WebRunner { calls: Call[] = []; ready = true; nativeTeam = false; + nativeTeamPreferences = false; async readiness() { return { ready: this.ready, nativeTeam: this.nativeTeam, + nativeTeamPreferences: this.nativeTeamPreferences, message: this.ready ? 'Test worker ready' : 'Test worker unavailable', }; } @@ -340,6 +342,34 @@ describe('web HTTP boundary with disposable local servers and no model calls', ( await tick(); } }); + it('keeps profile preferences when a new run uses the default team capacity', async () => { + const client = await session(); + const body = { ...input(), coordination: 'independent', nativeTeamPreferredProfiles: ['engineer'] }; + const unavailable = await request('/api/runs', client, { body }); + expect(unavailable.status).toBe(503); + expect((await unavailable.json()).error).toContain('未安装原生团队后端'); + runner.nativeTeam = true; + const unsupported = await request('/api/runs', client, { body }); + expect(unsupported.status).toBe(503); + expect((await unsupported.json()).error).toContain('不支持角色偏好'); + runner.nativeTeamPreferences = true; + const solo = await request('/api/runs', client, { body: { ...body, researchMode: 'legacy' } }); + expect(solo.status).toBe(400); + const submitted = { ...body, requestId: 'profile-default-team' }; + const response = await request('/api/runs', client, { body: submitted }); + expect(response.status).toBe(201); + const { run } = await response.json(); + expect(run).toMatchObject({ nativeTeamCapacity: 4, nativeTeamPreferredProfiles: ['engineer'] }); + expect(runner.calls.at(-1)?.value.input).toMatchObject({ + nativeTeamCapacity: 4, + nativeTeamPreferredProfiles: ['engineer'], + }); + runner.ready = false; + const replay = await request('/api/runs', client, { body: submitted }); + expect(replay.status).toBe(200); + expect((await replay.json()).run.id).toBe(run.id); + expect(runner.calls).toHaveLength(1); + }); it('selects only an operator-configured native harness and omits private launch configuration from HTTP records', async () => { const provider = { id: 'codex-test', @@ -556,10 +586,11 @@ describe('web HTTP boundary with disposable local servers and no model calls', ( const created = await request('/api/runs', alice, { body: { ...input(), modulePlan } }); expect(created.status).toBe(201); const run = (await created.json()).run; - expect(run.modulePlan).toEqual(modulePlan); + expect(run.modulePlan).toEqual({ ...modulePlan, scheduler: 'plan' }); + expect(run.moduleConfiguration.selection.scheduler).toBe('plan'); expect(run.nativeTeamCapacity).toBeUndefined(); await tick(); - expect(runner.calls[0].value.input.modulePlan).toEqual(modulePlan); + expect(runner.calls[0].value.input.modulePlan).toEqual(run.modulePlan); modulePlan.custom[0].instructions = 'A later client-side edit'; const current = await request(`/api/runs/${run.id}`, alice); expect((await current.json()).run.modulePlan).toEqual(run.modulePlan); From c735f3290872234ab25bf53ae147c9d2448dedae Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Sat, 5 Dec 2026 04:01:49 +0800 Subject: [PATCH 2/2] Drop translations for retired Web paths --- apps/web/i18n/errors.ts | 3 --- apps/web/i18n/server.ts | 1 - 2 files changed, 4 deletions(-) diff --git a/apps/web/i18n/errors.ts b/apps/web/i18n/errors.ts index 3cef686f..0a1c0f10 100644 --- a/apps/web/i18n/errors.ts +++ b/apps/web/i18n/errors.ts @@ -276,9 +276,6 @@ export const errors: Record = { '排队中或运行中的任务不能删除,请先取消或等待结束。': 'A queued or running task cannot be deleted; cancel it or wait for it to finish.', '运行尚未结束,且结果尚未生成。': 'The run has not finished and has no result yet.', - '接口不存在。': 'Endpoint not found.', - '验证码格式无效。': 'Invalid verification code format.', - '账号状态已变更,请重新读取。': 'The account status changed. Reload and try again.', '知识查询或分页参数无效。': 'Invalid knowledge query or paging parameters.', '服务暂时不可用。': 'The service is temporarily unavailable.', '服务已重启;保留最后观测与已有证据。本次运行未恢复执行。': diff --git a/apps/web/i18n/server.ts b/apps/web/i18n/server.ts index cfaea875..c702d453 100644 --- a/apps/web/i18n/server.ts +++ b/apps/web/i18n/server.ts @@ -234,7 +234,6 @@ export const server: Record = { 有界证明研究: 'Bounded proof research', 'Lean 局部检查': 'Local Lean checks', 计划顺序: 'Plan order', - 关键路径: 'Critical path', 必要证明上下文: 'Essential proof context', 角色分工与交付: 'Roles and handoffs', 完整原题独立验收: 'Independent acceptance of the complete problem',