From 3bc00c7aa25d3dbf8333ddb2d229164120c15cdd Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:00:15 +0800 Subject: [PATCH] fix(solver): harden portfolio scouts, team handoffs, usage accounting, and plan help - Isolate portfolio scout worktrees and private runtime profiles outside /tmp and the shared solver profile, serialize per-repository git worktree add/remove, and prevent web_provider config.toml writes from mutating frozen profiles. - Give portfolio scouts their concrete Phase 1 budget and a soft wrap-up notice, accept valid PORTFOLIO.json reports saved before abort, and classify missing/invalid deadline reports as math_portfolio_scout_timed_out. - Direct AgentResearchTeam Lead milestone notices to team coordination instead of declaration-submission.json, consume empty Lead helper nominations without a repair loop, and require non-empty compiled helpers in solo guidance. - Suppress already-accounted cumulative token replays on warm thread/resume before turnStarted while keeping alerts for genuinely unscoped tokens. - Materialize Lead plan-validate/plan-apply CLI guidance in .scratch/theoremos-help.md and remind Cooperative Leads to omit progressReview on initial plans. - Forward portfolio, soft-slice, compaction-circuit-breaker, and team-transport-fallback progress events in apps/web. --- apps/web/i18n/server.ts | 8 + apps/web/progress.ts | 11 +- .../references/cooperation.md | 2 +- src/runtime/codexSession.ts | 9 +- src/solver/agentTeamContext.ts | 2 + src/solver/declarationArtifacts.ts | 4 +- src/solver/modules/context.ts | 11 +- src/solver/portfolioExploration.ts | 212 ++++++++++++------ src/solver/problem.ts | 26 ++- src/solver/research.ts | 11 +- src/solver/researchGuidance.ts | 8 +- src/solver/researchToolGuide.ts | 5 +- src/solver/researchUsage.ts | 3 +- src/solver/skillProofLifecycle.ts | 4 +- src/solver/skillResearchContext.ts | 8 +- tests/codexSession.test.ts | 68 ++++-- tests/fullSkillWorkflow.test.ts | 24 +- tests/solverPortfolioGate.test.ts | 128 ++++++++++- tests/solverSoftSliceCompaction.test.ts | 28 ++- tests/solverUsageReceipts.test.ts | 20 ++ tests/webModuleTelemetry.test.ts | 23 ++ 21 files changed, 491 insertions(+), 124 deletions(-) diff --git a/apps/web/i18n/server.ts b/apps/web/i18n/server.ts index 6109c3d1..373d192e 100644 --- a/apps/web/i18n/server.ts +++ b/apps/web/i18n/server.ts @@ -59,6 +59,14 @@ export const server: Record = { "模型预算已停止后续调用": "Model budget stopped further calls", "本轮上下文已整理": "Context for this turn compiled", "初始规划已达到限额,正在交接研究任务": "Initial planning reached its limit; handing off research tasks", + "开始探索候选路线": "Exploring candidate routes", + "路线探查已开始": "Route scout started", + "路线探查已结束": "Route scout finished", + "路线探查未能提交有效报告": "Route scout delivered no usable report", + "候选路线评估已完成": "Candidate routes evaluated", + "团队已切换至宿主工具": "Team switched to host tools", + "已请 Agent 保存阶段成果并交接": "Agent asked to save progress and hand off", + "上下文多次压缩,已请 Agent 保存成果并交接": "Repeated context compaction prompted a handoff request", "研究上下文已重新建立": "Research context rebuilt", "研究任务已分配": "Research task assigned", "局部任务检查完成": "Local task check finished", diff --git a/apps/web/progress.ts b/apps/web/progress.ts index 9feb35c8..1667ee89 100644 --- a/apps/web/progress.ts +++ b/apps/web/progress.ts @@ -19,6 +19,12 @@ const descriptions: Record = { assignment_superseded: '当前分配已被更新', research_action: '已选择下一步研究操作', model_budget_stopped: '模型预算已停止后续调用', context_compiled: '本轮上下文已整理', planning_budget_stopped: '初始规划已达到限额,正在交接研究任务', + portfolio_exploration_started: '开始探索候选路线', + portfolio_scout_started: '路线探查已开始', portfolio_scout_finished: '路线探查已结束', + portfolio_scout_unavailable: '路线探查未能提交有效报告', portfolio_gate_evaluated: '候选路线评估已完成', + team_transport_fallback: '团队已切换至宿主工具', + soft_slice_milestone_requested: '已请 Agent 保存阶段成果并交接', + compaction_circuit_breaker_triggered: '上下文多次压缩,已请 Agent 保存成果并交接', context_restarted: '研究上下文已重新建立', task_assigned: '研究任务已分配', task_checked: '局部任务检查完成', task_check_reused: '已复用当前任务检查', task_failure_check_reused: '已复用当前任务的失败检查', task_recheck_started: '正在重新检查任务', @@ -97,7 +103,7 @@ const failureDescriptions: Record = { math_delivery_line_too_large: 'Agent 交付记录过大,未能读取', }; // A recovery succeeded; naming the provider failure it recovered from would read as a new failure. -const recoveries = new Set(['worker_recovered']); +const recoveries = new Set(['worker_recovered', 'team_transport_fallback']); const fields: Record = { turn_started: ['turn'], turn_checkpoint: ['turn', 'reason'], proof_check_started: ['turn'], proof_checked: ['passed', 'reused'], research_action: ['operation'], @@ -133,6 +139,9 @@ const fields: Record = { proof_ready_checked: ['taskId', 'passed', 'conditional'], proof_ready_frozen: ['taskId'], knowledge_use_observed: ['taskId'], knowledge_use_rejected: ['taskId'], worker_context_recovering: ['reason'], cooperation_poll_failed: ['reason'], rejected: ['reason'], + portfolio_scout_finished: ['status'], portfolio_scout_unavailable: ['status', 'reason'], + team_transport_fallback: ['reason'], soft_slice_milestone_requested: ['taskId'], + compaction_circuit_breaker_triggered: ['taskId'], }; /** The code before any ':' detail; runtime reasons append ids, sizes or Lean text after it. */ diff --git a/skills/theoremos-research/references/cooperation.md b/skills/theoremos-research/references/cooperation.md index 7cc64fc5..a6152ac4 100644 --- a/skills/theoremos-research/references/cooperation.md +++ b/skills/theoremos-research/references/cooperation.md @@ -12,7 +12,7 @@ Edit only assigned source paths. Preserve other seed proofs and frozen declarati ## Lead plan -Leave Lean sources unchanged and return a plan without running Lean diagnostics; assigned workers execute proof and check tasks. Publish one JSON line to the current Lead delivery log: +Leave Lean sources unchanged and delegate Lean diagnostics to workers. Omit `progressReview` on the initial plan. Save the draft in `.scratch/plan.json` and run `theorem-os plan-validate --file .scratch/plan.json` before publishing or running `plan-apply`. Publish one JSON line to the current Lead delivery log: ```json {"kind":"plan","baseVersion":"CURRENT_BASE_VERSION","dispatchNonce":"CURRENT_DISPATCH_NONCE","summary":"route and consumers","tasks":[]} diff --git a/src/runtime/codexSession.ts b/src/runtime/codexSession.ts index 3c78f45c..b89e0206 100644 --- a/src/runtime/codexSession.ts +++ b/src/runtime/codexSession.ts @@ -8,7 +8,6 @@ import { parse as parseToml, stringify as stringifyToml } from 'smol-toml'; import { mathProofEnvironmentWorkerEnvironment } from '../math/mathProofEnvironment'; import { assertMathCanonicalPath, isMathPathWithin } from '../math/paths'; import { startChatCompletionsBridge } from './chatCompletionsBridge'; -import { DEEPSEEK_PROVIDER } from './deepseek'; import { WESTLAKE_PROVIDER, validateWestlakeModel } from './westlake'; import { SUB2API_PROVIDER } from './sub2api'; import type { ModelRequestGate } from './modelRequest'; @@ -302,7 +301,8 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise (calledThread, calledTurn) => calledThread === threadId && activeTurn === calledTurn && !turnSettled && !turnStopping && !closing, options.delegation ? [INVESTIGATION_TOOL] : []) : undefined; const configFile = path.join(options.profile, 'config.toml'); - const profileConfig = fs.existsSync(configFile) ? parseToml(fs.readFileSync(configFile, 'utf8')) : {}; + const frozenConfig = fs.existsSync(configFile) ? fs.readFileSync(configFile, 'utf8') : undefined; + const profileConfig = frozenConfig === undefined ? {} : parseToml(frozenConfig); const providerId = typeof profileConfig.model_provider === 'string' ? profileConfig.model_provider : undefined; const providers = profileConfig.model_providers; const selectedProvider = providerId && providers && typeof providers === 'object' && !Array.isArray(providers) @@ -415,14 +415,13 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise let bridge: Awaited> | undefined; let responsesRelay: Awaited> | undefined; let nativeProfile = isolated?.profile ?? options.profile; - if (!isolated && (providerId === DEEPSEEK_PROVIDER.id || providerId === WESTLAKE_PROVIDER.id || - providerId === SUB2API_PROVIDER.id || options.nativeAgentControl && fs.existsSync(configFile))) { + if (!isolated && frozenConfig !== undefined) { // Codex persists project trust in config.toml; keep those writes outside the frozen profile. nativeProfile = path.join(options.profile, 'runtime'); fs.mkdirSync(nativeProfile, { recursive: true, mode: 0o700 }); const snapshot = path.join(nativeProfile, `.config-${randomUUID()}.toml`); try { - let config = fs.readFileSync(configFile, 'utf8'); + let config = frozenConfig; if (useResponsesRelay) { const clean = structuredClone(profileConfig), selected = { ...object(provider) } as ReturnType; delete selected.auth; diff --git a/src/solver/agentTeamContext.ts b/src/solver/agentTeamContext.ts index b16202d4..f2c8b9b8 100644 --- a/src/solver/agentTeamContext.ts +++ b/src/solver/agentTeamContext.ts @@ -30,6 +30,7 @@ export function agentTeamInstructions(role: AgentTeamRole, maxAgents: number, 'Inspection and adoption record source exposure; preserve original authorship and describe assembly or exposed review accurately. ' + 'Use resume to continue a paused task without replacing its identity. ' + 'Spawn and assign return immediately; poll/wait receives individual arrivals while other agents continue. ' + + 'If portfolio scouting produced no report, split concrete unanswered questions from the frozen statement and spawn useful independent work as soon as capacity is free. ' + 'Use inspect to examine exact declarations and evidence before choosing adoption into you or an idle child. ' + 'Save sources and notes before requesting adoption into your worktree, then return. ' + 'A pending adoption also makes the host hand off automatically before the next model request; ' + @@ -65,6 +66,7 @@ function nativeAgentTeamInstructions(role: AgentTeamRole, maxAgents: number): st 'This team run explicitly authorizes you to spawn and coordinate useful child agents through the native collaboration tools. ' + `At most ${maxAgents} agents including you may be available. ` + 'As soon as you identify a proof step you can advance, work on it in your Lean files. Keep writing the consuming argument or another unassigned gap while members work. ' + + 'If portfolio scouting produced no report, use native spawn_agent for concrete independent gaps found in the frozen statement. ' + 'If several goals share a mathematical foundation, assign and check its small Lean interfaces before dispatching the consuming goals. ' + 'Tag route-specific native spawn and followup objectives with Route: ROUTE_ID as the first line. Use theoremos_team retire_route with the obstruction and evidence refs to stop a refuted route. ' + 'Idle members still occupy their places. Use native followup_task to reuse a member for another gap or specialty; interrupt_agent stops its turn and preserves its place and work. ' + diff --git a/src/solver/declarationArtifacts.ts b/src/solver/declarationArtifacts.ts index 52bcb7f1..d4421fd3 100644 --- a/src/solver/declarationArtifacts.ts +++ b/src/solver/declarationArtifacts.ts @@ -60,6 +60,7 @@ const segmentedManifestSchema = z.object({ schema: z.literal('theorem-os.declara const segmentSchema = z.object({ schema: z.literal('theorem-os.declaration-artifacts.segment.v1'), ...manifestIdentity, previous: hash.nullable(), artifacts: z.array(z.unknown()).min(1).max(manifestRecords) }).strict(); +const emptyDeclarationSubmission = z.object({ declarations: z.tuple([]) }).strict(); const fail = (reason: string): never => { throw new Error(`math_declaration_artifact_${reason}`); }; function declarationIdentity({ file, name, type, kind }: DeclarationSubmission['declarations'][number], declarationHash: string) { return mathDigest(canonicalMathJson({ file, name, type, ...(kind && { kind }), declarationHash })); @@ -87,7 +88,7 @@ function submissionContent(operation: () => T, correctable: readonly string[] } } -export function readDeclarationSubmission(worktree: string): DeclarationSubmission | undefined { +export function readDeclarationSubmission(worktree: string, options?: { allowEmpty?: boolean }): DeclarationSubmission | undefined { const file = path.join(worktree, '.scratch', DECLARATION_SUBMISSION_FILE); if (!fs.existsSync(file)) return undefined; assertMathCanonicalPath(file); @@ -98,6 +99,7 @@ export function readDeclarationSubmission(worktree: string): DeclarationSubmissi if (error instanceof SyntaxError) throw new DeclarationSubmissionError('math_declaration_artifact_submission_invalid_json', { cause: error }); throw error; } + if (options?.allowEmpty && emptyDeclarationSubmission.safeParse(value).success) return undefined; return parseDeclarationSubmission(value); } diff --git a/src/solver/modules/context.ts b/src/solver/modules/context.ts index 465c6ed8..a5412474 100644 --- a/src/solver/modules/context.ts +++ b/src/solver/modules/context.ts @@ -37,11 +37,12 @@ import { mathematicalGapContextText } from '../mathematicalGaps'; import { nextCheckContextText } from '../nextChecks'; import { goalProgressTaskContext } from '../goalProgress'; import { assertMathAgentSkillsCurrent, type MathAgentSkill } from '../../runtime/agentSkills'; -import { buildCommonResearchContext, buildCommonResearchGuide, cooperativeDeliveryProtocol, cooperativeHelperProtocol } from '../researchGuidance'; +import { buildCommonResearchContext, buildCommonResearchGuide, cooperativeDeliveryProtocol, cooperativeHelperProtocol, leadPlanToolInstruction } from '../researchGuidance'; import { agentTeamContextSection, buildSkillResearchContext, executionLimitsSection } from '../skillResearchContext'; import type { AgentTeamAssignment, AgentTeamRole } from '../agentTeamContext'; import { researchSkillIdentity } from '../researchSkill'; -import { longCommandGuidance } from '../researchToolGuide'; +import { buildResearchToolGuide, longCommandGuidance } from '../researchToolGuide'; +import type { ResearchToolHelp } from '../researchToolHelp'; export type ContextAccess = Readonly<{ teamRole?: AgentTeamRole; @@ -81,6 +82,7 @@ export type ContextAccess = Readonly<{ export type ContextBundle = Readonly<{ assignment?: CooperativeAction; workContract?: ReturnType; + toolHelp?: ResearchToolHelp; instructions: string; message: string; /** Same-thread dispatch compiled under the same byte budget as the full context. */ @@ -163,6 +165,7 @@ export function buildResearchContext(task: SolverProblem, state: Readonly scout.reports?.length)) + return 'Phase 1 ended without a usable report. Proceed with the frozen problem and delegate independent gaps using available worker capacity.'; const summaries = [gate.primaryRouteId, gate.backupRouteId].flatMap(id => { if (!id) return []; const report = portfolio.scouts.flatMap(scout => scout.reports ?? []).find(report => @@ -127,7 +130,7 @@ export function configurePortfolioExploration(saved: PortfolioExploration | unde } const reportFile = 'PORTFOLIO.json'; -const instructions = (profile: ScoutProfile, ownedFiles: readonly string[]) => { +const instructions = (profile: ScoutProfile, ownedFiles: readonly string[], budgetMs: number) => { const example = { reports: [{ routeId: profile, status: 'proposed', blueprintSummary: 'Reduction with explicit remaining premises.', keyTransformations: ['First reduction'], proposedFoundationLemmas: [{ id: 'base-identity', proofPath: ownedFiles[0], theoremName: 'Portfolio.baseIdentity', type: '∀ (n : Nat), n = n', @@ -135,6 +138,8 @@ const instructions = (profile: ScoutProfile, ownedFiles: readonly string[]) => { falsificationEvidence: [], obstructions: [], probeRefs: [] }] }; return [ 'Phase 1 portfolio scout: ' + profile + '. ' + profileInstructions[profile], + `Wall-clock budget remaining: ${Math.ceil(budgetMs / 1000)} seconds. Write an initial valid ${reportFile} by halfway, even if your finding is inconclusive. ` + + 'Update it as evidence improves by writing a temporary file in the same directory and renaming it over the report.', 'Inspect the fixed Lean statement. Use mathematical derivations and quick numerical or symbolic probes with Python, PARI/GP, SymPy or SAT as available.', 'Keep original Lean files read-only. If necessary, write at most two Lean API probes of fewer than 40 lines each under .scratch/portfolio. Do not formalize full proofs.', 'Test the key claim in your own route even when another scout is assigned to falsification. The route IDs are ' + profiles.join(', ') + '.', @@ -193,81 +198,150 @@ export async function runPortfolioExploration(input: { for (const scout of eligible) if (!selected.includes(scout)) scout.status = 'failed'; changed(); emit('portfolio_exploration_started', { deadlineAt: portfolio.deadlineAt, profiles: selected.map(scout => scout.profile) }); - const signal = AbortSignal.any([input.signal, AbortSignal.timeout(Math.ceil(remainingMs()))]); + const deadline = new AbortController(); + const signal = AbortSignal.any([input.signal, deadline.signal]); + const runRoot = path.dirname(state.worktree); + const portfolioWorktreeRoot = path.join(runRoot, 'portfolio-worktrees'); + const portfolioProfileRoot = path.join(runRoot, 'portfolio-profiles'); + const timedOut = () => !input.signal.aborted && (deadline.signal.aborted || !remainingMs()); + const deadlineTimer = setTimeout(() => deadline.abort(new Error('math_portfolio_scout_timed_out')), Math.ceil(remainingMs())); + deadlineTimer.unref(); let falsifier: MathAgentSession | undefined; const proposals = () => portfolio.scouts.flatMap(scout => (scout.reports ?? []).filter(report => report.status === 'proposed') .map(({ routeId, blueprintSummary, keyTransformations }) => ({ routeId, blueprintSummary, keyTransformations }))); - const outcomes = await Promise.allSettled(selected.map(async scout => { - if (!remainingMs() || !modelDispatchAllowed(state.tokenBudget!)) { - scout.status = remainingMs() ? 'failed' : 'timed-out'; changed(); return; + try { + if (selected.length && remainingMs() && modelDispatchAllowed(state.tokenBudget!)) { + const sourceProfile = path.resolve(input.profile); + if (isMathPathWithin(sourceProfile, portfolioProfileRoot) || isMathPathWithin(sourceProfile, portfolioWorktreeRoot)) + throw new Error('math_portfolio_profile_must_be_separate'); + for (const directory of [portfolioWorktreeRoot, portfolioProfileRoot]) { + assertMathCanonicalPath(directory); + fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); + } } - const profile = scout.profile; - // A retry uses a fresh thread. Preserve the cumulative usage already observed for the earlier attempt. - scout.usageBeforeThread = scout.usage; - scout.status = 'running'; save(); - try { - await withSolverWorktree(state.worktree, state.problem.baseCommit, async worktree => { - const prepared = input.prepareWorkspace(worktree); - fs.mkdirSync(path.join(worktree, '.scratch', 'portfolio'), { recursive: true, mode: 0o700 }); - let session: MathAgentSession | undefined, started = false, result: string | undefined; - const usage = new ResearchUsage({ state, research: scout, maxTotalTokens: input.maxTotalTokens, - signal, remainingMs, changed, emit: (event, details) => emit(event, { ...details, profile }) }); - const sessionId = randomUUID(); - try { - signal.throwIfAborted(); - session = await input.open({ executable: input.executable, profile: input.profile, workspace: worktree, - proofProjectRoot: prepared.project, model: state.model, effort: state.effort, isolateProcess: true, - environment: { ...prepared.environment, DEEPSCIENTIST_MATH_WORKER_ID: 'portfolio-' + profile, - DEEPSCIENTIST_MATH_WORKER_WORKTREE: worktree }, - instructions: instructions(profile, state.problem.ownedFiles), signal, - turnTimeoutMs: Math.max(1, Math.min(input.maxTurnMs, remainingMs())), - ...usage.bindSession(sessionId, () => session?.lastInputTokens) }); - signal.throwIfAborted(); - if (!modelDispatchAllowed(state.tokenBudget!) || !remainingMs()) { - scout.status = remainingMs() ? 'failed' : 'timed-out'; - return; - } - usage.sessionOpened(session); - state.turns++; scout.turns++; - const counts = state.dispatchCounts ??= {}; - counts.research = (counts.research ?? 0) + 1; - started = true; usage.begin(undefined, 'portfolio-' + profile); - emit('portfolio_scout_started', { profile }); - const attacks = profile === 'falsification-obstruction'; - const currentProposals = attacks ? proposals() : []; - result = await session.run(input.taskText + '\n\nRead the frozen statement in ' + state.problem.projectRelative + '.' + - (currentProposals.length ? '\nProposals to test:\n' + JSON.stringify(currentProposals) : ''), randomUUID(), worktree, - turnId => { usage.turnStarted(turnId); if (attacks) falsifier = session; }); - } finally { - if (falsifier === session) falsifier = undefined; + const outcomes = await Promise.allSettled(selected.map(async scout => { + if (!remainingMs() || !modelDispatchAllowed(state.tokenBudget!)) { + scout.status = remainingMs() ? 'failed' : 'timed-out'; changed(); return; + } + const profile = scout.profile; + const workerId = 'portfolio-' + profile; + // A retry uses a fresh thread. Preserve the cumulative usage already observed for the earlier attempt. + scout.usageBeforeThread = scout.usage; + scout.status = 'running'; save(); + try { + await withSolverWorktree(state.worktree, state.problem.baseCommit, async worktree => { + const prepared = input.prepareWorkspace(worktree); + fs.mkdirSync(path.join(worktree, '.scratch', 'portfolio'), { recursive: true, mode: 0o700 }); + let session: MathAgentSession | undefined, started = false, result: string | undefined; + let wrapUpTimer: ReturnType | undefined; + const usage = new ResearchUsage({ state, research: scout, maxTotalTokens: input.maxTotalTokens, + signal, remainingMs, changed, emit: (event, details) => emit(event, { ...details, profile }) }); + const sessionId = randomUUID(); + const profileDirectory = path.join(portfolioProfileRoot, `${profile}-${sessionId}`); + const scoutProfile = path.join(profileDirectory, 'profile'); try { - const stopped = await session?.stopForFreeze?.(); - if (session && stopped?.status !== 'stopped') throw new Error('math_portfolio_scout_stop_unconfirmed'); + signal.throwIfAborted(); + fs.mkdirSync(profileDirectory, { mode: 0o700 }); + if (state.agentHarness && state.agentHarness.id !== 'codex') { + projectResearchHarnessProfile(state.agentHarness, scoutProfile, prepared.environment, state.model); + } else { + fs.mkdirSync(scoutProfile, { mode: 0o700 }); + // Provider environment keys and configured auth commands still work. Never copy credential stores. + const config = path.resolve(input.profile, 'config.toml'); + assertMathCanonicalPath(config); + if (fs.existsSync(config)) fs.writeFileSync(path.join(scoutProfile, 'config.toml'), fs.readFileSync(config), + { flag: 'wx', mode: 0o400 }); + } + const scoutBudgetMs = Math.max(1, Math.min(input.maxTurnMs, remainingMs())); + session = await input.open({ executable: input.executable, profile: scoutProfile, workspace: worktree, + proofProjectRoot: prepared.project, model: state.model, effort: state.effort, isolateProcess: true, + isolatedWorkspaceParent: portfolioWorktreeRoot, + environment: { ...prepared.environment, DEEPSCIENTIST_MATH_WORKER_ID: workerId, + DEEPSCIENTIST_MATH_WORKER_WORKTREE: worktree }, + instructions: instructions(profile, state.problem.ownedFiles, scoutBudgetMs), signal, + turnTimeoutMs: scoutBudgetMs, + ...usage.bindSession(sessionId, () => session?.lastInputTokens) }); + signal.throwIfAborted(); + if (!remainingMs()) throw new Error('math_portfolio_scout_timed_out'); + if (!modelDispatchAllowed(state.tokenBudget!)) { + scout.status = 'failed'; + return; + } + usage.sessionOpened(session); + state.turns++; scout.turns++; + const counts = state.dispatchCounts ??= {}; + counts.research = (counts.research ?? 0) + 1; + started = true; usage.begin(undefined, 'portfolio-' + profile); + emit('portfolio_scout_started', { profile, workerId }); + const attacks = profile === 'falsification-obstruction'; + const currentProposals = attacks ? proposals() : []; + const turnBudgetMs = Math.min(remainingMs(), scoutBudgetMs); + const wrapUpLeadMs = Math.min(60_000, Math.max(15_000, Math.floor(turnBudgetMs * 0.3))); + try { + const activeScout = session; + result = await activeScout.run(input.taskText + '\n\nRead the frozen statement in ' + state.problem.projectRelative + '.' + + (currentProposals.length ? '\nProposals to test:\n' + JSON.stringify(currentProposals) : ''), randomUUID(), worktree, + turnId => { + usage.turnStarted(turnId); + if (attacks) falsifier = activeScout; + const remaining = Math.min(remainingMs(), turnBudgetMs); + if (remaining <= 20_000) return; + wrapUpTimer = setTimeout(() => { + if (signal.aborted) return; + const notice = `Stop starting probes and stop any running experiments. Write or finalize ${reportFile} now ` + + 'with your best route, exact obstruction or reproducible refutation. Use inconclusive if needed. Save it atomically and return.'; + void activeScout.notify?.(notice, activeScout.advisoryNotifications === 'native-history' ? { mode: 'advisory' } : undefined) + .catch(async error => { + // Older app-servers may lack advisory history injection. Their normal steer still works. + if (!signal.aborted && activeScout.advisoryNotifications === 'native-history' && + error instanceof Error && error.message.startsWith('math_codex_rpc_failed:-32601:')) + await activeScout.notify?.(notice).catch(() => {}); + }); + }, Math.max(1000, remaining - wrapUpLeadMs)); + wrapUpTimer.unref(); + }); + } catch (error) { + if (!signal.aborted && !timedOut()) throw error; + } } finally { - try { await session?.close(); } - finally { - if (started) usage.finish(result === 'completed' || result === 'submitted'); - usage.sessionClosed(sessionId); + clearTimeout(wrapUpTimer); + if (falsifier === session) falsifier = undefined; + try { + const stopped = await session?.stopForFreeze?.(); + if (session && stopped?.status !== 'stopped') throw new Error('math_portfolio_scout_stop_unconfirmed'); + } finally { + try { await session?.close(); } + finally { + if (started) usage.finish(result === 'completed' || result === 'submitted'); + usage.sessionClosed(sessionId); + fs.rmSync(profileDirectory, { recursive: true, force: true }); + } } } - } - // Only accept validated advisory files. Reports atomically saved before a deadline remain useful. - if (fs.existsSync(path.join(worktree, reportFile)) && !input.signal.aborted) { - Object.assign(scout, readScoutReports(worktree, profile, state.problem)); - scout.status = 'reported'; - void falsifier?.notify?.('Scout route proposals to test:\n' + JSON.stringify(proposals()), - falsifier.advisoryNotifications === 'native-history' ? { mode: 'advisory' } : { waitForRequest: true }).catch(() => {}); - } else if (!input.signal.aborted) scout.status = signal.aborted ? 'timed-out' : 'failed'; - }); - } catch (error) { - if (!input.signal.aborted) scout.status = signal.aborted ? 'timed-out' : 'failed'; - emit('portfolio_scout_unavailable', { profile, status: scout.status, - reason: error instanceof Error && error.message === 'math_portfolio_scout_stop_unconfirmed' ? error.message : 'missing-or-invalid-scout-result' }); - } finally { changed(); } - emit('portfolio_scout_finished', { profile, status: scout.status, reports: scout.reports?.length ?? 0 }); - })); - const failure = outcomes.find(outcome => outcome.status === 'rejected'); - if (failure?.status === 'rejected') throw failure.reason; + // Only accept validated advisory files. Reports atomically saved before a deadline remain useful. + if (fs.existsSync(path.join(worktree, reportFile))) { + Object.assign(scout, readScoutReports(worktree, profile, state.problem)); + scout.status = 'reported'; + void falsifier?.notify?.('Scout route proposals to test:\n' + JSON.stringify(proposals()), + falsifier.advisoryNotifications === 'native-history' ? { mode: 'advisory' } : { waitForRequest: true }).catch(() => {}); + } else if (!input.signal.aborted) throw new Error('math_portfolio_scout_report_missing'); + }, portfolioWorktreeRoot); + } catch (error) { + if (!input.signal.aborted) scout.status = timedOut() ? 'timed-out' : 'failed'; + const reason = error instanceof Error ? /^math_[a-z0-9_]{1,72}(?=:|$)/u.exec(error.message)?.[0] : undefined; + emit('portfolio_scout_unavailable', { profile, workerId, status: scout.status, + reason: timedOut() ? 'math_portfolio_scout_timed_out' : reason ?? 'math_portfolio_scout_failed' }); + } finally { changed(); } + emit('portfolio_scout_finished', { profile, workerId, status: scout.status, reports: scout.reports?.length ?? 0 }); + })); + const failure = outcomes.find(outcome => outcome.status === 'rejected'); + if (failure?.status === 'rejected') throw failure.reason; + } finally { + clearTimeout(deadlineTimer); + for (const directory of [portfolioWorktreeRoot, portfolioProfileRoot]) { + if (fs.existsSync(directory) && fs.readdirSync(directory).length === 0) fs.rmdirSync(directory); + } + } input.signal.throwIfAborted(); input.assertCurrent?.(); portfolio.gate = evaluatePortfolioGate(portfolio.scouts.flatMap(scout => scout.reports ?? [])); diff --git a/src/solver/problem.ts b/src/solver/problem.ts index 5c0aa16c..64464d6a 100644 --- a/src/solver/problem.ts +++ b/src/solver/problem.ts @@ -430,16 +430,32 @@ export function commitSolverSources(problem: SolverProblem, worktree: string): s return git(worktree, ['rev-parse', 'HEAD']); } +const worktreeMutations = new Map>(); + +/** Serialize metadata changes across linked checkouts, leaving their work concurrent. */ +async function mutateWorktrees(repository: string, mutate: () => void): Promise { + const previous = worktreeMutations.get(repository) ?? Promise.resolve(); + const current = previous.then(mutate); + const settled = current.catch(() => {}); + worktreeMutations.set(repository, settled); + try { await current; } + finally { if (worktreeMutations.get(repository) === settled) worktreeMutations.delete(repository); } +} + /** Use a disposable checkout of a fixed commit and release it on every exit path. */ -export async function withSolverWorktree(worktree: string, commit: string, run: (checkout: string) => Promise): Promise { - const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'math-check-')); - const checkout = path.join(directory, 'worktree'); +export async function withSolverWorktree(worktree: string, commit: string, run: (checkout: string) => Promise, + parentDir?: string): Promise { + const repository = fs.realpathSync(git(worktree, ['rev-parse', '--path-format=absolute', '--git-common-dir'])); + const directory = fs.mkdtempSync(path.join(parentDir ?? os.tmpdir(), 'math-check-')); + // Process isolation masks a checkout's immediate parent to hide its peers. + const checkout = parentDir === undefined ? path.join(directory, 'worktree') : directory; let added = false; try { - git(worktree, ['worktree', 'add', '--quiet', '--detach', checkout, commit]); added = true; + await mutateWorktrees(repository, () => { git(worktree, ['worktree', 'add', '--quiet', '--detach', checkout, commit]); }); + added = true; return await run(checkout); } finally { - try { if (added) git(worktree, ['worktree', 'remove', '--force', checkout]); } + try { if (added) await mutateWorktrees(repository, () => { git(worktree, ['worktree', 'remove', '--force', checkout]); }); } finally { fs.rmSync(directory, { recursive: true, force: true }); } } } diff --git a/src/solver/research.ts b/src/solver/research.ts index 08878aab..63494410 100644 --- a/src/solver/research.ts +++ b/src/solver/research.ts @@ -52,6 +52,7 @@ import { buildSkillResearchContext, teamTurnTiming } from './skillResearchContex import { stopProofWriter } from './proofWriter'; import { createSkillProofLifecycle } from './skillProofLifecycle'; import { createSoftSlice, softSliceSettings, type SoftSliceSettings } from './softSlice'; +import { materializeResearchToolHelp } from './researchToolHelp'; import { portfolioUsageRecords } from './portfolioExploration'; // Scheduling checkpoints preserve unlimited solving budgets and resume the same assignment/thread. @@ -265,6 +266,8 @@ export async function runResearchWorkers(input: { if (skillResearch && !access.researchSkill) throw new Error('math_research_skill_missing'); const view = (): SolverRunState => ({ ...state, ...research, turns: state.turns }); const emit = (event: string, details = {}) => input.emit(event, { workerId: worker.id, ...details }); + // The host has one Lead writer in team mode too. This watches the full-proof Lean diagnostic, + // while the stopped-writer Skill lifecycle handles optional declaration nominations. const singleHandoff = !parallel ? new SingleSolverProofHandoff(state.problem, worker.worktree, submission => emit('proof_ready_checkpoint_requested', { ...submission, reason: 'current-lean-diagnostics' })) : undefined; // Cooperative callers keep their existing stopped-writer quarantine; other callers receive exact correction feedback. @@ -314,6 +317,7 @@ export async function runResearchWorkers(input: { const currentContext = { ...(skillMode && !fullSkillWorkflow && !access.commonResearchSkill ? buildSkillResearchContext(state.problem, contextState, { ...contextAccess, researchSkill: access.researchSkill! }) : modules.M4.build(state.problem, contextState, contextAccess)), ...(assignment ? { assignment } : {}) }; + materializeResearchToolHelp(currentContext, worker.worktree); if (assignment?.kind === 'task' && scoped) { const basis = captureResearchBasis(assignment.task, { problemReceiptDigest: state.problem.receiptDigest, environmentDigest: state.environmentDigest, @@ -562,9 +566,12 @@ export async function runResearchWorkers(input: { notice: (reason, completedCompactions) => { emit(reason === 'time' ? 'soft_slice_milestone_requested' : 'compaction_circuit_breaker_triggered', { turnId: milestoneTurnId, completedCompactions, graceMs: milestoneSettings.graceMs }); - const submission = assignment?.kind === 'task' + const submission = team + ? 'Use theoremos_team route_summary to review the team. Collect useful checked results and coordinate active teammates. ' + + 'If slots are free, delegate focused independent obligations using the team tools. ' + : assignment?.kind === 'task' ? 'Publish standalone helpers as a helpers event in the assignment delivery log. ' - : skillMode ? 'Nominate standalone helpers for host checking in .scratch/declaration-submission.json. ' + : skillMode ? 'Write .scratch/declaration-submission.json only if you have at least one locally compiled standalone helper to nominate. Never write an empty declarations array. ' : 'Save standalone helpers in the owned Lean files for host checking. '; void activeSession.notify?.(submission + 'Write fewer than 20 lines in worktree-root RESEARCH.md covering what is established, the exact obstruction, ' + diff --git a/src/solver/researchGuidance.ts b/src/solver/researchGuidance.ts index 07c665e0..b0ce8b09 100644 --- a/src/solver/researchGuidance.ts +++ b/src/solver/researchGuidance.ts @@ -20,7 +20,7 @@ import { assignmentDeliveryFile, isAdvisoryTask, isFeasibilityReview, isFinalCan /** Static shared guidance also serves a native single-task baseline without manufacturing solver state. */ export function buildCommonResearchGuide(problem: SolverProblem, access: Pick, environmentDigest: string, + 'retrievalRoot' | 'knowledgeFile' | 'knowledgeDigest' | 'libraryCatalog' | 'assignment'>, environmentDigest: string, purpose: 'comparison' | 'workflow' = 'comparison') { const { command, help, longCommandSummary } = buildResearchToolGuide(problem, access, environmentDigest); materializeResearchToolHelp({ toolHelp: help.build() }, access.worktree); @@ -125,18 +125,20 @@ export function cooperativeHelperProtocol(task: CooperativeTask, log: string): s (isAdvisoryTask(task) ? 'Restore your temporary Lean edits after the host acknowledges the submission and before ordinary findings delivery. ' : ''); } +export const leadPlanToolInstruction = 'Read Lead plan submission in .scratch/theoremos-help.md. Validate the draft JSON before publishing. Omit progressReview on the initial plan.\n'; + export function cooperativeDeliveryProtocol(action: NonNullable, taskLog?: string): string { if (action.kind === 'review') return 'Review the fixed candidate and matching evidence without editing it. ' + 'Save one JSON object in RESEARCH.md: {"verdict":"accepted|changes_requested","summary":"...","evidenceRefs":[]}, then return. '; if (action.kind === 'lead') { const nonce = action.initialPlanNonce ?? action.planNonce; - return 'Publish a complete task graph covering every original target exactly once, preserving current checked contracts and active assignments. ' + + return leadPlanToolInstruction + 'Publish a complete task graph covering every original target exactly once, preserving current checked contracts and active assignments. ' + 'Tasks use {id,kind,objective,dependsOn}; typed lemma tasks also need proofPath, theoremName and a full closed Lean type. ' + 'Copy exact original target names and proof paths from the fixed problem. Task status is active|paused|stopped, never host executionStatus. ' + `Append one JSON line to ${leadPlanDeliveryFile(action)}: ` + JSON.stringify({ kind: 'plan', baseVersion: action.planVersion, ...(nonce ? { dispatchNonce: nonce } : {}), summary: 'route and current work', tasks: [] }) + '. Replace the empty tasks array with the actual complete graph. ' + - 'Current required researchDecisions, progressReview and nextCheckDecisions belong in that same object. ' + + 'Include researchDecisions, nextCheckDecisions and any progressReview requested by the host in that same object. ' + 'Assign small shared foundation lemmas before their consumers and delegate exploratory computation. To stop work on a refuted group or proof route, use retireRoutes:[{routeId,reason,evidenceRefs}] in the current plan. ' + 'Alternatively save the complete graph in one math-plan JSON fence in RESEARCH.md and return. ' + 'Do not truncate delivery logs, modify run state, accept unchecked tasks or wait for human plan approval yourself. '; diff --git a/src/solver/researchToolGuide.ts b/src/solver/researchToolGuide.ts index 8d0065b1..8df21c25 100644 --- a/src/solver/researchToolGuide.ts +++ b/src/solver/researchToolGuide.ts @@ -16,10 +16,13 @@ export const longCommandGuidance = /** Shared optional tool reference; callers retain their own mandatory delivery contracts. */ export function buildResearchToolGuide(problem: Pick, access: Pick, environmentDigest: string, + 'knowledgeFile' | 'knowledgeDigest' | 'libraryCatalog' | 'teamRole' | 'assignment'>, environmentDigest: string, teamTransport?: AgentTeamTransport) { const command = `bun ${quote(access.tools ?? path.join(access.root, 'bin/math.ts'))}`; const help = new ResearchToolHelpBuilder(); + if (access.assignment?.kind === 'lead') help.section('Lead plan submission', + `Omit progressReview on the initial plan. Before publishing, validate the draft with ${command} plan-validate --file .scratch/plan.json\n` + + `To submit the validated draft on return, save it atomically to RESEARCH.md with ${command} plan-apply --file .scratch/plan.json`, ''); const editable = new Set(problem.ownedFiles.filter(file => file.endsWith('.lean') && !Object.hasOwn(problem.frozenFiles ?? {}, file))); const file = problem.targets.find(target => editable.has(target.proofPath))?.proofPath ?? editable.values().next().value; const leanCheckCommand = file && `${command} check-lean --worktree ${quote(access.worktree)} --file ${quote(file)} --timeout-seconds 0`; diff --git a/src/solver/researchUsage.ts b/src/solver/researchUsage.ts index 927c5db5..67556c39 100644 --- a/src/solver/researchUsage.ts +++ b/src/solver/researchUsage.ts @@ -160,7 +160,8 @@ export class ResearchUsage { } const before = research.usage; const priorTotal = reportedTotalTokens(before), total = reportedTotalTokens(usage), baseline = reportedTotalTokens(research.usageBeforeThread) ?? 0; - if (scope?.finished && total !== null && priorTotal !== null && total + baseline <= priorTotal) return; + // A resumed thread may replay its prior cumulative total before the next turn exists. + if (((!scope && !this.active) || scope?.finished) && total !== null && priorTotal !== null && total + baseline <= priorTotal) return; const reported = recordThreadUsage(research, usage); const index = scope ? nativeTurns.indexOf(scope) : -1; const previousUnreported = index > 0 && nativeTurns.slice(0, index).some(turn => !turn.reported); diff --git a/src/solver/skillProofLifecycle.ts b/src/solver/skillProofLifecycle.ts index fc9c0065..b25548d5 100644 --- a/src/solver/skillProofLifecycle.ts +++ b/src/solver/skillProofLifecycle.ts @@ -79,7 +79,9 @@ export function createSkillProofLifecycle(input: { try { let artifacts: Awaited>; try { - const submission = readDeclarationSubmission(worktree)!; + // A Lead may have nothing of its own to publish while teammates work. + const submission = readDeclarationSubmission(worktree, { allowEmpty: state.researchDelegation?.mode === 'team' }); + if (!submission) { consumed = true; return; } artifacts = await input.exclusiveCheck(() => checkDeclarationArtifacts({ state, worktree, commit, declarations: submission.declarations, env: environment, signal, timeoutMs: input.proofTimeoutMs, assertWriterStopped: () => { diff --git a/src/solver/skillResearchContext.ts b/src/solver/skillResearchContext.ts index 2bad8a9f..033929fd 100644 --- a/src/solver/skillResearchContext.ts +++ b/src/solver/skillResearchContext.ts @@ -78,14 +78,14 @@ export function buildSkillResearchContext(problem: SolverProblem, state: Readonl 'Save useful source and worktree-root RESEARCH.md before returning. The host confirms writer shutdown and freezes actual source. ' + 'A successful check-lean covering every original proof file, with no remaining proof holes, also hands writing back automatically. ' + 'Only independent host checks of all original targets can accept the original problem.\n' + - 'To publish independent declarations while the original problem is unfinished, write ' + + 'Only if you have at least one locally compiled standalone declaration ready for host checking, write ' + JSON.stringify(path.join(access.worktree, '.scratch/declaration-submission.json')) + ' containing ' + '{"declarations":[{"file":"OWNED_FILE.lean","name":"Qualified.helper","type":"COMPLETE_CLOSED_LEAN_TYPE"}]}, then stop editing and return. ' + - 'Optional description and premises describe scope, not additional proof authority. The host verifies each actual declaration and complete type independently. ' + + 'Never write an empty declarations array. Optional description and premises describe scope. The host verifies each actual declaration and complete type independently. ' + 'Other incomplete goals may remain; a helper that depends on them or on new axioms is rejected. ' + 'The request is consumed after the turn, and its host feedback is saved at .scratch/declaration-feedback.json. ' + - 'It never claims the original problem is solved. No task graph, role acknowledgment or fabricated receipt is required. ' + - 'When the host requests a soft milestone handoff, submit available standalone helpers, record progress and the exact obstruction in fewer than 20 lines in RESEARCH.md, then return.'; + 'It never claims the original problem is solved. ' + + 'At a soft milestone, record progress and the exact obstruction in fewer than 20 lines in RESEARCH.md, then return.'; help.section('delivery', teamWorker ? agentTeamWorkerDeliveryHelp() : team ? 'Member delivery contract, supplied by the host: ' + agentTeamWorkerDeliveryHelp() + '\n\n' + 'The following declaration-submission file is only for your own Lead worktree; do not assign it to a member. ' + ownDelivery : ownDelivery, ''); diff --git a/tests/codexSession.test.ts b/tests/codexSession.test.ts index fd4bbe59..67705ffb 100644 --- a/tests/codexSession.test.ts +++ b/tests/codexSession.test.ts @@ -6,6 +6,7 @@ import { createCodexMathSession, mathWorkerPermissionConfig, type MathAgentOptio import { deepSeekProfileDigest, prepareDeepSeekProfile } from '../src/runtime/deepseek'; import { prepareWestlakeProfile, westlakeProfileDigest } from '../src/runtime/westlake'; import { prepareSub2apiProfile, sub2apiProfileDigest } from '../src/runtime/sub2api'; +import { assertResearchHarnessCurrent, bindResearchHarness } from '../src/runtime/researchHarness'; import { nativeFileWatchFixture } from './helpers/nativeFileWatchFixture'; describe('Codex app-server adapter without provider calls', () => { @@ -48,8 +49,9 @@ readline.createInterface({ input: process.stdin }).on('line', line => { if (fixtureInstruction === 'startup-crash') return process.exit(27); if (fixtureInstruction === 'mutate-profile') { const config = process.env.CODEX_HOME + '/config.toml'; - fs.writeFileSync(config + '.updated', fs.readFileSync(config, 'utf8') + '\\n[projects.fixture]\\ntrust_level = "trusted"\\n'); - fs.renameSync(config + '.updated', config); + const update = config + '.' + process.pid + '.updated'; + fs.writeFileSync(update, fs.readFileSync(config, 'utf8') + '\\n[projects.fixture]\\ntrust_level = "trusted"\\n'); + fs.renameSync(update, config); } result({ thread: { id: fixtureInstruction === 'wrong-thread' ? 'wrong-thread' : settings.threadId || 'thread-fixture' }, model: fixtureInstruction === 'mismatch' ? 'wrong-model' : settings.model, @@ -192,7 +194,7 @@ readline.createInterface({ input: process.stdin }).on('line', line => { return; } if (process.env.THEOREM_OS_FIXTURE_REPAIR_JSON) { - const file = process.env.CODEX_HOME + '/OUTPUT.json'; + const file = path.join(settings.cwd, 'OUTPUT.json'); fs.writeFileSync(file + '.tmp', process.env.THEOREM_OS_FIXTURE_REPAIR_JSON); fs.renameSync(file + '.tmp', file); } @@ -207,10 +209,40 @@ readline.createInterface({ input: process.stdin }).on('line', line => { }); afterEach(async () => { await session?.close(); vi.unstubAllEnvs(); fs.rmSync(root, { recursive: true, force: true }); }); + it('protects the pinned Web provider config across concurrent sessions without native agent control', async () => { + const profile = path.join(root, 'web-profile'), workspaces = ['scout-one', 'scout-two'].map(name => path.join(root, name)); + for (const directory of [profile, ...workspaces]) fs.mkdirSync(directory); + const catalog = path.join(profile, 'models.json'), configFile = path.join(profile, 'config.toml'); + fs.writeFileSync(catalog, '{"models":[]}'); + const config = Buffer.from('model_provider = "web_provider"\nmodel_catalog_json = ' + JSON.stringify(catalog) + + '\n[model_providers.web_provider]\nbase_url = "https://fixture.invalid/v1"\nwire_api = "responses"\nenv_key = "FIXTURE_API_KEY"\n'); + fs.writeFileSync(configFile, config); + const environment = { PATH: process.env.PATH, FIXTURE_API_KEY: 'fixture-only' }; + const identity = bindResearchHarness('codex', options.executable, profile, environment, options.model); + const opened = await Promise.allSettled(workspaces.map(workspace => createCodexMathSession({ + ...options, profile, workspace, environment, instructions: 'mutate-profile', + }))); + try { + expect(opened.map(result => result.status === 'rejected' ? result.reason.message : result.status)) + .toEqual(['fulfilled', 'fulfilled']); + const runtime = path.join(profile, 'runtime'); + expect(fs.readFileSync(path.join(runtime, 'config.toml'), 'utf8')).toContain('[projects.fixture]'); + expect(fs.readdirSync(runtime).filter(file => file.startsWith('.config-'))).toEqual([]); + const launches = fs.readFileSync(path.join(runtime, 'calls.jsonl'), 'utf8').trim().split('\n') + .map(line => JSON.parse(line)).filter(call => call.method === 'thread/start'); + expect(launches).toHaveLength(2); + for (const { params } of launches) expect(params.config.model_catalog_json).toBe(catalog); + expect(fs.readFileSync(configFile)).toEqual(config); + expect(() => assertResearchHarnessCurrent(identity, environment, options.model)).not.toThrow(); + } finally { + await Promise.all(opened.flatMap(result => result.status === 'fulfilled' ? [result.value.close()] : [])); + } + }); + it('does not expose the host library configuration path to the agent process', async () => { vi.stubEnv('THEOREMOS_LIBRARY_HOST_CONFIG', '/host/private/library-config.json'); session = await createCodexMathSession(options); - expect(JSON.parse(fs.readFileSync(path.join(root, 'library-host-environment.json'), 'utf8'))) + expect(JSON.parse(fs.readFileSync(path.join(root, 'runtime', 'library-host-environment.json'), 'utf8'))) .toEqual({ hostConfigPresent: false }); }); @@ -345,7 +377,7 @@ readline.createInterface({ input: process.stdin }).on('line', line => { it('keeps canonical shell filters when excluding a custom provider credential', async () => { fs.writeFileSync(path.join(root, 'config.toml'), 'model_provider = "custom"\n[model_providers.custom]\nenv_key = "FIXTURE_API_KEY"\n[shell_environment_policy.filters]\nPATH = "include"\n'); session = await createCodexMathSession({ ...options, environment: { PATH: process.env.PATH, FIXTURE_API_KEY: 'fixture-key' } }); - const calls = fs.readFileSync(path.join(root, 'calls.jsonl'), 'utf8').trim().split('\n').map(line => JSON.parse(line)); + const calls = fs.readFileSync(path.join(root, 'runtime', 'calls.jsonl'), 'utf8').trim().split('\n').map(line => JSON.parse(line)); const config = calls.find(call => call.method === 'thread/start').params.config; expect(config['shell_environment_policy.filters']).toEqual({ PATH: 'include', FIXTURE_API_KEY: 'exclude' }); expect(config).not.toHaveProperty('shell_environment_policy.exclude'); @@ -358,7 +390,7 @@ readline.createInterface({ input: process.stdin }).on('line', line => { expect(started).toHaveBeenCalledWith('message-1'); expect(options.onUsage).toHaveBeenCalledWith({ totalTokens: 21 }, {}); expect(session.lastInputTokens).toBe(12345); - const calls = fs.readFileSync(path.join(root, 'calls.jsonl'), 'utf8').trim().split('\n').map(line => JSON.parse(line)); + const calls = fs.readFileSync(path.join(root, 'runtime', 'calls.jsonl'), 'utf8').trim().split('\n').map(line => JSON.parse(line)); expect(calls.find(call => call.method === 'thread/start').params.config).toMatchObject({ 'features.apps': false, 'features.plugins': false, }); @@ -397,7 +429,7 @@ readline.createInterface({ input: process.stdin }).on('line', line => { it('refuses a new thread whose app-server did not adopt the worker profile', async () => { await expect(createCodexMathSession({ ...options, instructions: 'ignore-permissions' })) .rejects.toThrow('math_codex_sandbox_profile_mismatch'); - const calls = fs.readFileSync(path.join(root, 'calls.jsonl'), 'utf8'); + const calls = fs.readFileSync(path.join(root, 'runtime', 'calls.jsonl'), 'utf8'); expect(calls).not.toContain('turn/start'); // A resumed thread keeps the sandbox it started with, so its response is not evidence either way. session = await createCodexMathSession({ ...options, threadId: 'retained-thread', instructions: 'ignore-permissions' }); @@ -638,7 +670,7 @@ readline.createInterface({ input: process.stdin }).on('line', line => { it('rejects an invalid proof environment before launching the app-server', async () => { await expect(createCodexMathSession({ ...options, proofProjectRoot: root, environment: { DEEPSCIENTIST_MATH_PROOF_ENVIRONMENT: '{}' } })).rejects.toThrow(); - expect(fs.existsSync(path.join(root, 'calls.jsonl'))).toBe(false); + expect(fs.existsSync(path.join(root, 'runtime', 'calls.jsonl'))).toBe(false); }); it('isolates mathematical temporary files by worktree and overrides inherited shell settings', async () => { @@ -652,9 +684,9 @@ readline.createInterface({ input: process.stdin }).on('line', line => { const temporaryDirectory = path.join(workspace, '.scratch', 'tmp'); expect(fs.readFileSync(path.join(temporaryDirectory, `${name}.txt`), 'utf8')).toBe('temporary fixture'); expect(fs.existsSync(path.join(project, '.scratch'))).toBe(false); - expect(JSON.parse(fs.readFileSync(path.join(root, 'temporary-environment.json'), 'utf8'))) + expect(JSON.parse(fs.readFileSync(path.join(root, 'runtime', 'temporary-environment.json'), 'utf8'))) .toEqual({ inherited: temporaryDirectory, shell: temporaryDirectory }); - const calls = fs.readFileSync(path.join(root, 'calls.jsonl'), 'utf8').trim().split('\n').map(line => JSON.parse(line)); + const calls = fs.readFileSync(path.join(root, 'runtime', 'calls.jsonl'), 'utf8').trim().split('\n').map(line => JSON.parse(line)); expect(calls.filter(call => call.method === 'thread/start').at(-1).params.config['shell_environment_policy.set']) .toEqual({ TMPDIR: temporaryDirectory, LANG: 'C.UTF-8' }); expect(calls.filter(call => call.method === 'thread/start').at(-1).params.config['permissions.math-worker.filesystem']) @@ -685,7 +717,7 @@ readline.createInterface({ input: process.stdin }).on('line', line => { await expect(createCodexMathSession({ ...options, workspace, proofProjectRoot: workspace, environment: { PATH: process.env.PATH } })).rejects.toThrow('math_path_invalid'); expect(fs.readdirSync(outside)).toEqual([]); - expect(fs.existsSync(path.join(root, 'calls.jsonl'))).toBe(false); + expect(fs.existsSync(path.join(root, 'runtime', 'calls.jsonl'))).toBe(false); }); it('rejects a scratch symlink inserted between turns before dispatching another turn', async () => { @@ -698,7 +730,7 @@ readline.createInterface({ input: process.stdin }).on('line', line => { fs.symlinkSync(outside, path.join(workspace, '.scratch')); await expect(session.run('temporary-file', 'unsafe', workspace, () => {})).rejects.toThrow('math_path_invalid'); expect(fs.readdirSync(outside)).toEqual([]); - const calls = fs.readFileSync(path.join(root, 'calls.jsonl'), 'utf8').trim().split('\n').map(line => JSON.parse(line)); + const calls = fs.readFileSync(path.join(root, 'runtime', 'calls.jsonl'), 'utf8').trim().split('\n').map(line => JSON.parse(line)); expect(calls.filter(call => call.method === 'turn/start')).toHaveLength(1); }); @@ -708,7 +740,7 @@ readline.createInterface({ input: process.stdin }).on('line', line => { expect(await session.run('temporary-file', 'generic', root, () => {})).toBe('completed'); expect(fs.readFileSync(path.join(inherited, 'generic.txt'), 'utf8')).toBe('temporary fixture'); expect(fs.existsSync(path.join(root, '.scratch'))).toBe(false); - const calls = fs.readFileSync(path.join(root, 'calls.jsonl'), 'utf8').trim().split('\n').map(line => JSON.parse(line)); + const calls = fs.readFileSync(path.join(root, 'runtime', 'calls.jsonl'), 'utf8').trim().split('\n').map(line => JSON.parse(line)); expect(calls.find(call => call.method === 'thread/start').params.config).not.toHaveProperty('shell_environment_policy.set'); }); @@ -753,7 +785,7 @@ readline.createInterface({ input: process.stdin }).on('line', line => { await session.notify!('A checked dependency is available'); await session.interrupt(); expect(await done).toBe('interrupted'); - const calls = fs.readFileSync(path.join(root, 'calls.jsonl'), 'utf8').trim().split('\n').map(line => JSON.parse(line)); + const calls = fs.readFileSync(path.join(root, 'runtime', 'calls.jsonl'), 'utf8').trim().split('\n').map(line => JSON.parse(line)); expect(calls.filter(call => call.method === 'turn/steer').map(call => call.params)).toEqual([{ threadId: 'thread-fixture', expectedTurnId: 'active-turn', input: [{ type: 'text', text: 'A checked dependency is available', text_elements: [] }], @@ -852,7 +884,7 @@ readline.createInterface({ input: process.stdin }).on('line', line => { session = await createCodexMathSession({ ...options, turnTimeoutMs: 30 }); expect(await session.run('wait', 'long-turn', root, () => {})).toBe('checkpoint'); expect(await session.run('proof', 'next-turn', root, () => {})).toBe('completed'); - const calls = fs.readFileSync(path.join(root, 'calls.jsonl'), 'utf8').trim().split('\n').map(line => JSON.parse(line)); + const calls = fs.readFileSync(path.join(root, 'runtime', 'calls.jsonl'), 'utf8').trim().split('\n').map(line => JSON.parse(line)); expect(calls.filter(call => call.method === 'turn/interrupt')).toHaveLength(1); }); @@ -860,9 +892,9 @@ readline.createInterface({ input: process.stdin }).on('line', line => { if (!value || typeof value !== 'object' || (value as Record).answer !== 'valid') throw new Error('invalid fixture submission'); }; - const interrupts = (directory: string) => fs.readFileSync(path.join(directory, 'calls.jsonl'), 'utf8').trim().split('\n') + const interrupts = (directory: string) => fs.readFileSync(path.join(directory, 'runtime', 'calls.jsonl'), 'utf8').trim().split('\n') .map(line => JSON.parse(line)).filter(call => call.method === 'turn/interrupt'); - const calls = (directory: string) => fs.readFileSync(path.join(directory, 'calls.jsonl'), 'utf8').trim().split('\n') + const calls = (directory: string) => fs.readFileSync(path.join(directory, 'runtime', 'calls.jsonl'), 'utf8').trim().split('\n') .map(line => JSON.parse(line)); it('steers an invalid exact quote and admits its repaired unknown in the original turn', async () => { @@ -1057,7 +1089,7 @@ readline.createInterface({ input: process.stdin }).on('line', line => { it('rejects a mismatched model before any provider request and fails a disconnected turn', async () => { await expect(createCodexMathSession({ ...options, instructions: 'mismatch' })).rejects.toThrow('math_codex_session_binding_mismatch'); await expect(createCodexMathSession({ ...options, threadId: 'retained-thread', instructions: 'wrong-thread' })).rejects.toThrow('math_codex_session_binding_mismatch'); - const calls = fs.readFileSync(path.join(root, 'calls.jsonl'), 'utf8'); + const calls = fs.readFileSync(path.join(root, 'runtime', 'calls.jsonl'), 'utf8'); expect(calls).not.toContain('turn/start'); session = await createCodexMathSession(options); await expect(session.run('crash', 'message-4', root, () => {})).rejects.toThrow('math_codex_transport_closed'); diff --git a/tests/fullSkillWorkflow.test.ts b/tests/fullSkillWorkflow.test.ts index 82286e3d..ecdb9818 100644 --- a/tests/fullSkillWorkflow.test.ts +++ b/tests/fullSkillWorkflow.test.ts @@ -5,6 +5,7 @@ import { canonicalMathJson, mathDigest } from '../src/math/mathRuntimeIo'; import { readMathAgentSkill } from '../src/runtime/agentSkills'; import { rejectedDeliveryReceipt } from '../src/solver/deliveryReceipts'; import { prepareResearchSkill, researchSkillIdentity } from '../src/solver/researchSkill'; +import { materializeResearchToolHelp } from '../src/solver/researchToolHelp'; import { buildResearchContext, finalizeResearchDispatch } from '../src/solver/modules/context'; import { buildRunInspection, renderRunInspection } from '../src/solver/inspection'; import { assignmentDeliveryFile, leadPlanDeliveryFile, parseCooperationPlan, taskVersion } from '../src/solver/tasks'; @@ -51,9 +52,15 @@ describe('Skill methods with complete host workflows', () => { expect(context.instructions).toContain('Keep the user-selected method available.'); expect(context.instructions).toContain('Leave every Lean source unchanged'); expect(context.instructions).toContain(leadPlanDeliveryFile(action)); + const leadHelp = fs.readFileSync(path.join(f.workspace, '.scratch/theoremos-help.md'), 'utf8'); + expect(leadHelp.split(/^## /mu)[1]).toMatch(/^Lead plan submission\b/u); + expect(leadHelp).toContain('Omit progressReview on the initial plan'); + expect(context.instructions).toContain('Validate the draft JSON before publishing'); + expect(leadHelp).toMatch(/plan-validate --file \.scratch\/plan\.json\n[^\n]+plan-apply --file \.scratch\/plan\.json/u); const reference = path.join(path.dirname(f.skill.path), 'references/cooperation.md'); expect(context.instructions).toContain(reference); const protocol = fs.readFileSync(reference, 'utf8'); + expect(protocol).toContain('Omit `progressReview` on the initial plan'); for (const field of ['proofRoutes', 'conditional', 'definition', 'family', 'statementReview', 'researchDecisions', 'nextCheckDecisions', 'guidanceDecisions', 'replacesReceipt']) expect(protocol).toContain(field); expect(context.workContract?.stage).toBe('route-planning'); @@ -72,6 +79,19 @@ describe('Skill methods with complete host workflows', () => { expect(next.manifest!.usedBytes).toBeLessThan(context.manifest!.usedBytes); }); + it('materializes bundled plan commands for a cooperative Lead without the full Skill workflow', () => { + const f = fixture(); + const action = { kind: 'lead' as const, seedCommit: f.problem.baseCommit, planVersion: 'initial', initialPlanNonce: 'start' }; + const tools = path.join(f.directory, 'agent-tools', 'math.mjs'); + const context = buildResearchContext(f.problem, { ...f.state, researchSkillWorkflow: undefined }, + { ...f.access, assignment: action, tools }); + materializeResearchToolHelp(context, f.workspace); + const help = fs.readFileSync(path.join(f.workspace, '.scratch/theoremos-help.md'), 'utf8'); + expect(help.split(/^## /mu)[1]).toContain(`bun '${tools}' plan-validate --file .scratch/plan.json`); + expect(help).toContain(`bun '${tools}' plan-apply --file .scratch/plan.json`); + expect(context.instructions).toContain('Omit progressReview on the initial plan'); + }); + it('keeps exact proof inputs, consumer context and mandatory failure feedback on task continuation', () => { const f = fixture(); const node = f.state.cooperation!.tasks.find(item => item.task.id === 'helper')!; @@ -85,9 +105,11 @@ describe('Skill methods with complete host workflows', () => { expect(context.message).toContain(assignment.taskDigest); expect(context.message).toContain('CURRENT_EXACT_TYPE_ERROR'); expect(context.message).toContain(f.state.cooperation!.tasks[0]!.task.theoremName); - expect(context.instructions).toContain(assignmentDeliveryFile(assignment)); + expect(context.instructions).toContain('delivery log named in the assignment message'); + expect(context.message).toContain(assignmentDeliveryFile(assignment)); expect(context.workContract?.input).toMatchObject({ taskId: 'helper', taskDigest: assignment.taskDigest }); const help = fs.readFileSync(path.join(f.workspace, '.scratch/theoremos-help.md'), 'utf8'); + expect(help).not.toContain('Lead plan submission'); expect(help).toContain("bun '" + tools.replaceAll("'", "'\\''") + "' research-observe"); const continued = finalizeResearchDispatch(context, { continuation: true }); expect(continued.message).toContain('CURRENT_EXACT_TYPE_ERROR'); diff --git a/tests/solverPortfolioGate.test.ts b/tests/solverPortfolioGate.test.ts index 4b75bdb3..60097e23 100644 --- a/tests/solverPortfolioGate.test.ts +++ b/tests/solverPortfolioGate.test.ts @@ -1,15 +1,21 @@ import fs from 'node:fs'; import path from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vitest'; +import { bootstrapLocalExample } from '../src/math/localExample'; +import { isMathPathWithin } from '../src/math/paths'; import type { MathAgentOptions, MathAgentSession } from '../src/runtime/agentSession'; +import { prepareHarnessProcess } from '../src/runtime/harnessProcess'; +import { assertResearchHarnessCurrent, bindResearchHarness } from '../src/runtime/researchHarness'; import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; import { buildRunInspection } from '../src/solver/inspection'; import { configurePortfolioExploration, evaluatePortfolioGate, portfolioPhase2Guidance, runPortfolioExploration, type PortfolioScoutReport } from '../src/solver/portfolioExploration'; +import { git, readSolverProblem } from '../src/solver/problem'; import { localExample, solverState } from './helpers/solver'; +import { deferred } from './helpers/async'; const roots: string[] = []; -afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); }); +afterEach(() => { vi.useRealTimers(); for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); }); const foundation = { id: 'base-change-of-variables', proofPath: 'Submission.lean', theoremName: 'Portfolio.sharedBase', type: '∀ (n : Nat), n + 0 = n', objective: 'Prove the shared change of variables separately.' }; @@ -29,14 +35,23 @@ const assignment = (options: MathAgentOptions) => options.environment!.DEEPSCIEN PortfolioScoutReport['profile']; const withoutProfile = ({ profile: _, ...result }: PortfolioScoutReport) => result; -function fixture(durationMs = 1000, capacity = 3) { - const { directory, workspace, problem } = localExample('portfolio-gate-'); +function mountFixture(directory: string) { roots.push(directory); + const workspace = path.join(directory, 'worktree'); + const { activeProblemPath } = bootstrapLocalExample(workspace); + return { directory, workspace, problem: readSolverProblem(workspace, activeProblemPath) }; +} + +function fixture(durationMs = 1000, capacity = 3, example = localExample('portfolio-gate-')) { + const { directory, workspace, problem } = example; + if (!roots.includes(directory)) roots.push(directory); const state = solverState(problem, workspace, { phase: 'prepared', runId: 'portfolio-fixture', workerCount: capacity }); state.portfolioExploration = configurePortfolioExploration(undefined, { enable: true, durationMs, capacity, startedResearch: false }); const stateFile = path.join(directory, 'state.json'); const events: { event: string; details?: Record }[] = []; - const input = { state, taskText: 'Prove the original statement.', executable: 'offline', profile: 'offline', maxTurns: 4, + const profile = path.join(directory, 'codex'); + fs.mkdirSync(profile, { mode: 0o700 }); + const input = { state, taskText: 'Prove the original statement.', executable: 'offline', profile, maxTurns: 4, maxTurnMs: Infinity, maxTotalTokens: 1000, remainingMs: () => Infinity, signal: new AbortController().signal, prepareWorkspace: (workspace: string) => ({ project: path.join(workspace, problem.projectRelative), environment: {} }), emit: (event: string, details?: Record) => { events.push({ event, details }); }, @@ -94,6 +109,12 @@ describe('portfolio exploration gate', () => { expect(opened.map(assignment)).toEqual(['structural-symmetry', 'explicit-constructive', 'falsification-obstruction']); expect(new Set(opened.map(options => options.workspace)).size).toBe(3); expect(opened.every(options => options.isolateProcess && options.workspace !== state.worktree && !fs.existsSync(options.workspace))).toBe(true); + const parent = path.join(path.dirname(state.worktree), 'portfolio-worktrees'); + for (const { workspace, isolatedWorkspaceParent } of opened) { + expect(path.dirname(workspace)).toBe(parent); + expect(isolatedWorkspaceParent).toBe(parent); + } + expect(fs.existsSync(parent)).toBe(false); expect(opened[0].instructions).toContain('symmetries'); expect(opened[1].instructions).toContain('rational bound'); expect(opened[2].instructions).toContain('counterexamples'); @@ -115,6 +136,105 @@ describe('portfolio exploration gate', () => { expect(open).not.toHaveBeenCalled(); }); + it.skipIf(process.platform !== 'linux' || !fs.existsSync('/usr/bin/bwrap'))( + 'masks /tmp and scout peers in the launch, then unregisters even a failed startup', async () => { + // Match the worker image layout, where the run and profile are both outside /tmp. + const directory = fs.mkdtempSync(path.join(fs.realpathSync(process.cwd()), '.portfolio-mount-test-')); + const { state, input, events } = fixture(5000, 2, mountFixture(directory)); + const profile = input.profile, catalog = path.join(profile, 'models.json'); + const config = `model_provider = "web_provider"\nmodel_catalog_json = ${JSON.stringify(catalog)}\n`; + fs.writeFileSync(catalog, '{"models":[]}'); + fs.writeFileSync(path.join(profile, 'config.toml'), config); + const identity = bindResearchHarness('codex', '/bin/true', profile, {}, state.model); + const parent = path.join(directory, 'portfolio-worktrees'); + const profilesRoot = path.join(directory, 'portfolio-profiles'); + const worktreesBefore = git(state.worktree, ['worktree', 'list', '--porcelain']); + const launches: ReturnType[] = []; + const opened: MathAgentOptions[] = []; + const modes: number[] = []; + const bothOpened = deferred(); + await runPortfolioExploration({ ...input, profile, open: async options => { + modes.push(fs.statSync(parent).mode & 0o777); + opened.push(options); + if (opened.length === 2) bothOpened.resolve(); + await bothOpened.promise; + expect(fs.statSync(options.profile).mode & 0o777).toBe(0o700); + expect(fs.readFileSync(path.join(options.profile, 'config.toml'), 'utf8')).toBe(config); + const runtime = path.join(options.profile, 'runtime'); + fs.mkdirSync(runtime, { mode: 0o700 }); + launches.push(prepareHarnessProcess({ ...options, profile: runtime }, '/bin/true', [])); + fs.writeFileSync(path.join(runtime, 'state_5.sqlite'), options.workspace, { flag: 'wx' }); + expect(fs.readFileSync(path.join(runtime, 'state_5.sqlite'), 'utf8')).toBe(options.workspace); + throw new Error('math_codex_rpc_failed:-32603:thread/start:private startup diagnostic'); + } }); + expect(modes).toEqual([0o700, 0o700]); + expect(launches).toHaveLength(2); + expect(new Set(opened.map(options => options.profile)).size).toBe(2); + for (const [index, launch] of launches.entries()) { + const options = opened[index], runtime = path.join(options.profile, 'runtime'); + expect(path.dirname(path.dirname(options.profile))).toBe(profilesRoot); + expect(isMathPathWithin(parent, options.profile)).toBe(false); + expect(isMathPathWithin(profile, options.profile)).toBe(false); + expect(launch.isolationReceipt.hiddenRoots).toEqual(expect.arrayContaining(['/tmp', parent])); + expect(launch.args.slice(launch.args.indexOf('/tmp') - 1, launch.args.indexOf('/tmp') + 1)).toEqual(['--tmpfs', '/tmp']); + expect(launch.args.slice(launch.args.indexOf(parent) - 1, launch.args.indexOf(parent) + 1)).toEqual(['--tmpfs', parent]); + expect(launch.isolationReceipt.writableDirectories).toEqual([options.workspace, runtime]); + expect(launch.env.XDG_STATE_HOME).toBe(path.join(runtime, 'xdg', 'state')); + expect(launch.isolationReceipt.hiddenRoots).not.toContain(profile); + } + expect(git(state.worktree, ['worktree', 'list', '--porcelain'])).toBe(worktreesBefore); + expect(fs.existsSync(parent)).toBe(false); + expect(fs.existsSync(profilesRoot)).toBe(false); + expect(fs.readdirSync(profile).sort()).toEqual(['config.toml', 'models.json']); + expect(() => assertResearchHarnessCurrent(identity, {}, state.model)).not.toThrow(); + expect(state.turns).toBe(0); + expect(events.filter(event => event.event === 'portfolio_scout_unavailable').map(event => event.details?.reason)) + .toEqual(['math_codex_rpc_failed', 'math_codex_rpc_failed']); + expect(JSON.stringify(events)).not.toContain('private startup diagnostic'); + }); + + it('requests wrap-up before the deadline and salvages only valid saved reports after abort', async () => { + vi.useFakeTimers(); + const { input, events, state } = fixture(60_000, 2); + const notices = vi.fn(); + const running = deferred(); + let started = 0; + const completion = runPortfolioExploration({ ...input, open: async options => { + const profile = assignment(options); + expect(options.instructions).toContain('60 seconds'); + expect(options.instructions).toContain('Write an initial valid PORTFOLIO.json by halfway'); + expect(options.instructions).toContain('renaming it over the report'); + return { ...session(options, []), advisoryNotifications: 'native-history', + notify: async (notice, mode) => { + notices(profile, notice, mode); + const file = path.join(options.workspace, 'PORTFOLIO.json'); + fs.writeFileSync(file + '.tmp', profile === 'structural-symmetry' + ? JSON.stringify({ reports: [withoutProfile(structural)] }) : '{"reports":[]}'); + fs.renameSync(file + '.tmp', file); + }, + run: async (_message, _id, _workspace, begin) => { + begin('scout-turn'); + if (++started === 2) running.resolve(); + return new Promise((_resolve, reject) => options.signal!.addEventListener('abort', + () => reject(new Error('math_codex_transport_closed:forced')), { once: true })); + } }; + } }); + await Promise.race([running.promise, completion.then(() => { throw new Error('scouts did not start'); })]); + await vi.advanceTimersByTimeAsync(41_999); + expect(notices).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + expect(notices).toHaveBeenCalledTimes(2); + expect(notices).toHaveBeenCalledWith('structural-symmetry', expect.stringContaining('finalize PORTFOLIO.json now'), { mode: 'advisory' }); + await vi.advanceTimersByTimeAsync(18_000); + await completion; + expect(state.portfolioExploration).toMatchObject({ phase: 'completed', scouts: [ + { status: 'reported', reports: [structural] }, { status: 'timed-out' }], gate: { primaryRouteId: 'structural-symmetry' } }); + expect(events.filter(event => event.event === 'portfolio_scout_unavailable')).toEqual([ + { event: 'portfolio_scout_unavailable', details: expect.objectContaining({ reason: 'math_portfolio_scout_timed_out' }) }, + ]); + expect(vi.getTimerCount()).toBe(0); + }); + it('resumes only unfinished scouts within the saved deadline', async () => { const { state, stateFile, input } = fixture(4000, 2); const first = state.portfolioExploration!.scouts[0]; diff --git a/tests/solverSoftSliceCompaction.test.ts b/tests/solverSoftSliceCompaction.test.ts index 2dd7fd82..8a888eed 100644 --- a/tests/solverSoftSliceCompaction.test.ts +++ b/tests/solverSoftSliceCompaction.test.ts @@ -16,7 +16,7 @@ vi.mock(import('../src/math/mathBuildManifest'), async importOriginal => describe('soft research milestones', () => { afterEach(() => vi.useRealTimers()); - it.each(['time', 'compaction', 'fallback', 'natural-return', 'independent'] as const)('yields an unlimited research turn after %s', async trigger => { + it.each(['time', 'compaction', 'fallback', 'natural-return', 'independent', 'team'] as const)('yields an unlimited research turn after %s', async trigger => { vi.useFakeTimers(); const { directory, workspace, problem } = localExample('soft-slice-'); const controller = new AbortController(); @@ -33,6 +33,10 @@ describe('soft research milestones', () => { return readMathAgentSkill(path.join(skillRoot, 'SKILL.md')); })(); const state = solverState(problem, workspace, { runId: 'soft-slice-fixture', phase: 'prepared', + ...(trigger === 'team' ? { researchDelegation: { mode: 'team', maxAgents: 3 }, portfolioExploration: { + phase: 'completed', durationMs: 1000, scouts: [{ profile: 'structural-symmetry', status: 'timed-out', turns: 1 }], + gate: { retiredRoutes: [], foundationLemmas: [] }, + } } : {}), ...(skill ? { researchMode: 'skill', researchSkill: { name: skill.name, digest: skill.digest, loading: skill.loading } } : {}) }); const modules: typeof directSolverModules = { ...directSolverModules, M2: { ...directSolverModules.M2, check: async () => { @@ -44,7 +48,8 @@ describe('soft research milestones', () => { M1: { ...directSolverModules.M1, open: async (options: MathAgentOptions): Promise => ({ threadId: 'offline-soft-slice', usageSource: 'upstream-requests', advisoryNotifications: 'native-history', notify, interrupt, close: vi.fn(async () => {}), stopForFreeze: stop, - run: async (_message, _id, _workspace, begin) => { + run: async (message, _id, _workspace, begin) => { + if (trigger === 'team') expect(message).toContain('Phase 1 ended without a usable report'); begin('held-turn'); started.resolve(options); return done.promise; @@ -75,7 +80,18 @@ describe('soft research milestones', () => { } expect(events).toContainEqual({ event, details: expect.objectContaining({ turnId: 'held-turn', completedCompactions: trigger === 'compaction' ? 2 : 0 }) }); - expect(notify.mock.calls).toEqual([[expect.stringMatching(/standalone helpers.*fewer than 20 lines.*RESEARCH\.md/u), { mode: 'advisory' }]]); + const notice = trigger === 'team' ? /route_summary.*delegate focused independent obligations.*fewer than 20 lines.*RESEARCH\.md/u + : /standalone helper.*fewer than 20 lines.*RESEARCH\.md/u; + expect(notify.mock.calls).toEqual([[expect.stringMatching(notice), { mode: 'advisory' }]]); + if (trigger === 'team') { + expect(options.instructions).toContain('spawn useful independent work'); + expect(notify.mock.calls.flat()).not.toContainEqual(expect.stringContaining('declaration-submission.json')); + // This file is handled after the turn, outside the whole-proof diagnostics watcher. + expect(options.completedOutput?.file).toMatch(/lean-diagnostics-latest\.json$/u); + fs.writeFileSync(path.join(workspace, '.scratch/declaration-submission.json'), '{"declarations":[]}'); + } else if (skill) { + expect(notify.mock.calls.flat()).toContainEqual(expect.stringContaining('Never write an empty declarations array')); + } expect(options.requestGate?.checkpoint?.()).toBe(false); expect(interrupt).not.toHaveBeenCalled(); fs.writeFileSync(path.join(workspace, 'RESEARCH.md'), 'Established the first reduction. The induction step remains open.\n'); @@ -95,6 +111,12 @@ describe('soft research milestones', () => { expect(events).toContainEqual({ event: 'turn_checkpoint', details: expect.objectContaining({ reason: 'math_soft_slice_checkpoint' }) }); expect(events.some(entry => entry.event === (skill ? 'research_saved' : 'proof_checked'))).toBe(true); expect(fs.readFileSync(path.join(workspace, 'RESEARCH.md'), 'utf8')).toContain('The induction step remains open.'); + if (trigger === 'team') { + expect(fs.existsSync(path.join(workspace, '.scratch/declaration-submission.json'))).toBe(false); + expect(fs.existsSync(path.join(workspace, '.scratch/declaration-feedback.json'))).toBe(false); + expect(events.some(entry => entry.event === 'declarations_checked')).toBe(false); + expect(state.declarationArtifacts ?? []).toEqual([]); + } } finally { controller.abort(); done.resolve('interrupted'); diff --git a/tests/solverUsageReceipts.test.ts b/tests/solverUsageReceipts.test.ts index 5783c6ed..a88d240c 100644 --- a/tests/solverUsageReceipts.test.ts +++ b/tests/solverUsageReceipts.test.ts @@ -118,6 +118,26 @@ function researchFixture(source: MathAgentSession['usageSource']) { const assignment = (id: string) => ({ kind: 'task', task: { id } }) as CooperativeAction; describe('usage attribution at task boundaries', () => { + it('ignores cumulative replays before the next turn and flags new unscoped tokens', () => { + const { state, research, emit, callbacks } = researchFixture('native-thread-totals'); + state.usageBeforeThread = { totalTokens: 30 }; + state.usage = { totalTokens: 50 }; + callbacks.onUsage!({ totalTokens: 19 }); + callbacks.onUsage!({ totalTokens: 20 }, { turnId: 'previous-thread-turn' }); + expect(emit).not.toHaveBeenCalled(); + expect(state.usage).toEqual({ totalTokens: 50 }); + + callbacks.onUsage!({ totalTokens: 21 }); + expect(emit).toHaveBeenCalledExactlyOnceWith('worker_usage_unscoped', + expect.objectContaining({ reason: 'native-turn-identity-unavailable', reportedTotalTokens: 21 })); + expect(state.usage).toEqual({ totalTokens: 51 }); + + research.begin(assignment('next')); + callbacks.onUsage!({ totalTokens: 21 }, { turnId: 'next-turn' }); + expect(emit).toHaveBeenCalledTimes(1); + callbacks.onUsage!({ totalTokens: 21 }, { turnId: 'unrecognized-turn' }); + expect(emit).toHaveBeenCalledTimes(2); + }); it('settles a late request into its original task without charging the next turn', () => { const { state, research, callbacks } = researchFixture('upstream-requests'); research.begin(assignment('first')); diff --git a/tests/webModuleTelemetry.test.ts b/tests/webModuleTelemetry.test.ts index e41366cc..821e0728 100644 --- a/tests/webModuleTelemetry.test.ts +++ b/tests/webModuleTelemetry.test.ts @@ -302,6 +302,29 @@ describe('bounded web progress forwarding', () => { return { sent, forward, at: (value: number) => { clock = value; } }; }; + it('forwards portfolio, handoff and fallback events through the runner protocol using safe details', () => { + const { sent, forward } = forwarder(); + const events = [ + { event: 'portfolio_exploration_started', profiles: ['structural-symmetry'] }, + { event: 'portfolio_scout_started', workerId: 'portfolio-structural-symmetry' }, + { event: 'portfolio_scout_finished', workerId: 'portfolio-structural-symmetry', status: 'failed' }, + { event: 'portfolio_scout_unavailable', workerId: 'portfolio-structural-symmetry', status: 'failed', + reason: 'math_codex_rpc_failed:private setup diagnostic' }, + { event: 'portfolio_gate_evaluated', foundationLemmas: ['private proposal'] }, + { event: 'team_transport_fallback', from: 'native-agent-control', to: 'host-tools', reason: 'math_codex_transport_closed' }, + { event: 'soft_slice_milestone_requested', workerId: 'solver', taskId: 'goal-1' }, + { event: 'compaction_circuit_breaker_triggered', workerId: 'solver', taskId: 'goal-1' }, + ]; + for (const event of events) forward({ ...event, error: 'private error', taskText: 'private prompt' }); + expect(sent.map(message => message.event)).toEqual(events.map(event => event.event)); + const received = sent.map(message => parseWorkerMessage(JSON.stringify(message))); + expect(received).toEqual(sent); + expect(received[3]).toMatchObject({ details: { workerId: 'portfolio-structural-symmetry', + status: 'failed', reason: 'math_codex_rpc_failed' } }); + expect(received[5]).toMatchObject({ message: '团队已切换至宿主工具', details: { reason: 'math_codex_transport_closed' } }); + expect(JSON.stringify(sent)).not.toContain('private'); + }); + it('keeps one activity heartbeat per worker per interval and drops the rest', () => { const { sent, forward, at } = forwarder(); for (let index = 0; index < 50; index++) forward({ event: 'worker_activity', workerId: 'solver' });