Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions apps/web/i18n/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,14 @@ export const server: Record<string, string> = {
"模型预算已停止后续调用": "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",
Expand Down
11 changes: 10 additions & 1 deletion apps/web/progress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ const descriptions: Record<string, string> = {
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: '正在重新检查任务',
Expand Down Expand Up @@ -97,7 +103,7 @@ const failureDescriptions: Record<string, string> = {
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<string, readonly (keyof WebEventDetails)[]> = {
turn_started: ['turn'], turn_checkpoint: ['turn', 'reason'], proof_check_started: ['turn'],
proof_checked: ['passed', 'reused'], research_action: ['operation'],
Expand Down Expand Up @@ -133,6 +139,9 @@ const fields: Record<string, readonly (keyof WebEventDetails)[]> = {
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. */
Expand Down
2 changes: 1 addition & 1 deletion skills/theoremos-research/references/cooperation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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":[]}
Expand Down
9 changes: 4 additions & 5 deletions src/runtime/codexSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -415,14 +415,13 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise
let bridge: Awaited<ReturnType<typeof startChatCompletionsBridge>> | undefined;
let responsesRelay: Awaited<ReturnType<typeof startFormalizationRelay>> | 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<typeof parseToml>;
delete selected.auth;
Expand Down
2 changes: 2 additions & 0 deletions src/solver/agentTeamContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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; ' +
Expand Down Expand Up @@ -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. ' +
Expand Down
4 changes: 3 additions & 1 deletion src/solver/declarationArtifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }));
Expand Down Expand Up @@ -87,7 +88,7 @@ function submissionContent<T>(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);
Expand All @@ -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);
}

Expand Down
11 changes: 7 additions & 4 deletions src/solver/modules/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -81,6 +82,7 @@ export type ContextAccess = Readonly<{
export type ContextBundle = Readonly<{
assignment?: CooperativeAction;
workContract?: ReturnType<typeof cooperativeWorkContract>;
toolHelp?: ResearchToolHelp;
instructions: string;
message: string;
/** Same-thread dispatch compiled under the same byte budget as the full context. */
Expand Down Expand Up @@ -163,6 +165,7 @@ export function buildResearchContext(task: SolverProblem, state: Readonly<Solver
const command = `bun ${shellArgument(access.tools ?? path.join(access.root, 'bin/math.ts'))}`;
const fixedReview = access.assignment?.kind === 'review';
const planningLead = access.assignment?.kind === 'lead';
const toolHelp = planningLead && !skillWorkflow ? buildResearchToolGuide(task, access, state.environmentDigest).help.build() : undefined;
const readOnlySources = fixedReview || planningLead || access.assignment?.kind === 'task' &&
(isFeasibilityReview(access.assignment.task) || isFinalCandidateReview(access.assignment.task));
const deliveryFile = access.assignment?.kind === 'lead' ? leadPlanDeliveryFile(access.assignment) : undefined;
Expand Down Expand Up @@ -255,7 +258,7 @@ ${access.corpusFile ? `For library lookup, run ${command} search-lean --workspac
checkpoint = readMathText(notes, 1_000_000);
}
}
const bundle: ContextBundle = { instructions,
const bundle: ContextBundle = { instructions, ...(toolHelp ? { toolHelp } : {}),
message, scope: 'original-problem-and-allowed-library',
sources: { problemReceiptDigest: task.receiptDigest } };
const residualSnapshot = readLeanResidualGoalSnapshot({ projectRoot: path.join(access.worktree, task.projectRelative), env: access.environment,
Expand Down Expand Up @@ -635,7 +638,7 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio
(action.kind === 'task' && ['lemma', 'goal'].includes(action.task.kind)
? 'Source-bound research findings require sources with exactly these Lean file keys: ' + JSON.stringify(leanFiles) + '.\n' : '') +
connectionRules + familyMemberRules + canonicalProbeRules
: context.instructions + '\n' + initialPlanningRules + rules + helperRules + organizationRules + leadDeliveryRules + planRevisionRules + familyRules + feasibilityRules + earlyRouteRules + connectionRules + familyMemberRules + attemptRules + focusRules + gapRules + nextCheckRules + observationRules + checkpointRules + mathematicalInterfaceRules + inheritedFindingRules + researchSourcesRules + canonicalProbeRules +
: context.instructions + '\n' + (action.kind === 'lead' ? leadPlanToolInstruction : '') + initialPlanningRules + rules + helperRules + organizationRules + leadDeliveryRules + planRevisionRules + familyRules + feasibilityRules + earlyRouteRules + connectionRules + familyMemberRules + attemptRules + focusRules + gapRules + nextCheckRules + observationRules + checkpointRules + mathematicalInterfaceRules + inheritedFindingRules + researchSourcesRules + canonicalProbeRules +
(action.kind === 'lead' || action.kind === 'task' && !isFeasibilityReview(action.task)
? 'For parallel work, assign distinct proof, feasibility/counterexample, library-connection or consumer questions. Inspect in-flight work and reuse saved results; do not duplicate an unchanged question. Keep backup routes testing different inferences. Leave a slot waiting for input when no independent useful work exists. Do not manufacture helpers. Route priority reflects recorded inputs and obstructions, not predicted ease.\n' : '') +
(action.kind === 'lead' ? 'Use the proof-continuation snapshot to identify the original goal\'s current mathematical frontier. Prefer consuming relevant checked lemmas before creating more auxiliary work; give each new helper an intended consumer and explicitly assign every substantive missing premise. Keep useful alternative routes visible. A lemma without a recorded consumer may still be useful; investigate its connection rather than deleting it. Planned dependencies, actual Lean proof references and conditional references are reported separately. Do not count auxiliary lemma totals as completion of the original problem. The host obtains fixed-candidate review after the complete proof is checked; mark any advisory final-candidate task with reviewScope:"final-candidate" so it waits for freshly checked original goals. Use a distinct task with reviewScope:"feasibility" for independent mathematical route checks before a complete candidate exists. Inspect validated lemmaRequests in deliveries and adopt useful exact proposals as separate lemma tasks; proposals and their local checks are advisory. Advisory research may start before its planned dependencies are proved; use typed proof tasks when a consumer must wait for checked premises. Set consumerGoalIds on advisory tasks to the original goals their effort serves; these attribution links never add proof premises or dependency waits.\n' : '') +
Expand Down
Loading
Loading