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
1 change: 1 addition & 0 deletions apps/web/i18n/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ export const server: Record<string, string> = {
"示例运行:自然数加法": "Sample run: natural number addition",
"离线示例 Agent": "Offline sample Agent",
"先证 add_zero:n + 0 按定义就等于 n,可以直接用 rfl。另一个定理先不要动。": "Prove add_zero first: n + 0 equals n by definition, so rfl works directly. Leave the other theorem alone for now.",
"请用 Nat.zero_add 证明第二个定理。": "Use Nat.zero_add to prove the second theorem.",
"请把对这份完整证明的审阅结论交上来。最后是否通过,以独立的 Lean 验收为准。": "Please send your review of this complete proof. Whether it passes is decided by the independent Lean check.",
"审阅者看过了两个定理的完整证明,同意提交。最终是否通过,仍以独立的 Lean 验收为准。": "The reviewer read the complete proof of both theorems and agrees to submit it. Whether it passes is still decided by the independent Lean check.",
"证明 Tutorial.add_zero:n + 0 按定义就等于 n。": "Prove Tutorial.add_zero: n + 0 is n by definition.",
Expand Down
52 changes: 8 additions & 44 deletions apps/web/workerBridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { buildRunInspection, exportRunPlan, readRunInspection } from '../../src/
import { queuePlanApproval, queueRunEdit } from '../../src/solver/humanEdit';
import { planApprovalInputSchema } from '../../src/solver/planApproval';
import { humanGuidanceInputSchema, queueHumanGuidance, readHumanGuidance, withdrawHumanGuidance } from '../../src/solver/humanGuidance';
import { parseCooperationPlan, taskGroup, taskVersion, type TaskRecord } from '../../src/solver/tasks';
import { taskVersion, type TaskRecord } from '../../src/solver/tasks';
import { allowedKnowledgeFile, buildTheoremKnowledge, validateTheoremKnowledge, type TheoremKnowledgeBase } from '../../src/solver/theoremKnowledge';
import { importKnowledgeRuns } from '../../src/solver/theoremKnowledgeRuns';
import { proofReceiptsMatch, type ProofCheck } from '../../src/solver/modules/evidence';
Expand Down Expand Up @@ -326,42 +326,6 @@ export function createWebWorkerBridge(options: {
return { capture };
}

function previewEdit(state: SolverRunState, proposal: unknown) {
const proposed = parseCooperationPlan(state.problem, proposal), previous = new Map(state.cooperation?.tasks.map(node => [node.task.id, node.task]) ?? []);
const changes: { taskId: string; fields: string[] }[] = [];
const oldGroups = new Map(state.cooperation?.groups?.map(record => [record.group.id, record.group]) ?? []);
const affected = new Set<string>(), mathematical = new Set<string>();
for (const task of proposed.tasks) {
const before = previous.get(task.id), fields: string[] = [];
if (!before) fields.push('added');
else for (const key of new Set([...Object.keys(before), ...Object.keys(task)])) {
if (canonicalMathJson((before as Record<string, unknown>)[key] ?? null) !== canonicalMathJson((task as Record<string, unknown>)[key] ?? null)) fields.push(key);
}
const group = proposed.groups.find(item => item.id === taskGroup(task)), oldGroup = oldGroups.get(taskGroup(task));
if (group && oldGroup) for (const key of new Set([...Object.keys(group), ...Object.keys(oldGroup)])) {
if (canonicalMathJson((group as Record<string, unknown>)[key] ?? null) !== canonicalMathJson((oldGroup as Record<string, unknown>)[key] ?? null)) fields.push(`group.${key}`);
}
if (fields.length) { changes.push({ taskId: task.id, fields }); affected.add(task.id); }
if (!before || taskVersion(before) !== taskVersion(task) || fields.some(field => ['group.objective', 'group.revision'].includes(field))) mathematical.add(task.id);
}
for (const id of previous.keys()) if (!proposed.tasks.some(task => task.id === id)) { changes.push({ taskId: id, fields: ['removed'] }); affected.add(id); mathematical.add(id); }
if (canonicalMathJson(state.cooperation?.proofRoutes ?? []) !== canonicalMathJson(proposed.proofRoutes ?? [])) {
for (const route of [...(state.cooperation?.proofRoutes ?? []), ...(proposed.proofRoutes ?? [])]) {
affected.add(route.targetTaskId); mathematical.add(route.targetTaskId);
const existing = changes.find(change => change.taskId === route.targetTaskId);
if (existing) { if (!existing.fields.includes('proofRoutes')) existing.fields.push('proofRoutes'); }
else changes.push({ taskId: route.targetTaskId, fields: ['proofRoutes'] });
}
}
for (let changed = true; changed;) {
changed = false;
for (const task of proposed.tasks) if (!mathematical.has(task.id) && task.dependsOn.some(id => mathematical.has(id))) {
mathematical.add(task.id); affected.add(task.id); changed = true;
}
}
return { affectedTaskIds: [...affected], changes };
}

const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('edit-preview'), proposal: z.record(z.unknown()) }).strict(),
z.object({ type: z.literal('edit'), proposal: z.record(z.unknown()) }).strict(),
Expand All @@ -378,8 +342,8 @@ export async function handleWebWorkerCommand(value: unknown, options: { activeRu
const bridge = createWebWorkerBridge({ ...active, libraryRestart: command.type === 'capture' ? active.libraryRestart : undefined });
if (command.type === 'capture') return { id: 'capture', status: 'captured',
...await bridge.capture({ includeCatalog: true, force: true, waitMs: 5_000 }) };
const { state, stateFile } = readRunInspection(active.output);
if (command.type === 'guidance') {
const { state, stateFile } = readRunInspection(active.output);
try {
const previous = bridgeMeta(path.join(active.directory, 'web-bridge.json'), active.webRunId, state.runId);
const alreadyQueued = readHumanGuidance(stateFile, state.runId).some(record => record.id === command.guidance.id);
Expand Down Expand Up @@ -427,15 +391,15 @@ export async function handleWebWorkerCommand(value: unknown, options: { activeRu
throw error;
}
}
let impact: ReturnType<typeof previewEdit>;
try { impact = previewEdit(state, command.proposal); }
catch (error) {
// The pure preview rejects invalid plans before the edit queue is opened. Queue failures stay uncertain.
try {
const commandDigest = mathDigest(canonicalMathJson(command.proposal));
const result = await queueRunEdit(active.output, command.proposal, command.type === 'edit-preview');
return { ...result, commandDigest };
} catch (error) {
// Plan errors are decided before appending. Lease and persistence failures still propagate.
const reason = error instanceof Error ? error.message : '';
if (/^math_plan_[a-z_]+(?::|$)/u.test(reason))
return { id: command.proposal.id, status: 'rejected', reason, baseVersion: command.proposal.baseVersion };
throw error;
}
const result = await queueRunEdit(active.output, command.proposal, command.type === 'edit-preview');
return { ...result, baseVersion: command.proposal.baseVersion, ...impact, commandDigest: mathDigest(canonicalMathJson(command.proposal)) };
}
4 changes: 3 additions & 1 deletion bin/math.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const commands: Readonly<Record<string, string>> = {
'check-lean': 'scripts/mathematics/checkLean.ts',
'proof-search': 'scripts/mathematics/proofSearch.ts',
'research-observe': 'scripts/mathematics/researchObserve.ts',
checkpoint: 'scripts/mathematics/checkpoint.ts',
'plan-validate': 'scripts/mathematics/planValidate.ts',
'plan-apply': 'scripts/mathematics/planApply.ts',
'check-finite': 'scripts/mathematics/checkFinite.ts',
Expand Down Expand Up @@ -67,8 +68,9 @@ if (!command || ['help', '--help', '-h'].includes(command)) {
check-lean Check changed Lean files with bounded diagnostics
proof-search Explore bounded tactic branches and retain resumable proof states
research-observe Validate and publish one research finding with retained Lean probes
checkpoint Save the acknowledgment requested by the active host
plan-validate Check a cooperative Lead plan and report field-level issues
plan-apply Save a validated cooperative Lead plan for host intake
plan-apply Validate and save or publish a cooperative Lead plan
check-finite Replay finite Boolean constraints and return witnesses
kernel-certificate Generate chunked decide +kernel certificate modules
library-pack Extract checked run modules or backport upstream files as a frozen library
Expand Down
6 changes: 3 additions & 3 deletions docs/codex-skill-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ Each domain profile also links [collected domain materials](../skills/theoremos-

Collaboration follows useful milestones. Lead keeps the shared route and gap ownership visible through native messages when needed, and assesses findings, probes, blockers and route changes when they affect the next decision. A member messages usable findings and blockers promptly, submits independent helpers once they answer the assignment and returns for checking before expanding its scope. These instructions guide Agent choices without a timed polling loop, forced proof method, task quota or automatic adoption. Waiting is useful when progress depends on an outstanding member result; an empty loaded team alone is not a reason to wait.

The native transport leaves identity, dispatch, instructions, messaging, waiting and interruption to Codex collaboration tools. Both Lead and members can call `history`, `inspect`, `inspect-research` and `route_summary` through `theoremos_team`. Lead can also call `finish`, `adopt` and `retire_route`. Members can call `yield`, `submit` and `submit_helpers`. Native `followup_task` resumes a yielded draft or assigns work to a completed member. `list_agents` lists loaded agents. The saved overview retains members and their task and evidence identities after their writer process stops.
The native transport leaves identity, dispatch, instructions, messaging, waiting and interruption to Codex collaboration tools. Both Lead and members can call `history`, `inspect`, `inspect-research` and `route_summary` through `theoremos_team`. Lead can also call `finish`, `adopt` and `retire_route`. Members can call `yield` and `submit`. Set `helpersOnly: true` on `submit` to share standalone helpers and keep the assignment open. Native `followup_task` resumes a yielded draft or assigns work to a completed member. `list_agents` lists loaded agents. The saved overview retains members and their task and evidence identities after their writer process stops.

Host tools add Lead operations for `spawn`, `assign`, `amend`, `coordinate`, `resume`, `cancel`, `publish` and `stop`, plus `message`, `poll` and `wait` for both roles and `progress` for members. `budget` and its parameters are available to Lead with a finite token or turn allowance. The tool description lists the required and optional fields for each operation, and the host checks each call against its operation and role. The pinned [parallel-work reference](../skills/theoremos-research/references/parallel-work.md) documents both transports. Spawn and assign queue work and return a task ID. Poll and wait return individual arrivals and a durable cursor while other members continue. Wait is bounded to 30 seconds. Inspect retrieves checked declaration interfaces, source excerpts, commits and proof evidence so Lead can make an informed adoption decision.

Expand All @@ -111,7 +111,7 @@ Runs have no token, turn or solving-time budget by default. Without a finite hos

Native team tools expose no task-budget or reserve controls. Host tools provide optional `budget:{tokens?,turns?}` on spawn/assign and `budget(leadReserve?, agentId?, taskId?, budget?)` only with an explicitly configured finite host allowance. These replace cumulative local allowances without resetting consumption or resuming paused work. Shared configured limits still govern the whole run. The overview reports observed usage and any saved finite allowances; historical turn limits remain unknown when no host limit was saved. Token caps govern subsequent request admission using observed receipts, so an admitted request may finish beyond a cap. A missing receipt is preserved as unavailable usage.

A child saves its sources, calls submit with exact declarations and returns. Submission and yield also checkpoint at the next unpaid request boundary, after the current paid response and tool group settle; submission enters checking, while yielding retains the task for resume. The host confirms writer shutdown, freezes those bytes and checks the delivery independently. Adopt defaults to Lead and queues integration. Lead saves sources and notes before requesting it; a pending Lead adoption triggers an automatic checkpoint before the next model request. Lead can also call `finish(summary)` after saving to request independent whole-problem checking without relying on a local diagnostic; remaining holes or errors return normal feedback. The paid response and its tools finish and usage settles before confirmed writer shutdown; the host then freezes sources, rechecks and integrates the delivery and continues the saved thread. No token, time or turn allowance is added. Adoption into an idle child also queues and returns immediately; its safe work loop integrates before dispatching the next assignment, allowing native messages and interruption during slow checking. Lead can send the consumer instructions after requesting adoption and inspect the resulting status and feedback. Changed source versions, conflicts or failed checks return feedback. Checked declarations and completed adoptions never replace independent whole-problem acceptance.
A child saves its sources, calls submit with exact declarations and returns. Submission and yield also checkpoint at the next unpaid request boundary, after the current paid response and tool group settle; submission enters checking, while yielding retains the task for resume. The host confirms writer shutdown, freezes those bytes and checks the delivery independently. Adopt defaults to Lead and queues integration. Lead saves sources and notes before requesting it; a pending Lead adoption triggers an automatic checkpoint before the next model request. Lead normally saves the complete proof and returns for independent checking. Lead can call `finish(summary)` after saving to request early handoff. Remaining holes or errors return normal feedback. The paid response and its tools finish and usage settles before confirmed writer shutdown; the host then freezes sources, rechecks and integrates the delivery and continues the saved thread. No token, time or turn allowance is added. Adoption into an idle child also queues and returns immediately; its safe work loop integrates before dispatching the next assignment, allowing native messages and interruption during slow checking. Lead can send the consumer instructions after requesting adoption and inspect the resulting status and feedback. Changed source versions, conflicts or failed checks return feedback. Checked declarations and completed adoptions never replace independent whole-problem acceptance.

In native runs, `send_message` binds the sender to the issuing native thread. Use `/root` for Lead and canonical paths or native IDs for peers. Relative paths follow upstream Codex resolution. Teams using host tools send `message` with `agentId`, with receipts and deduplication.

Expand Down Expand Up @@ -139,7 +139,7 @@ Skill, team and native-baseline preparation save the Lean project location at `.

Single Skill research, complete Skill workflows and common-guidance/native comparisons generate optional tool references through the same `researchToolGuide.ts` implementation. It selects the actual projected executable and available corpus, knowledge and library resources. Complete workflows reuse the existing context compiler for tasks, consumers, required feedback, routes, definitions, families and fixed-source review. Workflow guidance and comparison guidance retain distinct purposes. The shared reference does not enable native delegation. The durable writer avoids rewriting unchanged help bytes.

Complete cooperative Skill sessions keep their role, current delivery entry point and exact source scope in session instructions. Stable plan/revision, research, gap, correction and review formats live in the pinned [cooperation reference](../skills/theoremos-research/references/cooperation.md), read by role or current need. Same-thread continuations carry the current assignment, delivery path, contract, inbox, decision requirements and feedback without repeating these formats or prescribing a mathematical route. Pending correction receipt indexes remain mandatory even when their full details exceed the optional context budget. Legacy prompts retain their existing behavior.
Cooperative sessions keep role, delivery and source rules in their session instructions. The pinned [cooperation reference](../skills/theoremos-research/references/cooperation.md) describes the stable formats for Skill sessions. Same-thread continuations carry the current assignment, contract, inbox and feedback. A worker sees `checkOutcome` when assigned a pending check. Lead receives `nextCheckDecisions` with the outcomes that need a decision. Unanswered human guidance is referenced by ID in the prompt and available in that worker's `COOPERATION.json`. Pending correction receipt indexes remain mandatory even when their full details exceed the optional context budget.

Normal turn completion saves source and notes after confirmed writer shutdown. Native resume, request recovery, compaction handling, leases, cumulative usage and the existing dispatch budget remain shared infrastructure. A missing shutdown confirmation quarantines that workspace before any new writer, freeze or acceptance. Unfinished original proofs do not trigger a full original-target compilation after every research turn. A complete candidate still goes through the original strict check and S3 evaluation of **every** frozen original target.

Expand Down
Loading
Loading