diff --git a/apps/web/i18n/server.ts b/apps/web/i18n/server.ts index 373d192e..2057b7b7 100644 --- a/apps/web/i18n/server.ts +++ b/apps/web/i18n/server.ts @@ -178,6 +178,7 @@ export const server: Record = { "示例运行:自然数加法": "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.", diff --git a/apps/web/workerBridge.ts b/apps/web/workerBridge.ts index 4daaa79e..be55a9a8 100644 --- a/apps/web/workerBridge.ts +++ b/apps/web/workerBridge.ts @@ -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'; @@ -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(), mathematical = new Set(); - 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)[key] ?? null) !== canonicalMathJson((task as Record)[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)[key] ?? null) !== canonicalMathJson((oldGroup as Record)[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(), @@ -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); @@ -427,15 +391,15 @@ export async function handleWebWorkerCommand(value: unknown, options: { activeRu throw error; } } - let impact: ReturnType; - 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)) }; } diff --git a/bin/math.ts b/bin/math.ts index fbe00af3..079bdf39 100644 --- a/bin/math.ts +++ b/bin/math.ts @@ -24,6 +24,7 @@ const commands: Readonly> = { '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', @@ -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 diff --git a/docs/codex-skill-runtime.md b/docs/codex-skill-runtime.md index bcede457..093df928 100644 --- a/docs/codex-skill-runtime.md +++ b/docs/codex-skill-runtime.md @@ -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. @@ -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. @@ -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. diff --git a/docs/cooperative-proof-routes.md b/docs/cooperative-proof-routes.md index 4d1ba01c..2cd1caa5 100644 --- a/docs/cooperative-proof-routes.md +++ b/docs/cooperative-proof-routes.md @@ -80,7 +80,7 @@ Lead 的计划和人工导出计划新增可选的顶层字段: Lead 的 capacity/stagnation 请求保存稳定的 `requestId`、原始 `inputDigest` 和当前 dispatch nonce。未完成的请求续接沿用身份;完成回复须匹配当前请求和 nonce。有待处理 handoff/challenge 时,先走原有决策协议。没有独立可执行工作时,可提交上下文给出的 `assessment` 短回执和具体数学缺口。新输入可重新触发评估;worker 调度、inbox 变化或纯计划版本变化不会清除同一数学责任的无进展保护。探索耗尽要求当前全部 focus 实际完成,只有派发记录不算完成。 -对于有类型的证明任务,worker 保存源码后,可向当前分工日志追加 `{"kind":"ready","summary":"saved proof ready for checking"}`,随即停止编辑并返回。宿主先持久记录请求,再等待 turn 结束、确认受管 writer 进程组停止,然后固定 Git commit 并独立检查。中断请求的应答和普通 `close()` 都不能代替停写确认;主动交回写权后的中断若未结束,复用现有 10 秒清理期限关闭会话。无法确认停止时,不提交或验收活动源码,回执记为失败,并持久隔离该 writer 的工作目录;禁止同目录重派或直接恢复,须恢复到新的隔离目录。普通验收失败可通过带新 id 的事件重试。自然 turn 完成仍兼容原交付协议。 +对于有类型的证明任务,worker 保存源码后直接返回即可交付。需要提前交回写权限时,可向当前分工日志追加 `{"kind":"ready","summary":"saved proof ready for checking"}`,随即停止编辑并返回。宿主先持久记录请求,再等待 turn 结束、确认受管 writer 进程组停止,然后固定 Git commit 并独立检查。中断请求的应答和普通 `close()` 都不能代替停写确认;主动交回写权后的中断若未结束,复用现有 10 秒清理期限关闭会话。无法确认停止时,不提交或验收活动源码,回执记为失败,并持久隔离该 writer 的工作目录;禁止同目录重派或直接恢复,须恢复到新的隔离目录。普通验收失败可通过带新 id 的事件重试。 `proofReadyRecords` 区分 `awaiting-freeze`、`frozen`、`checked`、`failed` 和 `superseded`,保存固定 snapshot、源码摘要和 Lean 回执。恢复未冻结请求必须在新会话重新提交 ready;已有 frozen snapshot 直接按原 commit 重新验收,不再启动写入 turn,也不替换为后续活动源码。条件证明明确保留依赖条件并释放当前 Engineer;它不能关闭原目标,仍须后续无条件集成与独立最终评测。停写确认针对本 runtime 管理的进程组;ready 协议要求合作式交回写权。 diff --git a/docs/usage.md b/docs/usage.md index 3230b138..61c61380 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -323,7 +323,7 @@ Lead 的普通规划和初始规划执行 90 秒后收到保存提醒,120 秒 | Lean-Eval | 执行独立官方比较器,记录比较结果与对应题目身份 | | `--evaluator-command` | 使用指定命令作为最终评测,记录 `official: false`;它会覆盖默认评测器 | -完整候选进入终审后,宿主优先安排未参与该候选证明的同伴,在新会话中做只读审阅。若存活的同伴都参与了证明,宿主使用新会话审阅并标记 `independent: false`。终审期间暂停派发普通研究,在途研究会保存草稿并让出执行位置。候选失效或终审要求修改时,普通研究可继续派发。模型审阅和 Lean 验收分别保存。 +配置了模型终审时,宿主优先安排未参与该候选证明的同伴,在新会话中做只读审阅。若存活的同伴都参与了证明,宿主使用新会话审阅并标记 `independent: false`。终审期间暂停派发普通研究,在途研究会保存草稿并让出执行位置。候选失效或终审要求修改时,普通研究可继续派发。模型审阅和 Lean 验收分别保存。 | 输出 | 内容 | | --- | --- | @@ -510,7 +510,7 @@ Lead 的完整计划可显式填写 `handoffDecisions: [{"id":"当前派发的 交付校验失败后,按回执指示修改并在新 finding 中填写 `replacesReceipt`。若这次纠正仍有字段错误,宿主保留经同一分工核对的纠正链;纠正事件成功发布后只解决该链中的错误,不清除无关回执。`mathematicalGap.consumer` 必须引用当前可见的原题 `goal`;`previousDeliveryId` 只能引用 `COOPERATION.json.mathematicalGaps` 中的缺口记录,不能用普通研究交付 ID。没有先前缺口记录时省略该引用,仍须填写 `previousGap`。 -研究任务的 `reviewScope: "final-candidate"` 以及兼容的 `independent_candidate_review` 仅在全部原始目标经过本进程重新检查后派发;`reviewScope: "feasibility"` 用于独立检查尚未完成的数学路线。最终验收仍由完整原题检查和固定候选审阅决定。可恢复的工具调用解析、连接和会话中断最多重试三次,退避 10、20、40 秒;已有源码、笔记和累计用量保留。认证、未知错误及源码归属或冻结声明违规继续明确失败,不自动重试。该局部恢复策略不增加整体求解时限。 +计划里启用的 `reviewScope: "final-candidate"` 和兼容的 `independent_candidate_review` 会把各自的问题交给同一个固定候选 Reviewer。它们的结论写入运行的审阅记录。`reviewScope: "feasibility"` 用于独立检查尚未完成的数学路线。普通协作候选通过完整原题检查后直接进入 S3 独立验收。启用计划审批、配置陈述审查、明确安排活跃的最终候选审阅任务,或恢复已记录的候选审阅时,继续走固定候选审阅流程。可恢复的工具调用解析、连接和会话中断最多重试三次,退避 10、20、40 秒;已有源码、笔记和累计用量保留。认证、未知错误及源码归属或冻结声明违规继续明确失败,不自动重试。该局部恢复策略不增加整体求解时限。 声明投影失败会在 `.runtime/statement-diagnostics/` 保存实际投影源码、各最多 1MB 的标准输出和错误输出及题目/提交绑定的清单,异常摘要优先显示首条 Lean 错误。这些含证明擦除占位符的投影仅用于诊断。 diff --git a/docs/web-workbench.md b/docs/web-workbench.md index 0c270fb4..1ba62262 100644 --- a/docs/web-workbench.md +++ b/docs/web-workbench.md @@ -537,7 +537,7 @@ bun scripts/test-web-runtime.ts 最后一项派生带明确 fixture 标记的测试镜像,用模拟 Codex app-server 生成候选,执行真实 Lean 检查。共 7 个场景:标准库正确 / 错误候选、运行中取消、创建时取消,以及 Mathlib 正确 / 错误候选和运行中取消;Mathlib 取消场景还核对设备权限、匿名卷和删除结果。不会调用模型或使用真实 Key。可用 `--case mathlib-valid` 单独排查;Mathlib 冷准备可能持续数分钟。报告写入 `out/web-runtime-smoke/report.json`,测试镜像默认自动删除。 -`test:web-cooperative-runtime` 单独验证真实 Docker 多 Agent 协作,使用离线 Codex 替身生成工作材料,执行真实 host、命令通道和 Lean 检查:Lead 发布计划,Engineer 实际接收指定任务版本的指导并完成第一个目标;人工修改计划后,已检查任务的版本失效,两个目标重新检查;独立 Researcher/Reviewer 审阅固定候选,最终由 S3 验收完整原题。测试还核对预览只读、重复 edit 只应用一次、归档证据和容器清理。默认从 `theorem-os-worker:local` 派生一次性测试镜像,可用 `--base-image TAG` 指定已构建镜像;报告与原始证据写入 `out/web-cooperative-smoke/`。本机此流程已通过,两个目标的 recheck 与最终 `evaluated_passed` 均由真实 Lean 产生。 +`test:web-cooperative-runtime` 单独验证真实 Docker 多 Agent 协作,使用离线 Codex 替身生成工作材料,执行真实 host、命令通道和 Lean 检查:Lead 发布计划,Engineer 实际接收指定任务版本的指导并完成第一个目标;人工修改计划后,已检查任务的版本失效,两个目标重新检查;完整候选通过 Lean 检查后直接由 S3 验收原题。测试还核对预览只读、重复 edit 只应用一次、归档证据和容器清理。默认从 `theorem-os-worker:local` 派生一次性测试镜像,可用 `--base-image TAG` 指定已构建镜像;报告与原始证据写入 `out/web-cooperative-smoke/`。本机此流程已通过,两个目标的 recheck 与最终 `evaluated_passed` 均由真实 Lean 产生。 已验证标准库和 Mathlib 的正确 / 错误证明、取消及容器清理;浏览器到 HTTP、Docker 和真实 Mathlib/Lean 的完整流程也通过验收,并检查了下载和 320–1440 像素布局。实际运行结果写入各次测试报告。不同服务商的 Responses API 兼容性与付费模型行为需要使用者通过自己的账户验证。 diff --git a/scripts/build-agent-tools.ts b/scripts/build-agent-tools.ts index 2e6c697e..8f2d3a4b 100644 --- a/scripts/build-agent-tools.ts +++ b/scripts/build-agent-tools.ts @@ -16,6 +16,7 @@ const agentToolCommands = { declarations: 'readDeclarations.ts', hub: 'huggingMath.ts', 'research-observe': 'researchObserve.ts', 'proof-search': 'proofSearch.ts', + checkpoint: 'checkpoint.ts', 'plan-validate': 'planValidate.ts', 'plan-apply': 'planApply.ts', 'check-finite': 'checkFinite.ts', 'kernel-certificate': 'kernelCertificate.ts', continuation: 'readContinuation.ts', } as const; diff --git a/scripts/build-web-sample.ts b/scripts/build-web-sample.ts index 434545d7..afcb1f3a 100644 --- a/scripts/build-web-sample.ts +++ b/scripts/build-web-sample.ts @@ -16,10 +16,12 @@ if (!['theorem-os.web-archive.v1', 'theorem-os.web-archive.v2'].includes(archive const from = archive.run.id; const title = '示例运行:自然数加法'; const task = '证明两个自然数加法定理,保持原题声明不变。根据 Lean 反馈修复候选,并验收完整原题。'; -// The scripted agent acts on marker-prefixed instructions and writes a fixed review; the sample shows them as a person would say them. +// Replace fixture markers with the text shown to sample readers. Older archives also include a candidate review. const readable: [recorded: string, shown: string][] = [ ['WEB_COOPERATIVE_PROVE_FIRST: use definitional equality and leave the other original target unchanged.', '先证 add_zero:n + 0 按定义就等于 n,可以直接用 rfl。另一个定理先不要动。'], + ['WEB_COOPERATIVE_PROVE_SECOND: prove the second goal using Nat.zero_add.', + '请用 Nat.zero_add 证明第二个定理。'], ['WEB_COOPERATIVE_RELEASE_REVIEW: report the review of this fixed candidate. Final acceptance remains with S3.', '请把对这份完整证明的审阅结论交上来。最后是否通过,以独立的 Lean 验收为准。'], ['Offline independent reviewer inspected the fixed two-target candidate; only host Lean/S3 checks can accept it.', diff --git a/scripts/mathematics/checkpoint.ts b/scripts/mathematics/checkpoint.ts new file mode 100644 index 00000000..d88872fd --- /dev/null +++ b/scripts/mathematics/checkpoint.ts @@ -0,0 +1,17 @@ +import { parseArgs } from 'node:util'; +import { queueContextCheckpoint } from '../../src/solver/contextCheckpoint'; + +try { + const { values } = parseArgs({ options: { + worktree: { type: 'string' }, log: { type: 'string' }, 'request-id': { type: 'string' }, + help: { type: 'boolean', short: 'h' }, + } }); + if (values.help) console.log('Usage: theorem-os checkpoint --log FILE --request-id ID [--worktree DIR]'); + else { + if (!values.log || !values['request-id']) throw new Error('Use the checkpoint command from the current host request.'); + console.log(JSON.stringify(queueContextCheckpoint(values.worktree ?? process.cwd(), values.log, values['request-id']))); + } +} catch (error) { + console.log(JSON.stringify({ status: 'error', error: error instanceof Error ? error.message : String(error) })); + process.exitCode = 1; +} diff --git a/scripts/mathematics/editMathRun.ts b/scripts/mathematics/editMathRun.ts index 0efcc9b1..2a505f6d 100644 --- a/scripts/mathematics/editMathRun.ts +++ b/scripts/mathematics/editMathRun.ts @@ -10,7 +10,8 @@ try { if (values.help) console.log('Usage: theorem-os edit --run RESULT_OR_STATE --plan FILE [--dry-run]\nValidates and queues a versioned plan edit. The running or resumed solver applies it and separately rechecks affected proofs.'); else { if (!values.run || !values.plan) throw new Error('--run and --plan are required'); - console.log(JSON.stringify(await queueRunEdit(values.run, JSON.parse(readMathText(values.plan, 1024 * 1024)), values['dry-run']))); + const { id, status, baseVersion } = await queueRunEdit(values.run, JSON.parse(readMathText(values.plan, 1024 * 1024)), values['dry-run']); + console.log(JSON.stringify({ id, status, baseVersion })); } } catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; diff --git a/scripts/mathematics/planCommand.ts b/scripts/mathematics/planCommand.ts index 49d0d584..0997679b 100644 --- a/scripts/mathematics/planCommand.ts +++ b/scripts/mathematics/planCommand.ts @@ -1,7 +1,7 @@ import fs from 'node:fs'; import { parseArgs } from 'node:util'; import { MAX_RESEARCH_NOTES_BYTES } from '../../src/solver/deliveries'; -import { applyCooperationPlanFile, validateCooperationPlanFile } from '../../src/solver/planTool'; +import { applyCooperationPlanFile, publishCooperationPlanFile, validateCooperationPlanFile } from '../../src/solver/planTool'; function readStandardInput(): string { const bytes = Buffer.alloc(MAX_RESEARCH_NOTES_BYTES + 1); @@ -16,17 +16,18 @@ function readStandardInput(): string { } export function runPlanCommand(command: 'plan-validate' | 'plan-apply', args: string[]): void { - const usage = `theorem-os ${command} [--file FILE] [--workspace DIR]`; + const usage = `theorem-os ${command} [--file FILE] [--workspace DIR]` + (command === 'plan-apply' ? ' [--publish]' : ''); let field = 'arguments'; try { const { values } = parseArgs({ args, options: { file: { type: 'string' }, workspace: { type: 'string' }, worktree: { type: 'string' }, + ...(command === 'plan-apply' ? { publish: { type: 'boolean' as const } } : {}), help: { type: 'boolean', short: 'h' }, } }); if (values.help) { console.log(JSON.stringify({ usage, description: 'Read a complete plan or revision from --file or stdin. ' + 'Use the Lead workspace with COOPERATION.json, or a prepared workspace with active-problem.json. ' + - (command === 'plan-apply' ? 'Save a validated draft in RESEARCH.md for host intake.' : 'Report validation issues.') })); + (command === 'plan-apply' ? 'Save a validated draft in RESEARCH.md, or use --publish to queue it for the current Lead dispatch.' : 'Report validation issues.') })); return; } if (values.worktree && values.workspace) throw new Error('Choose --workspace or --worktree.'); @@ -36,7 +37,8 @@ export function runPlanCommand(command: 'plan-validate' | 'plan-apply', args: st field = 'stdin'; input = { workspace, text: readStandardInput() }; } else input = { workspace, file: values.file }; - const result = command === 'plan-apply' ? applyCooperationPlanFile(input) : validateCooperationPlanFile(input); + const result = values.publish ? publishCooperationPlanFile(input) : + command === 'plan-apply' ? applyCooperationPlanFile(input) : validateCooperationPlanFile(input); console.log(JSON.stringify(result)); if (!result.ok) process.exitCode = 1; } catch (error) { diff --git a/scripts/test-codex-backend-delivery.ts b/scripts/test-codex-backend-delivery.ts index 01cb516e..4d0e8d91 100644 --- a/scripts/test-codex-backend-delivery.ts +++ b/scripts/test-codex-backend-delivery.ts @@ -117,7 +117,7 @@ export async function verifyNativeProofDelivery(input: { repository: string; exe if (!childRequest) assert.doesNotMatch(host.description, /\bD\d{3}\b/u, 'The shared Lead tool must not preselect a domain expert for unrelated assignments.'); assert.deepEqual([...host.parameters.properties.operation.enum].sort(), (childRequest - ? ['yield', 'history', 'inspect', 'inspect-research', 'submit', 'submit_helpers', 'route_summary'] + ? ['yield', 'history', 'inspect', 'inspect-research', 'submit', 'route_summary'] : ['finish', 'history', 'inspect', 'inspect-research', 'adopt', 'retire_route', 'route_summary']).sort(), 'Native host operations must stay limited to proof delivery, route management and inspection.'); assert.equal(body.tool_choice, 'auto', 'The host must not impose a collaboration decision.'); diff --git a/scripts/test-web-cooperative-runtime.ts b/scripts/test-web-cooperative-runtime.ts index 11038ecf..8a837522 100644 --- a/scripts/test-web-cooperative-runtime.ts +++ b/scripts/test-web-cooperative-runtime.ts @@ -17,7 +17,7 @@ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const execute = promisify(execFile); const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); const editId = 'web-cooperative-edit', guidanceId = 'web-cooperative-direction'; -const proveMarker = 'WEB_COOPERATIVE_PROVE_FIRST', reviewMarker = 'WEB_COOPERATIVE_RELEASE_REVIEW'; +const proveMarker = 'WEB_COOPERATIVE_PROVE_FIRST', secondProofMarker = 'WEB_COOPERATIVE_PROVE_SECOND'; const terminal = (run: WebRun) => ['completed', 'error', 'cancelled'].includes(run.status); const docker = (args: string[], timeout = 30_000) => execute('docker', args, { cwd: root, timeout, maxBuffer: 16 * 1024 * 1024 }); @@ -130,18 +130,12 @@ export async function runWebCooperativeSmoke(argv = process.argv.slice(2)) { const queuedEdit = await jobs.command(owner, run.id, { type: 'edit', proposal }); assert.ok(['queued', 'received', 'applied'].includes(queuedEdit.status)); assert.equal(queuedEdit.commandDigest, preview.commandDigest); - await wait('host applies the complete plan, rechecks revised targets, and starts independent review', () => Boolean( - run?.observation?.inspection.edits.find(edit => edit.id === editId)?.recheck?.status === 'passed' && - run.observation.inspection.review?.status === 'running')); - const rechecked = await capture(), edit = rechecked.inspection.edits.find(item => item.id === editId)!; - assert.equal(edit.status, 'applied'); assert.notEqual(edit.planVersion, proposal.baseVersion); - assert.equal(edit.recheck!.tasks.length, 2); - for (const item of edit.recheck!.tasks) { - assert.equal(item.status, 'passed'); assert.equal(item.lastCheck!.passed, true); - assert.ok(item.lastCheck!.receiptIds.length); - assert.equal(item.taskDigest, rechecked.inspection.tasks.find(task => task.id === item.taskId)!.version); - } - assert.notEqual(rechecked.inspection.tasks.find(task => task.id === 'goal_1')!.version, first.version); + await wait('host applies the revised plan and starts the second proof', () => Boolean( + run?.observation?.inspection.edits.find(edit => edit.id === editId)?.status === 'applied' && + run.observation.inspection.workers.some(worker => worker.id === 'engineer' && worker.task === 'goal_2' && + worker.scheduling?.status === 'working'))); + const revised = await capture(), second = revised.inspection.tasks.find(task => task.id === 'goal_2')!; + assert.notEqual(revised.inspection.tasks.find(task => task.id === 'goal_1')!.version, first.version); const duplicate = await jobs.command(owner, run.id, { type: 'edit', proposal }); assert.equal(duplicate.status, 'applied'); const auditScript = `const fs=require('node:fs'),path=require('node:path'),cp=require('node:child_process'); @@ -158,12 +152,10 @@ export async function runWebCooperativeSmoke(argv = process.argv.slice(2)) { assert.ok(audit.proofNotes.some((item: { notes: { fixture?: { guidanceReceived?: string } } }) => item.notes.fixture?.guidanceReceived?.includes(proveMarker)), 'A frozen worker note must retain the guidance actually received through turn/steer.'); write('host-audit.json', audit); - const reviewerId = rechecked.inspection.review!.workerId!; - assert.equal(reviewerId, 'researcher-1', 'The independent reviewer must be a separate peer from the proof Engineer.'); - const release = guidance(rechecked, { id: 'web-cooperative-review-release', recipient: { kind: 'worker', id: reviewerId }, - text: `${reviewMarker}: report the review of this fixed candidate. Final acceptance remains with S3.` }); + const release = guidance(revised, { id: 'web-cooperative-second-proof', recipient: { kind: 'task', id: second.id }, + taskRef: { id: second.id, version: second.version }, text: `${secondProofMarker}: prove the second goal using Nat.zero_add.` }); assert.ok(['queued', 'deferred', 'delivered'].includes((await jobs.command(owner, run.id, { type: 'guidance', guidance: release })).status)); - await wait('independent reviewer settles and final Lean/S3 accepts both original targets', () => terminal(run!), 180_000); + await wait('final Lean/S3 accepts both original targets', () => terminal(run!), 180_000); assert.equal(run.status, 'completed', run.error); assert.equal(run.result!.status, 'evaluated_passed', JSON.stringify(run.result!.report)); assertWebEnvironmentReport(run.result!.report, 'standard'); @@ -174,7 +166,16 @@ export async function runWebCooperativeSmoke(argv = process.argv.slice(2)) { // Canonical integration can remove empty lines between unchanged declaration headers. assert.equal(run.result!.proof.replace(/\n\n+/gu, '\n'), input.source.replace('by sorry', 'by rfl').replace('by sorry', 'by exact Nat.zero_add n').replace(/\n\n+/gu, '\n')); - assert.equal(run.observation!.inspection.review!.status, 'accepted'); + const finished = run.observation!.inspection, edit = finished.edits.find(item => item.id === editId)!; + assert.equal(edit.status, 'applied'); assert.notEqual(edit.planVersion, proposal.baseVersion); + assert.equal(edit.recheck!.status, 'passed'); + assert.equal(edit.recheck!.tasks.length, 2); + for (const item of edit.recheck!.tasks) { + assert.equal(item.status, 'passed'); assert.equal(item.lastCheck!.passed, true); + assert.ok(item.lastCheck!.receiptIds.length); + assert.equal(item.taskDigest, finished.tasks.find(task => task.id === item.taskId)!.version); + } + assert.equal(finished.review, undefined); assert.equal(run.observation!.acceptance, 'not-assessed'); assert.equal(run.observation!.inspection.configuration.methodDigest, run.moduleConfiguration!.methodDigest); assert.equal(run.observation!.guidance.find(item => item.id === release.id)!.status, 'delivered'); @@ -197,7 +198,7 @@ export async function runWebCooperativeSmoke(argv = process.argv.slice(2)) { workers: run.observation!.inspection.workers.map(worker => ({ id: worker.id, role: worker.role, turns: worker.turns })), initialPlanPublished: true, guidanceDeliveredToExactTask: delivered, actualGuidanceRetainedInFrozenWorkerNotes: true, previewReadOnly: true, previousCheckedTaskVersion: first.version, edit: edit, duplicateEditAppliedOnce: true, - independentReviewer: reviewerId, result: run.result, archive: archive, containerRemoved: removed, + result: run.result, archive: archive, containerRemoved: removed, artifacts: ['observations.json', 'host-audit.json', 'archive.json', 'commands.json', 'trace.json'] }); console.log('Cooperative Docker / command / host / Lean checks passed. Report: out/web-cooperative-smoke/report.json'); } catch (error) { diff --git a/scripts/web-sample-actions.ts b/scripts/web-sample-actions.ts index 33f5deb2..9053346d 100644 --- a/scripts/web-sample-actions.ts +++ b/scripts/web-sample-actions.ts @@ -71,13 +71,16 @@ export function sampleActions(sample: Pick event.type === 'review_assigned'), reviewer = assigned?.details?.workerId; - const review = observations.at(-1)?.inspection?.review; - const asked = reviewer && observations.at(-1)!.guidance.find(item => item.deliveredTo?.includes(reviewer)); - if (!reviewer || !review || !asked) throw new Error('no recorded review'); - write(reviewer, time(asked.updatedAt, 100), [{ path: 'RESEARCH.md', kind: 'add', - diff: JSON.stringify({ commit: review.commit, verdict: review.status, summary: review.summary }, null, 2) + '\n' }]); + // Older recordings include a guided review turn. + const assigned = events.find(event => event.type === 'review_assigned'); + if (assigned) { + const reviewer = assigned.details?.workerId; + const review = observations.at(-1)?.inspection?.review; + const asked = reviewer && observations.at(-1)!.guidance.find(item => item.deliveredTo?.includes(reviewer)); + if (!reviewer || !review || !asked) throw new Error('no recorded review'); + write(reviewer, time(asked.updatedAt, 100), [{ path: 'RESEARCH.md', kind: 'add', + diff: JSON.stringify({ commit: review.commit, verdict: review.status, summary: review.summary }, null, 2) + '\n' }]); + } return written.sort((a, b) => a.at.localeCompare(b.at)).map((item, index) => ({ ...item.body, sequence: index + 1, at: item.at })); } diff --git a/skills/theoremos-research/SKILL.md b/skills/theoremos-research/SKILL.md index c727dde5..c95a93a6 100644 --- a/skills/theoremos-research/SKILL.md +++ b/skills/theoremos-research/SKILL.md @@ -13,7 +13,7 @@ When the host selects native AgentControl, use the exposed native collaboration When `theoremos_team` is exposed, Lead organizes a flat team using the [Lead charter](references/team-roles.md#lead--organize-and-connect-the-work), which the host injects into Lead's stable instructions at startup and continuation. Assign concrete gaps with usable outputs and keep one owner per active obligation, including Lead's own work. While a member owns a gap, Lead advances its consumer or another gap and integrates findings. Follow [parallel-work.md](references/parallel-work.md) for the current operation contracts. -Choose expertise for the specific missing concept, assumption or formal interface. Begin the assignment with a `Profiles:` header listing [member work profiles](references/team-roles.md#select-a-member-profile) or relevant domain IDs or slugs. The coordinator's `lead` profile cannot be assigned. A work profile alone is valid. The host loads core knowledge and locators for reading on demand; custom expertise can be described in the assignment. Give the member its gap, known inputs, intended consumer and first useful result. Say what work remains with you. The member chooses its proof approach. Choose inherited history to suit the task, following [parallel-work.md](references/parallel-work.md#identity-and-assignments). +Choose expertise for the specific missing concept, assumption or formal interface. Use the [assignment format](references/parallel-work.md#identity-and-assignments) to select a member profile or tag work by route when useful. The host loads profile material for reading on demand. Give the member its gap, known inputs, intended consumer and first useful result. Say what work remains with you. The member chooses its proof approach. Members send the first usable finding, probe result or blocker through native messages (historical host-tools may use `progress`), with the exact claim or question, assumptions and available evidence. Do not wait for every subgoal before reporting. Private reasoning is not a team update. These are research milestones, without fixed polling intervals, message counts or task quotas. @@ -21,7 +21,7 @@ Use native `followup_task` for further instructions and `interrupt_agent` to sto Frozen original declarations retain their statements, hypotheses and permitted source structure. Add independent helpers inside the exact editable Lean paths supplied by the host; the same filename in different members' worktrees denotes separate copies. Lead describes mathematical work while the host supplies file and delivery rules. Keep scratch experiments under the documented scratch paths; transfer useful helpers through the current owned-file delivery interface. Helpers may be checked while unrelated original goals remain open, but cannot depend on those holes or new axioms. -Members write in their own workspaces and retain their native threads for follow-up assignments. When a helper answers the assignment, save sources and RESEARCH.md, message Lead, `submit` and return for host checking. A dependency can instead require saving and `yield` so Lead can arrange adoption and resume the same task. Lead saves before adoption or `finish`. These handoffs stop writing before independent checking. Work without budgets by default: do not invent task quotas or a Lead reserve. Respect explicitly configured shared run limits and actual host deadlines. +Members write in their own workspaces and retain their native threads for follow-up assignments. When a helper answers the assignment, save sources and RESEARCH.md, `submit` and return. The host checks the declarations and notifies Lead. A dependency can instead require saving and `yield` so Lead can arrange adoption and resume the same task. Lead saves before adoption and returns after saving the complete original proof for independent checking. Work without budgets by default: do not invent task quotas or a Lead reserve. Respect explicitly configured shared run limits and actual host deadlines. Use these references when the work calls for them: diff --git a/skills/theoremos-research/references/cooperation.md b/skills/theoremos-research/references/cooperation.md index a6152ac4..78651c0f 100644 --- a/skills/theoremos-research/references/cooperation.md +++ b/skills/theoremos-research/references/cooperation.md @@ -4,7 +4,7 @@ Use this reference only for a host-assigned cooperative role. The model chooses ## Shared rules -The current assignment and `.scratch/theoremos-help.md` provide exact paths, interfaces, versions, nonce and feedback. They supersede old dispatch values. Use only exposed tools within current permissions. The host owns task assignment, isolation, integration, approvals and budgets; create additional agents only when it permits them. +The current assignment and `.scratch/theoremos-help.md` provide exact paths, interfaces and feedback. They supersede old dispatch values. Use only exposed tools within current permissions. The host owns task assignment, isolation, integration, approvals and budgets; create additional agents only when it permits them. Append complete newline-terminated JSON events to the current delivery log. A missing log is normal; create it by appending. Preserve earlier events. In an assignment-scoped task log, omitted `id`, `taskId`, `taskDigest` and `kind` are supplied by the host (`kind` defaults to `progress`); supplied task identity must match the assignment. Explicit event and task IDs use `[A-Za-z0-9_-]{1,64}`. @@ -12,15 +12,12 @@ Edit only assigned source paths. Preserve other seed proofs and frozen declarati ## Lead plan -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: +Leave Lean sources unchanged and delegate Lean diagnostics to workers. Omit `progressReview` on the initial plan. Save your plan or revision with any [required decisions](#required-lead-decisions) in `.scratch/plan.json`. Use the command from Lead plan submission in `.scratch/theoremos-help.md`. -```json -{"kind":"plan","baseVersion":"CURRENT_BASE_VERSION","dispatchNonce":"CURRENT_DISPATCH_NONCE","summary":"route and consumers","tasks":[]} -``` +- To dispatch work during the turn, run `theorem-os plan-apply --publish --file .scratch/plan.json`. It validates the draft and binds the current dispatch. Publish once, save concise route notes and return promptly. +- To submit on return, run `theorem-os plan-apply --file .scratch/plan.json`. It validates the draft and atomically replaces the plan block in `RESEARCH.md`. A revision saved this way includes its `baseVersion` from `COOPERATION.json.planVersion`. -Replace dispatch values from the assignment; omit `dispatchNonce` if none is supplied. Replace the empty `tasks` array with the complete graph. The first plan covers every original target exactly once. Keep checked task contracts and active unrelated assignments stable. Publish once per dispatch, save concise route notes and return promptly without polling approval or copying the published graph into other responses. - -When returning without live publication, save the graph or revision as a JSON file with any [required decision fields](#required-lead-decisions). From the Lead worktree, run `theorem-os plan-validate --file .scratch/plan.json` to see field-level issues, then `theorem-os plan-apply --file .scratch/plan.json` to replace the plan block in `RESEARCH.md` atomically. Both commands also read JSON from stdin. `planVersion` in the result fingerprints the validated draft. Use `COOPERATION.json.planVersion` as the accepted `baseVersion` for a revision. Return after saving so the host can check the draft against live state. +The first plan covers every original target exactly once. Keep checked task contracts and active unrelated assignments stable. For `idleWorkers` with `m3-no-ready`, `dependency-blocked` or `m5-no-selection`, inspect M3 readiness, role/owner and saved-assignment pins. Publish an executable revision, name the concrete running dependency when waiting, or explicitly pause the route. Returning an unchanged accepted graph does not resolve that continuous idle episode. @@ -38,7 +35,7 @@ Typed declaration final name components must be unique and must not reuse frozen Proof `dependsOn` names actual typed inputs. Advisory dependencies are inspection inputs rather than proof premises. Only untyped research/sketch may use `consumerGoalIds` to name original goals; connect typed helpers through consumer dependencies or [proof routes](#optional-task-forms). -Optional task metadata includes `premises`, `informalProof` (at most 2000 characters), `citations` (at most 8 references, 300 characters each), `researchSource` (`mathlib`, `verified-library`, `public-literature`; advisory tasks only), and `reviewScope` (`feasibility` or `final-candidate`; advisory tasks only). Final-candidate review waits for freshly checked original goals. Blueprints and citations do not change proof contracts. For statement-meaning review, use `statementReview:true` with `informalStatement` and the assignment's review interface. +Optional task metadata includes `premises`, `informalProof` (at most 2000 characters), `citations` (at most 8 references, 300 characters each), `researchSource` (`mathlib`, `verified-library`, `public-literature`; advisory tasks only), and `reviewScope` (`feasibility` or `final-candidate`; advisory tasks only). Active final-candidate entries send their objectives to one fixed Reviewer after the host checks the complete candidate. The verdict is saved in the run’s review record. Blueprints and citations do not change proof contracts. For statement-meaning review, use `statementReview:true` with `informalStatement` and the assignment's review interface. Optional `groups` carry `id`, `objective`, `status`, `revision`, `engineerId`, `maxTurns` and `maxConcurrent`. Tasks use `groupId` and `sharing` (`group` or `problem`); cross-group inputs require problem sharing. Use `ownerId` only for an intentional reservation. Omitting it does not release an existing assignment. Do not copy host-owned capacity explorations or pending-check tasks into the editable graph or use their IDs as proof premises. @@ -75,31 +72,29 @@ A proof or research worker can publish standalone helpers before finishing its a The host snapshots the saved files and independently checks the helpers and their same-file helper dependencies. Keep the original target and its unfinished body intact. The host publishes checked signatures with their canonical commit. Other workers can inspect that commit or reuse the helpers in their next seeded worktree. Publishing a helper does not complete the assignment. -Save the assigned exact declaration in its allowed proof file, then append: +Save the assigned exact declaration in its allowed proof file and return for host checking. For an early handoff, append: ```json {"kind":"ready","summary":"saved assigned proof"} ``` -Omit `commit` and `targets`; the host selects and freezes the source for the assigned declaration. Stop writing and return. Natural return also submits saved work. Read `COOPERATION.json.proofReadyRecords` for the specific result. A new attempt after failure uses a new event ID; an unchanged submission is deduplicated. Unconfirmed writer shutdown causes host quarantine rather than acceptance. +Omit `commit` and `targets`; the host selects and freezes the source for the assigned declaration. Stop writing after the early handoff. Read `COOPERATION.json.proofReadyRecords` for the specific result. A new attempt after failure uses a new event ID; an unchanged submission is deduplicated. Unconfirmed writer shutdown causes host quarantine rather than acceptance. Unfinished typed work may deliver an intermediate [research finding](#research-delivery) without changing its proof obligation. A progress event such as `{"summary":"current result and remaining gap"}` does not complete or accept the proof. ## Research delivery -Save findings and reproducible evidence in `RESEARCH.md`, then append: +Save findings and reproducible evidence in `RESEARCH.md`. Return with those notes to complete the advisory assignment. To share useful progress or request a Lead decision during the turn, save the finding object in `.scratch/finding.json` and use `research-observe` from the generated tool help. ```json -{"kind":"research","finding":{"summary":"argument, assumptions and remaining gap","conclusion":"inconclusive","needsDecision":true,"evidenceRefs":[],"remainingObligations":[],"lemmaRequests":[]}} +{"summary":"argument, assumptions and remaining gap","conclusion":"inconclusive","remainingObligations":[]} ``` -Choose one `conclusion`: `supporting`, `refuted` or `inconclusive`. Use `refuted` only for a concrete refutation of the scoped claim; failed search or an unknown inference is inconclusive. `summary` is nonempty; optional `premises` and `remainingObligations` are string arrays. Set `needsDecision:true` for a route decision. Findings remain advisory. - -Put `lemmaRequests`, `mathematicalGap`, `blockers`, `checkOutcome` and `replacesReceipt` **inside `finding`**. Lemma requests need new IDs and complete typed task definitions (`kind:"lemma"`, objective, theorem name, closed type, owned proof path and dependencies) in the same route group. They become proof assignments only after Lead adoption; proposals do not authorize source edits. +Use `supporting`, `refuted` or `inconclusive`. Reserve `refuted` for a concrete refutation of the scoped claim. Optionally include `premises`, `evidenceRefs`, `mathematicalGap`, `blockers`, `checkOutcome`, `lemmaRequests` or `replacesReceipt`. Set `needsDecision:true` when Lead must choose a route or resolve a blocker. Lemma requests need new IDs and complete typed definitions in the same route group. They become proof assignments after Lead adoption. -Advisory research/sketch leaves Lean files as in the assignment seed on delivery. A typed finding that relies on changed supporting Lean sources must bind those sources: outer event `sources` maps **every currently allowed owned, nonfrozen Lean path** to its complete UTF-8 content, at most 1,000,000 bytes total. Serialize from files. Exact allowed paths come from the current assignment. Without `sources` or `commit`, the finding is bound to its seed; a supporting immutable `commit` must descend from that seed. These two fields are mutually exclusive. The normal flow uses host source snapshots, not worker-created commits. +Use `--probe FILE` to retain the code of a Lean probe. Leave advisory assignment sources as in their seed when delivering findings. For a typed assignment, use `--snapshot-sources` when the finding depends on changed saved Lean sources. Ordinary findings remain advisory. -If exposed by current help, `theorem-os research-observe --worktree WORKTREE --finding FINDING_FILE [--probe LEAN_FILE] [--snapshot-sources]` validates and records this report. `--finding` takes a file containing the finding object, not inline JSON or the outer delivery event. +When the host requests a context checkpoint, save your current notes and any drafts, publish useful findings or plans, run the checkpoint command in the request, then return. ## Independent review @@ -113,7 +108,7 @@ Choose `accepted` or `changes_requested`; identify the exact change for the latt ## Gaps, blockers and checks -Use these fields when reporting a scoped unresolved inference; they do not refute the original problem or create proof premises. A research event nests them in `finding`; a progress event may carry `mathematicalGap` or `blockers` at the top level. +Use these fields when reporting a scoped unresolved inference; they do not refute the original problem or create proof premises. Put them in the finding file passed to `research-observe`. ### Mathematical gap @@ -139,7 +134,7 @@ Optional `blockerId` refers to an existing blocker for this task/route. Optional ### Assigned check outcome -Complete a pending host check with `finding.checkOutcome`: +Complete a pending host check with `checkOutcome` in the finding: ```json {"checkId":"ASSIGNED_CHECK_ID","conclusion":"inconclusive","summary":"scoped result","evidenceRefs":[]} @@ -162,13 +157,13 @@ Read the current assignment's referenced `COOPERATION.json` records and feedback A delivery's `summarySource` points to its full finding in the context manifest. If that section was omitted for budget, retrieve notes using `savedSource.commit` and `savedSource.notesPath`; omission does not mean no result was saved. A "Saved Lead draft pending integration" similarly retains interrupted source work at a fixed commit. Inspect it with `git show COMMIT:PROJECT_RELATIVE_PATH`, then recover useful declarations through typed tasks against current canonical sources, preserving integrated proofs. Drafts still require normal host checking. -For intake corrections, inspect **every** `deliveryReceipts` row scoped to this worker, task, task digest, seed, assignment and environment with status `needs-correction`. Match any supplied receipt index/count/digest. Append a complete corrected research event with `finding.replacesReceipt` set to that receipt ID; preserve the log and earlier evidence. If the correction is rejected, replace its new receipt. Each independent rejected submission needs its own correction; only the verified replacement chain is resolved. +For intake corrections, read each `needs-correction` row in the current assignment’s `COOPERATION.json.deliveryReceipts`. Rerun `research-observe` with `replacesReceipt` set to that receipt ID in the corrected finding file. If the correction is rejected, replace its new receipt. Each independent rejected submission needs its own correction; only the verified replacement chain is resolved. Correcting an earlier **valid** finding is different: update the active note's conclusion, cite the immutable old commit/finding digest, identify the bad inference, and retain corrected evidence and remaining gap. Publish a new `needsDecision:true` finding; Lead then revises or rechecks the affected route. Do not rewrite archived findings. ### Delivered guidance -Only for guidance actually delivered to this assignment, include top-level `guidanceDecisions`, outside `finding`: +Only for guidance actually delivered to this assignment, include `guidanceDecisions` in the plan, finding file or final response: ```json [{"guidanceId":"DELIVERED_ID","status":"accepted","reason":"specific reason","evidenceRefs":[]}] diff --git a/skills/theoremos-research/references/domain-experts.md b/skills/theoremos-research/references/domain-experts.md index 62202d9b..6a9c0d76 100644 --- a/skills/theoremos-research/references/domain-experts.md +++ b/skills/theoremos-research/references/domain-experts.md @@ -6,7 +6,7 @@ Each profile's **Reading** link leads to [collected domain materials](domain-mat ## Choose and combine -Select expertise from the missing concept and its actual objects, definitions and assumptions. Use the index to locate that knowledge; a broad label such as algebra does not imply that ideals, field extensions or representations will help a particular calculation. A cross-domain question can combine specialties in one member. Put the selected IDs or slugs after `Profiles:` on the first line. If only a work responsibility is needed, choose it without a domain. Give the question, known inputs, intended consumer and useful output on the following lines. The host supplies selected profiles and locators for reading on demand; inspect the loading modes and unresolved selection record. There is no separate domain or role tool parameter. +Select expertise from the missing concept and its actual objects, definitions and assumptions. Use the index to locate that knowledge. A broad label such as algebra does not imply that ideals, field extensions or representations will help a particular calculation. A cross-domain question can combine specialties in one member. Put the selected IDs or slugs on the optional `Profiles:` line in the [assignment format](parallel-work.md#identity-and-assignments). If only a work responsibility is needed, choose it without a domain. Give the question, known inputs, intended consumer and useful output in the assignment body. The host supplies selected profiles and locators for reading on demand. For example, assign a representation theorist the question whether a specified invariant subspace has an invariant complement, giving the group, field and action. The expert selects the relevant knowledge and decides how to investigate it. Several profiles can fit the same question; use complementary knowledge where it helps and give additional members distinct questions. diff --git a/skills/theoremos-research/references/parallel-work.md b/skills/theoremos-research/references/parallel-work.md index fee073f1..f76b29f2 100644 --- a/skills/theoremos-research/references/parallel-work.md +++ b/skills/theoremos-research/references/parallel-work.md @@ -40,11 +40,11 @@ Make the dispatch message self-contained: give the selected profiles, concrete g Choose native `fork_turns` for the assignment. Use `"none"` with a self-contained question when prior conversation is unnecessary, especially for independent reconstruction or review. Use `"all"` when continuing reasoning that needs inherited history; it can contain tentative answers, obsolete tool results and Lead's route. Full-history forks inherit the parent's model and reasoning effort, with native provenance but no access to another member's mutable files. The child still receives the host's current assignment, source permissions and its own workspace. Historical host-tools children start without Lead's conversation. For an independent review, choose a member who did not produce the work and provide the fixed claim and required evidence without prescribing the verdict. Record prior exposure rather than claiming independence after an answer-bearing fork. -Put only catalogue IDs or slugs on the first line, for example `Profiles: prover`. Put role explanations and custom specialties in the message body. If the host rejects a selection, correct that line and retry the assignment to the same member name. The host loads selected profile sections and provides local reading locators from the pinned Skill. A native followup without a new header keeps the current selection; a valid new header switches it while earlier specialties remain history. A new task can also omit the header and describe the expertise needed in its body. +Native `spawn_agent` and `followup_task` use the same message format. Put an optional `Route: ROUTE_ID` line first, an optional `Profiles: prover, D006` line next, then the assignment. The `Profiles:` line lists only catalogue IDs or slugs. Put custom expertise in the body. Historical host-tools use the `routeId` argument and put `Profiles:` first in `message` if present. The host loads selected profile sections and provides local reading locators from the pinned Skill. A native followup keeps the current selection unless it supplies a new one. The task retains `profileEvidence`: the pinned Skill digest and source file, anchor, line range, digests and loading mode. An `available-on-demand` entry identifies readable material; it does not claim its text reached the model. When a passage informs a finding, name its anchor and concrete application in the message or RESEARCH.md. A loading record or reported use does not prove expert contribution or a fresh external-source read. -Lead uses native `followup_task` for further instructions, including a changed objective or specialty. Put any new `Profiles:` selection on its first line. The saved task retains the draft, instruction history and loaded profile identities; earlier findings remain evidence from their original context. Historical host-tools use `amend(agentId, taskId, message, reason, workKind?)` for an objective change, preserving their revision history and optional research, proof, independent-reconstruction, review or assembly work kind. A discussion message in either transport is advisory. +Lead uses native `followup_task` for further instructions, including a changed objective or specialty. The saved task retains the draft, instruction history and loaded profile identities; earlier findings remain evidence from their original context. Historical host-tools use `amend(agentId, taskId, message, reason, workKind?)` for an objective change, preserving their revision history and optional research, proof, independent-reconstruction, review or assembly work kind. A discussion message in either transport is advisory. `inspect` records exposure to a checked peer delivery. Adoption records reuse and its producer, task and commit; that information persists across assignments and is attached to later proof deliveries. Members use independent Git object stores and cannot browse mutable peer workspaces. These records describe explicit transfers, not complete mathematical independence: messages, prior work and the seeded sources also inform reasoning. Do not describe a proof assembled from peer results as an independent reconstruction. Preserve the original authors of reused results even when your delivery also contains their declarations. @@ -56,14 +56,14 @@ Communicate a useful reduction, blocking question or contradictory finding as so Apply the [Lead charter](team-roles.md#lead--organize-and-connect-the-work) when sharing ownership, receiving findings or deciding adoption. Assess native messages and available results, or the durable inbox in historical host-tools mode, when they affect the work. When the first usable result is ready, handle its submission, checking and adoption before requesting optional extensions. Use the current transport's instruction mechanism when responsibility changes. -A member reports the first usable finding, local probe result or blocker when it can affect another member's work, including on a whole-target assignment. Send the exact claim, assumptions, argument or diagnostic and remaining uncertainty, and save reproducible notes. Once independent Lean declarations answer the assignment, message Lead, save source and RESEARCH.md, call `submit` and return for host checking before expanding into a peer's gap. Remaining holes in unrelated original targets do not prevent a helper delivery. If a host command fails, send its command, diagnostic and any documented fallback result; distinguish infrastructure failure from a failed mathematical argument. Lead can arrange the next assignment once the result has entered the checking and handoff path. +A member reports the first usable finding, local probe result or blocker when it can affect another member's work, including on a whole-target assignment. Send the exact claim, assumptions, argument or diagnostic and remaining uncertainty, and save reproducible notes. Once independent Lean declarations answer the assignment, save source and RESEARCH.md, call `submit` and return for host checking before expanding into a peer's gap. Remaining holes in unrelated original targets do not prevent a helper delivery. If a host command fails, send its command, diagnostic and any documented fallback result; distinguish infrastructure failure from a failed mathematical argument. Lead can arrange the next assignment once the result has entered the checking and handoff path. Native members use `send_message` for findings, probe results, blockers and route changes. Choose a useful question or probe and report its result when it matters to someone else, with its assumptions and evidence. Historical host-tools additionally support optional structured `progress` records. Private transcript commentary is not a shared message, and reported progress does not grant proof acceptance. For example, send the consumer the exact candidate type, the hypotheses that work, the application that fails, and the goal Lean leaves open. Keep those facts and the next experiment in RESEARCH.md. After `send_message`, retain its `submission_id` in the notes so Lead can match the message to the saved artifact. - When you try a peer result, save the single Lean probe and use the normal `check-lean` command with `--candidate` and its reference. Use `message:`, `research:`, or `delivery:` from this run. Report the result and any remaining hypotheses. -- When a finding changes an assignment, put one line such as `Based on: research:` in the native spawn or `followup_task` message. Give the new scope in the body. Keep any `Profiles:` header on the first line. +- When a finding changes an assignment, put a line such as `Based on: research:` after any `Route:` and `Profiles:` lines. Give the new scope in the body. - For formal reuse, use `adopt` with the checked delivery ID and the consumer workspace. The host records the integration receipt when the write succeeds. For a computational finding, send its intended consumer the domain and assumptions, the input and command, and the decisive output (for example, a witness or a failed constraint). A plotted pattern is a conjecture until checked. Keep reproducible details in `RESEARCH.md`; a path into your private scratch directory alone is unusable by a peer. @@ -78,7 +78,7 @@ When a peer dependency or Lead decision blocks the current task, save the draft Save before `submit` or `yield`. Both also request an automatic handoff at the next unpaid request boundary. The current paid response and its tool calls settle first; the host then confirms writer shutdown. Submission enters declaration checking; yielding retains the task for resume. No further model request is needed to poll this handoff. -When all original proofs are saved, Lead can call `finish(summary)` to request whole-problem checking even when a local diagnostic could not start. Return after the call; the host also hands off before the next request, freezes actual sources and independently checks every original target. This is a submission request, not acceptance. Remaining holes or failed checks return ordinary feedback for continued work. +Lead saves all original proofs and returns for independent checking. For an early handoff, call `finish(summary)` after saving. Return after the call; the host also hands off before the next request, freezes actual sources and independently checks every original target. This is a submission request, not acceptance. Remaining holes or failed checks return ordinary feedback for continued work. Do not invent task budgets or a Lead reserve. Native team tools expose no local allowance controls. Report observed usage as usage, without turning it into a stopping rule. @@ -98,11 +98,10 @@ After an executed task's writer has stopped, the host saves a stable `sourceComm ### Historical host-tools compatibility -These additional collaboration and note operations apply only when advertised by the historical transport. Decision notes and publication do not gate research or schedule a turn handoff. +These additional operations apply only when advertised by the historical transport. Publication is advisory. | Operation | Caller | Arguments and result | | --- | --- | --- | -| `coordinate` | Lead | `decision` (`defer` or `continue`), `reason`, `nextStep`: save an optional advisory decision note. | | `spawn` | Lead | `agentId`, `message`: create a child and queue its first assignment; returns a task ID. Optional `budget:{tokens?,turns?}` is available only with a finite host allowance. | | `assign` | Lead | `agentId`, `message`: queue follow-up work for an existing child. Optional `budget:{tokens?,turns?}` is available only with a finite host allowance. | | `amend` | Lead | `agentId`, `taskId`, `message`, `reason`, optional `workKind`: revise a queued, running or paused objective without replacing the task or draft. `spawn`/`assign` also accept optional `workKind`. | @@ -119,23 +118,23 @@ These additional collaboration and note operations apply only when advertised by | `wait` | Any member | `after`, optional `timeoutMs` from 1 to 30000: wait for addressed events, then return the same snapshot as `poll`. | | `inspect` | Any member | `deliveryId`: read a checked delivery's declarations, provenance, commit, imports and evidence. For a truncated source change, call `inspect` again with the same delivery ID, its `changeIndex` and `nextOffset` as `offset`. Each page returns up to `limit` Unicode code points (default and maximum 16,000). Reading a page does not adopt it. | | `inspect-research` | Any member | `artifactId`, optional `offset` and `limit` in Unicode code points: read a page of saved research notes at their fixed commit; follow `nextOffset` until complete. | -| `submit` | Child | `summary`, `declarations`: nominate the current assignment's exact declarations for checking after returning. | +| `submit` | Child | `summary`, `declarations`: nominate exact declarations for checking after returning. Optional `helpersOnly: true` shares standalone helpers and keeps the assignment open. | | `adopt` | Lead | `deliveryId`, optional `targetId` (default `lead`): queue checked integration into Lead or an idle child; returns before integration completes. | | `stop` | Lead | `agentId`: prevent further assignments and request interruption of an active child; shutdown finishes asynchronously. | -`spawn` and `assign` queue work without waiting for its completion. Receive results through `poll` or `wait`, passing the cursor returned by either receive operation as `after` on the next one. Each result can arrive while other children continue. Messages and completion summaries are advisory. Use `inspect` to assess a proof delivery before deciding whether to adopt it. A saved result is available even after its producer receives another assignment. +`spawn` and `assign` queue work without waiting for its completion. Receive results through `poll` or `wait`, passing the cursor returned by either receive operation as `after` on the next one. Each result can arrive while other children continue. Messages and completion summaries are advisory. Use `inspect` if you need the exact interface or evidence for an adoption decision. A saved result is available even after its producer receives another assignment. ### Source checking and adoption -To check a long proof before adoption in either transport, read its frozen source pages through `inspect` until there is no `nextOffset`. Keep the same `deliveryId` and `changeIndex` between calls. +Adopt by delivery ID when the checked interface fits. For a source review, `inspect` can page through a long frozen declaration using the same `deliveryId` and `changeIndex` with each `nextOffset`. For a new auxiliary `def` or `abbrev`, add `"kind":"definition"` to that declaration in `submit`. Supply its full closed type and name in the existing editable file; omit `kind` for theorem/lemma declarations. A consumer adopts the checked implementation. Submit claims about its behavior as separate theorems. This does not allow replacing an existing definition or transferring new files, structures or instances. An acknowledged submission keeps the assignment revision at nomination. Interrupting a member stops its work; submitted declarations still go to the checker after confirmed writer shutdown. A busy followup may report a pending submission: let the check settle before assigning new work. For a rejected Lean check, give the repairing member the producer's `history` locator from the failure notice. The full task entry contains the failing declaration, the checked versions and Lean's diagnostic. -When the assigned proof is still open, save the sources and call `submit_helpers` with `summary` and the standalone declarations you want to share. Supply the same declaration fields as `submit`. Include the current `objectiveRevision` after an amendment in host-tools mode. The host also checks any same-file helper dependencies and rejects any helper that depends on an unfinished original goal. Return after the call so the host can verify the saved sources independently. The host publishes checked signatures and brings the helpers into peer worktrees before their next turns. Lead can resume the producer's same assignment with its unfinished proof and notes. +When the assigned proof is still open, save the sources and call `submit` with `helpersOnly: true`, `summary` and only the standalone declarations you want to share. Include the current `objectiveRevision` after an amendment in host-tools mode. The host also checks any same-file helper dependencies and rejects any helper that depends on an unfinished original goal. Return after the call so the host can verify the saved sources independently. The host publishes checked signatures and brings the helpers into peer worktrees before their next turns. Lead can resume the producer's same assignment with its unfinished proof and notes. -In either transport, a child submitting Lean work supplies 1–32 declarations, each with `file`, fully qualified `name` and complete closed `type`; optional `description` and explicit `premises` preserve its interface. Native submit omits `objectiveRevision`: the host binds the current member and task. Historical host-tools require the current `objectiveRevision` after an amendment. List every changed declaration in the delivery. Frozen original declarations keep their names, statements, hypotheses and permitted source structure. New independent helper declarations are allowed inside editable owned Lean files; keeping original proof edits within their permitted bodies does not forbid these additions. Helpers cannot depend on unfinished original proofs or new axioms. Scratch experiments remain under the documented scratch paths; put transferable helper declarations in an editable owned file before nomination. Save sources and research notes, call `submit`, then return. Its `pending-writer-stop` response records the request; it does not assert that checking passed. The host confirms shutdown, freezes actual source bytes and checks the submitted declarations before publishing a delivery ID. Read failures from the task/event feedback and correct them through a later assignment. A deterministic source-policy failure preserves the invalid draft and clears that rejected nomination so the same member can repair it; invalid source bytes do not create a checked commit or research artifact. If the host identifies a file outside ownership, repair it in your own worktree and nominate only permitted source paths. Historical pending infrastructure checks retain their separate retry path. +In either transport, a child submitting Lean work supplies 1–32 declarations, each with `file`, fully qualified `name` and complete closed `type`; optional `description` and explicit `premises` preserve its interface. Native submit omits `objectiveRevision`: the host binds the current member and task. Historical host-tools require the current `objectiveRevision` after an amendment. For a completed assignment, list every changed declaration in the delivery. Frozen original declarations keep their names, statements, hypotheses and permitted source structure. New independent helper declarations are allowed inside editable owned Lean files; keeping original proof edits within their permitted bodies does not forbid these additions. Helpers cannot depend on unfinished original proofs or new axioms. Scratch experiments remain under the documented scratch paths; put transferable helper declarations in an editable owned file before nomination. Save sources and research notes, call `submit`, then return. Its `pending-writer-stop` response records the request; it does not assert that checking passed. The host confirms shutdown, freezes actual source bytes and checks the submitted declarations before publishing a delivery ID. Read failures from the task/event feedback and correct them through a later assignment. A deterministic source-policy failure preserves the invalid draft and clears that rejected nomination so the same member can repair it; invalid source bytes do not create a checked commit or research artifact. If the host identifies a file outside ownership, repair it in your own worktree and nominate only permitted source paths. Historical pending infrastructure checks retain their separate retry path. Draft sources from a deferred or rejected delivery remain part of the next submission. List their changed declarations as well as the new corrections; only a successful delivery advances this source baseline. A stopped child may receive a checked peer adoption while retaining its own unfinished draft. The host preserves that draft and its delivery baseline, rechecks the integration and reports conflicts. Later submissions still list all of the child's own unpublished changes; adopted peer declarations are already tracked by the host and need not be manually resubmitted as new work. diff --git a/skills/theoremos-research/references/team-roles.md b/skills/theoremos-research/references/team-roles.md index aba67778..9990c3d3 100644 --- a/skills/theoremos-research/references/team-roles.md +++ b/skills/theoremos-research/references/team-roles.md @@ -34,7 +34,7 @@ Lead chooses profiles for concrete gaps in the current shared proof effort; no p Select domain expertise for the actual missing knowledge and a work responsibility for the needed result: an algebraic-number-theory expert can act as Prover, or a graph-theory expert as Reviewer. A broad subject match alone does not justify extra profiles; a concrete Lean type or tactic failure may instead need a Library Scout or Lean Debugger. The domain profile supplies mathematical knowledge; the work profile describes the responsibility. Members choose their proof approach from the problem. Specialized names do not require more workers or a fixed sequence of handoffs. -Names and identifiers above are task vocabulary, not tool arguments or new authority. Start the assignment's `message` with a `Profiles:` header followed by comma-separated IDs or slugs selected for that gap. A work profile alone is sufficient when no specialized domain knowledge is needed. Then give the concrete gap or exact declaration, necessary definitions and known inputs, intended consumer and first usable result. The first result can be a reduction, counterexample, exact library interface or checked helper rather than the complete original proof. In native AgentControl mode this is the native spawn/followup message; in historical host-tools mode it is `spawn.message` or `assign.message`. The host includes the selected work and domain sections from the pinned Skill in the assignment context. Do not add a `role` parameter to the tool. Lead authority belongs to the actual coordinator; professional profiles do not change source permissions, tools, budgets or acceptance. +Select profiles for the gap using the optional `Profiles:` line in the [assignment format](parallel-work.md#identity-and-assignments). A work profile alone is sufficient when no specialized domain knowledge is needed. Then give the concrete gap or exact declaration, necessary definitions and known inputs, intended consumer and first usable result. The first result can be a reduction, counterexample, exact library interface or checked helper. The host includes the selected work and domain sections from the pinned Skill in the assignment context. Lead authority belongs to the actual coordinator, and profiles do not change source permissions, tools, budgets or acceptance. A member reads the selected sections and the current assignment before working. Its agentId, workspace and thread persist when profiles change. All child profiles retain the ability to investigate and write Lean in their own permitted workspace. A researcher who finds a useful proof can submit it directly; a second proof-only assignment is unnecessary. Use [parallel-work.md](parallel-work.md) for communication, source transfer, submission and adoption. @@ -48,13 +48,13 @@ A member reads the selected sections and the current assignment before working. Own a connected proof effort that closes the frozen original targets. Divide work by the mathematical result or formal interface needed, not by agent names, tactics or coordinate systems. Keep one owner per active proof obligation, including your own work. Use specialist results as inputs to the shared proof; your own research and Lean work advances their consumer, the connecting argument or another unassigned gap. -If several goals share a measure change, algebraic construction, or comparison estimate, commission independent, small typed lemmas for that foundation first. Land and reuse them before you dispatch the large consumer proofs. Delegate exploratory computation and use the planning turn to review evidence, choose a route, and publish assignments. Give host tool tasks a `routeId`. For native assignments, use `Route: ROUTE_ID` on the first line, then the usual profile and objective. When concrete evidence refutes a route, use `retire_route` with its ID, scoped reason, and evidence references so its unfinished work stops immediately. +If several goals share a measure change, algebraic construction, or comparison estimate, commission independent, small typed lemmas for that foundation first. Land and reuse them before you dispatch the large consumer proofs. Delegate exploratory computation and use the planning turn to review evidence, choose a route, and publish assignments. Tag work by route when it helps track alternatives. When concrete evidence refutes a route, use `retire_route` with its ID, scoped reason, and evidence references so its unfinished work stops immediately. Lead and members can call `route_summary` for a compact snapshot before changing direction or reusing a result. Pass `routeId` to focus the assignments and checked deliveries, or set `includeRetired: false` to hide retired branches. The snapshot includes shared landed helper signatures. Use `history` for full task text and `inspect` for exact declarations and proof evidence. Look for useful complementary work after reading the statement and necessary definitions, before deriving the complete solution; see [start and reassess](parallel-work.md#start-and-reassess). A missing argument, library application, boundary claim or route-discriminating question is enough to assign; an exact helper type can be negotiated with the member. Avoid solving a gap merely to make it assignable. If a direct proof is already clear and no useful independent question remains, check it without filling agent slots. Reassess ownership when a failed probe, library-interface uncertainty or substantial new gap creates useful work. No opening acknowledgment or fixed sequence of collaboration decisions is required. -Start the member's message with its specialty, for example `Profiles: prover` for a checked helper, `researcher` for a missing argument or `library-scout` for a library interface. Add a domain profile when its specific knowledge helps. The host selects `lead` for you alone. A useful split might give the member one existence lemma while you show how its witness implies the original conclusion. Send the hypotheses and expected output, identify the inference you retain, and let the member choose its proof. Ask for the first usable finding, probe result or blocker as soon as it is available. Independent declarations that answer the assignment should be saved, submitted and returned for host checking before optional extensions. An investigation can instead return an advisory finding, exact interface or blocker. +A useful split might give the member one existence lemma while you show how its witness implies the original conclusion. Send the hypotheses and expected output, identify the inference you retain, and let the member choose its proof. Ask for the first usable finding, probe result or blocker as soon as it is available. Independent declarations that answer the assignment should be saved, submitted and returned for host checking before optional extensions. An investigation can instead return an advisory finding, exact interface or blocker. An assignment can be as short as this. @@ -116,7 +116,7 @@ Implement the assigned auxiliary theorem with its complete requested type and re Deliver saved source, the exact declaration and full type, relevant local diagnostics, and the consumer for which it was proved. Use `submit` and return for host checking. If blocked, retain the useful draft and report the earliest substantive gap, distinguishing mathematics from library, type and tactic issues. Do not add axioms, weaken the statement or count an unchecked local proof as a checked delivery. -Report the first usable intermediate claim, probe result or blocker even when the assignment ultimately asks for a whole original target. Once independent declarations answer the assignment, message Lead and enter the submission and handoff path. Unfinished original targets do not require keeping a useful helper private. Arrange further work with Lead before expanding into another member's responsibility. +Report the first usable intermediate claim, probe result or blocker even when the assignment ultimately asks for a whole original target. Once independent declarations answer the assignment, submit them and return for host checking. Unfinished original targets do not require keeping a useful helper private. Arrange further work with Lead before expanding into another member's responsibility. ### Lean Engineer — close the original target diff --git a/src/solver/agentTeam.ts b/src/solver/agentTeam.ts index c7ca5469..03c39195 100644 --- a/src/solver/agentTeam.ts +++ b/src/solver/agentTeam.ts @@ -35,7 +35,7 @@ import { agentTeamProfileSelection, resolveNewMemberProfiles, resolveAgentTeamPr import { writeWorkerProject } from './workerProject'; import { agentTeamRequestSchema as request, agentTeamToolDefinition as teamTool, agentTeamMemberOperations as memberOperations, agentTeamArgumentFeedback, agentTeamMessageRouteFeedback, - agentTeamOperationAllowed } from './agentTeamTool'; + agentTeamOperationAllowed, legacyHelperSubmissionSchema } from './agentTeamTool'; import type { ModelRequestGate } from '../runtime/modelRequest'; import { LeanEnvironmentHealthCheckError } from '../runtime/leanHealthCheck'; import { prepareAgentTeamWorkspace } from './agentTeamWorkspace'; @@ -251,9 +251,14 @@ export class AgentResearchTeam { return { definitions: [definition], call: async (name, args, context) => { context.signal.throwIfAborted(); if (name !== definition.name) throw new Error('math_team_tool_unknown'); - const parsed = request.safeParse(args); + const parsed = args && typeof args === 'object' && 'operation' in args && args.operation === 'submit_helpers' + ? legacyHelperSubmissionSchema.safeParse(args) + : request.safeParse(args); if (!parsed.success) return agentTeamArgumentFeedback(actor, this.budgetControlsEnabled, args, parsed.error, transport); - const operation = parsed.data; + const received = parsed.data; + const operation = received.operation === 'submit_helpers' + ? { ...received, operation: 'submit' as const, helpersOnly: true } + : received; if (this.nativeAgentControlEnabled && !agentTeamOperationAllowed(actor, this.budgetControlsEnabled, transport, operation.operation)) return { ok: false, error: 'math_team_native_operation_required', hint: 'Use an advertised mathematical host operation. Native collaboration tools manage this run\'s agent transport.' }; @@ -267,7 +272,7 @@ export class AgentResearchTeam { } if (operation.operation === 'route_summary') return agentTeamRouteSummary(this.archive, operation); const key = canonicalMathJson([actor, context.threadId, context.turnId, context.callId]); - const digest = mathDigest(canonicalMathJson(operation)); + const digest = mathDigest(canonicalMathJson(received)); // Serializing mutations also prevents concurrent spawn/adoption calls from racing capacity or source checks. const apply = this.serial.then(async () => { context.signal.throwIfAborted(); @@ -819,8 +824,7 @@ export class AgentResearchTeam { artifacts: delivery.artifacts.map(artifact => ({ id: artifact.id, declaration: artifact.declaration, proof: artifact.proof })), originalProblemAcceptance: 'not-assessed' }; } - case 'submit': - case 'submit_helpers': { + case 'submit': { if (actor === 'lead') throw new Error('math_team_child_submission_required'); const worker = this.worker(actor), task = worker.tasks.find(item => item.status === 'running'); if (!task || task.cancelRequested || task.pauseRequested || !this.live.has(actor)) throw new Error('math_team_task_not_running'); @@ -835,7 +839,7 @@ export class AgentResearchTeam { ownedFiles: this.input.state.problem.ownedFiles, hint: 'Declaration file paths are relative to the Lean project. Use an exact owned file path; ' + 'put helpers in an editable owned Lean file or keep exploratory files under .scratch. No nomination was saved; correct the declarations and submit again.' }; - if (operation.operation === 'submit_helpers') { + if (operation.helpersOnly) { task.helperSubmission = operation.declarations; task.summary = operation.summary; task.pauseRequested = { at: Date.now(), kind: 'handoff', reason: 'Standalone helper handoff. The assignment remains open.' }; @@ -1063,7 +1067,7 @@ export class AgentResearchTeam { { workerId: worker.id, taskId: task.id, turnId, completedCompactions, graceMs: sliceSettings.graceMs }); const active = entry.session; void active?.notify?.( - 'Use theoremos_team submit_helpers for standalone helpers. Write fewer than 20 lines in worktree-root RESEARCH.md covering what is established, the exact obstruction, and the next route or smaller obligation. Save your files and return after the current request and tools settle.', + 'Use theoremos_team submit with helpersOnly:true for standalone helpers. Write fewer than 20 lines in worktree-root RESEARCH.md covering what is established, the exact obstruction, and the next route or smaller obligation. Save your files and return after the current request and tools settle.', active.advisoryNotifications === 'native-history' ? { mode: 'advisory' } : { waitForRequest: true }).catch(() => {}); }, interrupt: () => { @@ -1385,7 +1389,7 @@ export class AgentResearchTeam { const ready = delivery.declarations.slice(0, 8).map(item => item.name).join(', '); const more = delivery.declarations.length - 8; const checked = 'Lean checked ' + ready + (more > 0 ? ' and ' + more + ' more' : '') + - '. Use inspect with this deliveryId for exact types and evidence, then adopt into the workspace that needs the declarations.'; + '. Use this deliveryId to adopt into the workspace that needs the declarations. Inspect it for exact types or evidence as needed.'; this.event(worker.id, 'lead', 'delivery', checked + (task.summary ? '\n' + task.summary : ''), { taskId: task.id, deliveryId: delivery.id, researchArtifactId: task.researchArtifactId }); } catch (error) { diff --git a/src/solver/agentTeamContext.ts b/src/solver/agentTeamContext.ts index 7df0831f..a6b75bf0 100644 --- a/src/solver/agentTeamContext.ts +++ b/src/solver/agentTeamContext.ts @@ -11,7 +11,7 @@ export function agentTeamInstructions(role: AgentTeamRole, maxAgents: number, if (transport === 'native-agent-control') return nativeAgentTeamInstructions(role, maxAgents); const shared = 'Read the pinned references/parallel-work.md for the theoremos_team interface and collaboration methods. ' + 'Select domain knowledge for the specific missing concept from references/domain-experts.md and work responsibilities from references/team-roles.md. ' + - 'Lead starts an assignment with Profiles: followed by comma-separated IDs or slugs selected for its gap; a work profile alone is valid. ' + + 'To select a member profile, start the assignment with an optional Profiles: line of comma-separated IDs or slugs. ' + 'The host includes selected profiles and locators for collected reading from the pinned Skill; read relevant material on demand and clarify unresolved expertise. ' + 'Profiles guide the work without changing tools, source permissions or proof acceptance. ' + 'The published team research summary and fixed-commit research artifacts are advisory; use inspect-research to read an artifact. ' + @@ -23,7 +23,6 @@ export function agentTeamInstructions(role: AgentTeamRole, maxAgents: number, `At most ${maxAgents} agents including you may be available. ` + 'Use the injected Lead profile from the pinned Skill for delegation, task ownership and integration decisions. ' + 'Team updates enter your ongoing native conversation after the current response and tools. Poll the durable inbox for complete addressed messages. ' + - 'Coordinate and publish are optional compatibility operations for saved decision notes and shared research summaries; they do not gate research, tools or turn scheduling. ' + 'Use cancel to withdraw or replace an individual assignment. Tag route-specific work with routeId and use retire_route with the obstruction and evidence refs to stop the entire branch. ' + 'Use amend to change a current task objective or responsibility while retaining its task ID, draft and history; message alone does not amend it. ' + 'Mark workKind when the distinction matters: independent-reconstruction, assembly, review, research or proof. ' + @@ -31,11 +30,11 @@ export function agentTeamInstructions(role: AgentTeamRole, maxAgents: number, '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. ' + + 'Adopt a checked delivery when its interface fits. Use inspect for exact declarations and evidence when needed. ' + '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; ' + 'after confirmed writer shutdown it rechecks and integrates the delivery, then continues your saved thread. ' + - 'When all original proofs are saved, a successful diagnostic can hand them off automatically. You can also call finish with summary to request independent host checking if a diagnostic could not start; save first, then return. ' + shared + '\n'; + 'Save all original proofs and return for independent host checking. Use finish to request early handoff. ' + shared + '\n'; return `You are a mathematical researcher and Lean proof writer; your agentId is ${JSON.stringify(role.id)}, and your coordinator is lead. ` + 'Carry out the current Lead assignment; the frozen original problem supplies its background and constraints. ' + 'Use the selected professional knowledge and choose your methods independently within that assignment. A requested specialization is a task focus and can change on a later assignment. ' + @@ -44,8 +43,7 @@ export function agentTeamInstructions(role: AgentTeamRole, maxAgents: number, 'For message, agentId is the recipient: use agentId:"lead" to report to Lead, or the peer ID to contact a peer. The host binds your sender identity; self-addressed messages are rejected. ' + 'Message Lead at the first usable result, local probe or blocker, including the exact claim, assumptions and available evidence; a whole-target assignment does not require waiting for the complete proof to report. ' + 'Use progress for a useful finding, probe result, blocker or route change. Give the exact result and next step; optional knowledgeUses names a supplied source anchor actually used and its concrete application. These reports remain advisory. ' + - 'For a formal delivery, save exact declarations and call submit, then return to release writing for host checking; a local check or normal return alone does not publish a team delivery. ' + - 'Use submit_helpers to share checked standalone helpers while the assigned target is unfinished. Save your draft, then return for the host to check and land the helpers. ' + + 'For a formal delivery, save exact declarations, call submit and return for host checking. Set helpersOnly:true to share standalone helpers while keeping the assignment open. ' + 'For a host tool failure, message Lead with the command and diagnostic; use a documented fallback when available and distinguish that result from host checking. ' + 'Use inspect to read peer deliveries and inspect-research for their saved findings; ask Lead to adopt useful declarations into your worktree. ' + 'When the same task needs a dependency or Lead decision, save your draft and notes, call yield with the reason, then return to release writing; Lead can resume it later. ' + @@ -69,16 +67,16 @@ function nativeAgentTeamInstructions(role: AgentTeamRole, maxAgents: number): st 'If portfolio scouting produced no report, use native spawn_agent for concrete independent gaps found in the frozen statement. ' + 'Omit model and reasoning_effort when calling spawn_agent so members inherit the frozen run configuration. ' + '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. ' + + 'For a native spawn or followup, put an optional Route: ROUTE_ID line first, then an optional Profiles: line of comma-separated IDs or slugs, then the assignment. 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. ' + 'Only Lead dispatches, interrupts and adopts; members can exchange findings directly. ' + - 'Inspect evidence before adopting into yourself or a stopped writer. Save sources and notes, request adoption and return so the host can stop writing, integrate and continue your saved thread. ' + - 'When all original proofs are saved, call finish with a summary and return for independent host checking.\n' + shared; + 'Adopt a checked delivery when its interface fits. Use inspect for exact declarations and evidence when needed. For adoption into your own workspace, save sources and notes, request adoption and return. ' + + 'Save all original proofs and return for independent host checking. Use finish to request early handoff.\n' + shared; return `You are a mathematical researcher and Lean proof writer; your workspace member ID is ${JSON.stringify(role.id)} and your coordinator is /root (lead). ` + 'Carry out the current Lead assignment; the frozen original problem supplies background and source constraints. ' + 'Use native send_message for the first usable finding, probe result or blocker without waiting for the complete proof. Include the exact claim, assumptions and available evidence. ' + - 'Tell Lead if another branch could use your lemma and confirm its Lean statement with its consumer. Use submit_helpers for standalone helpers while your current target is unfinished. ' + - 'Save exact declarations and RESEARCH.md, then call submit and return. The pending-writer-stop acknowledgment is not a checked delivery. ' + + 'Tell Lead if another branch could use your lemma and confirm its Lean statement with its consumer. ' + + 'Save exact declarations and RESEARCH.md, then call submit and return for host checking. Set helpersOnly:true to keep the assignment open and share standalone helpers. ' + 'When the same task needs a dependency or Lead decision, save the draft, call yield with a reason and return. Lead can adopt dependencies into your stopped workspace and resume this same task with native followup_task. ' + 'Only Lead dispatches and adopts. Ask Lead before expanding into another gap. Do not spawn subteams or interrupt peers.\n' + shared; } @@ -89,7 +87,7 @@ export function agentTeamWorkerDeliveryHelp(): string { 'Use the member\'s own editable paths listed by the host; the same filename in Lead\'s workspace is a separate copy. New independent helper declarations may be added inside these files while frozen original statements remain fixed; put scratch results in an editable owned file before nomination. ' + 'List every changed declaration since the assignment deliveryBaseCommit, including earlier unpublished or rejected drafts. ' + 'For a new shared def or abbrev in an existing owned file, add kind:"definition". Its checked body is reusable; prove any claimed property separately. Each declaration may include description and explicit premises. Submit accepts 1–32 declarations, including original targets you have proved. ' + - 'For standalone helpers before the assignment is finished, use submit_helpers with the same declaration fields. Nominate just the helpers and return. The host checks and lands eligible helpers, and Lead can resume the current task. ' + + 'Set helpersOnly:true to submit only standalone helpers and keep the current assignment open for resumption. ' + 'The pending-writer-stop result acknowledges the request only: stop editing and return. The host confirms writer shutdown and checks actual source before publishing a delivery ID. ' + 'Read your task feedback on the next assignment. Messages, notes and local checks remain advisory. ' + 'Save reproducible findings in RESEARCH.md before returning; after writer shutdown the host records its fixed-commit advisory artifact. ' + diff --git a/src/solver/agentTeamProfiles.ts b/src/solver/agentTeamProfiles.ts index 41ad56c6..95cb0f8d 100644 --- a/src/solver/agentTeamProfiles.ts +++ b/src/solver/agentTeamProfiles.ts @@ -101,7 +101,7 @@ export function resolveNewMemberProfiles(skill: MathAgentSkill, message: string, 'math_team_profile_unresolved: ' + (emptyHeader ? 'empty Profiles: header' : JSON.stringify(profiles.evidence.unresolved)) + '. Use only comma-separated IDs or slugs from the pinned Skill (references/team-roles.md or references/domain-experts.md)' + (cards?.length ? ' or asset: from this run\'s personal expert catalogue' : '') + '. ' + - 'For example, put "Profiles: prover" alone on the first line. Put descriptions or custom expertise in the body; the header is optional.'); + 'Put "Profiles: prover" on its own line before the assignment, after the optional Route: line in native messages. The Profiles: line is optional. Describe custom expertise in the body.'); return profiles; } diff --git a/src/solver/agentTeamTool.ts b/src/solver/agentTeamTool.ts index a43cc595..2cd4c999 100644 --- a/src/solver/agentTeamTool.ts +++ b/src/solver/agentTeamTool.ts @@ -8,10 +8,18 @@ type Json = Record; export type AgentTeamTransport = 'host-tools' | 'native-agent-control'; // Codex 0.171 drops the entire parameters object above this branch count. const MAX_CODEX_ONEOF_BRANCHES = 16; -const nativeOperations = new Set(['finish', 'history', 'inspect', 'inspect-research', 'adopt', 'yield', 'submit', 'submit_helpers', 'retire_route', 'route_summary']); +const nativeOperations = new Set(['finish', 'history', 'inspect', 'inspect-research', 'adopt', 'yield', 'submit', 'retire_route', 'route_summary']); const text = z.string().trim().min(1).max(16000); const id = z.string().regex(/^[A-Za-z0-9_-]{1,64}$/u); +const submission = z.object({ + operation: z.literal('submit'), summary: text, objectiveRevision: z.number().int().positive().optional(), + declarations: declarationSubmissionSchema.shape.declarations, helpersOnly: z.boolean().optional(), +}).strict(); +// Saved threads can still send the old operation. Keep its parsed form for the operation journal. +export const legacyHelperSubmissionSchema = submission.omit({ helpersOnly: true }) + .extend({ operation: z.literal('submit_helpers') }); + export const agentTeamRequestSchema = z.discriminatedUnion('operation', [ z.object({ operation: z.literal('spawn'), agentId: id, message: text, routeId: portfolioRouteIdSchema.optional(), workKind: agentTeamWorkKindSchema.optional(), budget: agentTeamAllowanceSchema.optional() }).strict(), z.object({ operation: z.literal('assign'), agentId: id, message: text, routeId: portfolioRouteIdSchema.optional(), workKind: agentTeamWorkKindSchema.optional(), budget: agentTeamAllowanceSchema.optional() }).strict(), @@ -40,8 +48,7 @@ export const agentTeamRequestSchema = z.discriminatedUnion('operation', [ limit: z.number().int().min(1).max(16000).optional() }).strict(), z.object({ operation: z.literal('inspect-research'), artifactId: z.string().regex(/^[a-f0-9]{64}$/u), offset: z.number().int().nonnegative().optional(), limit: z.number().int().min(1).max(16000).optional() }).strict(), - z.object({ operation: z.literal('submit'), summary: text, objectiveRevision: z.number().int().positive().optional(), declarations: declarationSubmissionSchema.shape.declarations }).strict(), - z.object({ operation: z.literal('submit_helpers'), summary: text, objectiveRevision: z.number().int().positive().optional(), declarations: declarationSubmissionSchema.shape.declarations }).strict(), + submission, z.object({ operation: z.literal('adopt'), deliveryId: z.string().regex(/^[a-f0-9]{64}$/u), targetId: id.optional() }).strict(), z.object({ operation: z.literal('stop'), agentId: id }).strict(), routeRetirementSchema.extend({ operation: z.literal('retire_route') }), @@ -49,7 +56,7 @@ export const agentTeamRequestSchema = z.discriminatedUnion('operation', [ includeRetired: z.boolean().optional() }).strict(), ]); -export const agentTeamMemberOperations = new Set(['message', 'poll', 'wait', 'inspect', 'inspect-research', 'history', 'yield', 'submit', 'submit_helpers', 'progress', 'route_summary']); +export const agentTeamMemberOperations = new Set(['message', 'poll', 'wait', 'inspect', 'inspect-research', 'history', 'yield', 'submit', 'progress', 'route_summary']); export function agentTeamMessageRouteFeedback(actor: string, recipient: string) { if (recipient !== actor) return; @@ -61,7 +68,7 @@ export function agentTeamMessageRouteFeedback(actor: string, recipient: string) function optionsFor(actor: string, budgetControlsEnabled: boolean, transport: AgentTeamTransport = 'host-tools') { return agentTeamRequestSchema.options.filter(option => (transport !== 'native-agent-control' || nativeOperations.has(option.shape.operation.value)) && (actor === 'lead' - ? !['submit', 'submit_helpers', 'yield', 'progress'].includes(option.shape.operation.value) && (budgetControlsEnabled || option.shape.operation.value !== 'budget') + ? !['submit', 'yield', 'progress'].includes(option.shape.operation.value) && (budgetControlsEnabled || option.shape.operation.value !== 'budget') : agentTeamMemberOperations.has(option.shape.operation.value))); } @@ -103,7 +110,9 @@ function fieldSchema(value: z.ZodTypeAny): Json { } function operationContracts(actor: string, budgetControlsEnabled: boolean, transport: AgentTeamTransport = 'host-tools') { - return optionsFor(actor, budgetControlsEnabled, transport).map(option => { + // Historical host callers can still send coordinate explicitly. + const advertised = optionsFor(actor, budgetControlsEnabled, transport).filter(option => option.shape.operation.value !== 'coordinate'); + return advertised.map(option => { const schema = fieldSchema(option); if (!budgetControlsEnabled) { delete schema.properties.budget; @@ -148,10 +157,10 @@ export function agentTeamToolDefinition(actor: string, budgetControlsEnabled: bo for (const { schema } of contracts) Object.assign(properties, schema.properties); properties.operation = { type: 'string', enum: contracts.map(item => item.operation) }; const purpose = native ? lead - ? 'Mathematical host interface for the Lead. Native collaboration tools manage agent identities, spawning, followups, messages and interruption. Inspect reads a checked delivery; it does not install its declarations. Adopt merges them into the saved consumer draft before rechecking, so that draft may already call the agreed names. Finish requests independent original-proof checking. ' + ? 'Mathematical host interface for the Lead. Native collaboration tools manage agent identities, spawning, followups, messages and interruption. Adopt rechecks a delivery in the saved consumer draft before merging. Inspect shows details on demand. Return with saved original proofs for independent checking. Finish requests early handoff. ' : 'Mathematical host interface for a proof-writing member. Native collaboration tools deliver messages. Submit exact saved declarations, then return for stopped-writer checking. Yield preserves this task and draft for native followup after dependencies are integrated. ' : lead - ? 'Lead collaboration interface. Spawn and assign queue proof writers and return immediately. Amend changes the effective objective or workKind of a queued, running or paused task, retaining its identity, draft and revision history. Coordinate records a deliberate collaboration decision and next step. Publish updates the shared advisory research summary. Inspect evidence before adoption; return after adopting into yourself so the host can stop writing and integrate. Finish hands saved original proofs to the host for independent acceptance even if local diagnostics failed to start. Stop interrupts a member. ' + ? 'Lead collaboration interface. Spawn and assign queue proof writers and return immediately. Amend changes the effective objective or workKind of a queued, running or paused task, retaining its identity, draft and revision history. Publish updates the shared advisory research summary. Inspect shows delivery details on demand. Return after requesting adoption into your workspace. Save original proofs and return for independent checking. Finish requests early handoff. Stop interrupts a member. ' : 'Proof-writing member interface. Progress records a useful finding, local probe, blocker or route change against the supplied current objectiveRevision and notifies Lead. Optional knowledgeUses names a supplied source anchor (file#heading) actually used and its concrete application; a report remains advisory. Message Lead or peers to discuss results. Submit exact declarations once they answer the assignment; include objectiveRevision after an amendment, then return for host checking. The host also checkpoints before the next model request after submit/yield. Other original goals may remain open. Yield preserves the task and draft for later resume. '; return { name: 'theoremos_team', description: purpose + (native ? 'History pages complete business task text; inspect and inspect-research read fixed evidence. agentId/targetId refer to the workspace member IDs shown in team observations; native collaboration targets use canonical paths or thread IDs. ' : @@ -164,9 +173,9 @@ export function agentTeamToolDefinition(actor: string, budgetControlsEnabled: bo (native ? 'Inspection and adoption retain peer-result provenance. ' : 'WorkKind describes the deliverable: research, proof, independent-reconstruction, review or assembly. Inspection/adoption exposure is recorded and carried with later deliveries; this records reuse, not a guarantee of mathematical independence. ') + (lead ? 'Use retire_route to record a refutation and cancel all unfinished work tagged with that route. ' + - (native ? 'For native spawn_agent or followup_task, tag the assignment with Route: ROUTE_ID on its first line. ' : + (native ? 'For native spawn_agent or followup_task, put an optional Route: ROUTE_ID line first, then an optional Profiles: line of comma-separated IDs or slugs, then the assignment. ' : 'For spawn/assign, use routeId to tag the route and select assignment profiles from the pinned Skill for the gap. ') : - 'Use submit_helpers at a milestone to nominate standalone helpers, even while the assigned proof is open. Save and return for independent checking, then resume the same assignment. The host makes accepted signatures available to peers and applies the helpers before their next turn. ' + + 'Set helpersOnly:true on submit to share standalone helpers and keep the assignment open. The host makes checked helpers available to peers before their next turn. ' + (native ? '' : 'To report to Lead use agentId: "lead"; for peer discussion use the peer ID. ') + 'Submit omits agentId because the caller and task are already bound; each declaration supplies file, name and complete closed type. For a new auxiliary def or abbrev, also set kind to "definition"; submit theorems about it as separate declarations. ') + 'Use route_summary for a compact view of route assignments, checked helpers and recent deliveries. ' + 'Supply only the fields for the selected operation:\n' + contracts.map(item => contractText(item.operation, item.schema)).join('\n'), diff --git a/src/solver/contextCheckpoint.ts b/src/solver/contextCheckpoint.ts index 16a3f6b2..5bdca2a1 100644 --- a/src/solver/contextCheckpoint.ts +++ b/src/solver/contextCheckpoint.ts @@ -3,7 +3,7 @@ import path from 'node:path'; import { mathDigest } from '../math/mathRuntimeIo'; import { assertMathCanonicalPath } from '../math/paths'; import type { SolverRunState } from './archive'; -import { MAX_RESEARCH_NOTES_BYTES } from './deliveries'; +import { appendDeliveryEvent, MAX_RESEARCH_NOTES_BYTES } from './deliveries'; type CheckpointResearch = Pick; export type ContextCheckpointRejection = { threadId: string; requestId: string; file: string; offset: number; reason: string }; @@ -20,10 +20,15 @@ export function contextCheckpointRejectionFeedback(rejection: ContextCheckpointR file: string | undefined): string | undefined { if (!rejection || !file) return; return 'Host rejected the current context checkpoint acknowledgment:\n' + JSON.stringify(rejection) + '\n' + - 'After saving the current argument and unresolved inference in RESEARCH.md, recompute notesDigest as SHA256 of its exact saved bytes. ' + - 'Append one complete corrected JSON line to ' + file + ': ' + - JSON.stringify({ kind: 'checkpoint', requestId: rejection.requestId, notesDigest: 'SHA256_OF_SAVED_RESEARCH_MD' }) + '. ' + - 'Preserve the log, append this control event last, then stop editing and return. This acknowledgment grants no proof acceptance.'; + 'Save the current argument and unresolved inference in RESEARCH.md. From the worktree root rerun checkpoint with ' + + '--log ' + file + ' --request-id ' + JSON.stringify(rejection.requestId) + ', then return.'; +} + +export function queueContextCheckpoint(worktree: string, file: string, requestId: string) { + const notesDigest = readCheckpointNotesDigest(worktree); + if (!notesDigest) throw new Error('Save your current research in a nonempty RESEARCH.md before acknowledging the checkpoint.'); + appendDeliveryEvent(worktree, file, { kind: 'checkpoint', requestId, notesDigest }); + return { status: 'queued', file }; } export function readCheckpointNotesDigest(worktree: string): string | undefined { diff --git a/src/solver/contextCompiler.ts b/src/solver/contextCompiler.ts index be995eaa..be8e7ab5 100644 --- a/src/solver/contextCompiler.ts +++ b/src/solver/contextCompiler.ts @@ -164,57 +164,21 @@ const receiptsComplete = ({ verification }: NonNullable) => present(verification.targetCommit) && verification.results.length > 0 && verification.results.every(result => result.status === 'kernel_verified' && result.targetCommit === verification.targetCommit && present(result.receiptId)); -function evidence(node: TaskRecord, environmentDigest?: string) { +function taskEvidence(problem: SolverProblem, node: TaskRecord, environmentDigest?: string) { const proof = node.integratedCheck ?? node.proof; if (!proof) return undefined; if (proof.taskDigest !== taskVersion(node.task) || (environmentDigest && proof.references && proof.references.environmentDigest !== environmentDigest) || (proof.passed && !receiptsComplete(proof))) return stale(`evidence:${node.task.id}`); return { evidence: 'recorded-not-replayed', passed: proof.passed, commit: proof.commit, + path: node.task.proofPath && sourcePath(problem, node.task.proofPath), sourceDigest: proof.sourceDigest, taskDigest: proof.taskDigest, conditions: proof.conditions ?? [], verification: { status: proof.verification.status, targetCommit: proof.verification.targetCommit, receipts: proof.verification.results.map(result => ({ receiptId: result.receiptId, status: result.status, targetCommit: result.targetCommit })) }, references: proof.references && { sourceCommit: proof.references.sourceCommit, environmentDigest: proof.references.environmentDigest, contextDigest: proof.references.contextDigest, - root: proof.references.root, inputs: proof.references.inputs, tasks: proof.references.tasks, - statement: proof.references.statement, proof: proof.references.proof }, imports: proof.imports }; -} - -type EvidenceReferences = NonNullable>['references']>; -type EvidenceReferenceEntry = EvidenceReferences['inputs'][number] | EvidenceReferences['proof'][number] | - NonNullable[number]; - -/** First-seen index of each distinct key. */ -function interner(key: (value: T) => string) { - const values: T[] = [], indices = new Map(); - return { values, index: (value: T) => { - const id = key(value), previous = indices.get(id); - if (previous !== undefined) return previous; - indices.set(id, values.length); values.push(value); return values.length - 1; - } }; -} - -/** Intern exact metadata only; each proof retains its own source and verifier identities. */ -function evidenceReferenceDictionary() { - const { values: entries, index } = interner(canonicalMathJson); - const { values: digests, index: digestIndex } = interner(digest => digest); - return { entries, digests, encode: (record: ReturnType) => record?.references ? { - ...record, references: { ...record.references, - environmentDigest: digestIndex(record.references.environmentDigest), - contextDigest: digestIndex(record.references.contextDigest), - inputs: record.references.inputs.map(index), proof: record.references.proof.map(index), tasks: record.references.tasks?.map(index), - statement: record.references.statement.map(index) }, - } : record }; -} - -/** Null marks only exact field equality; absent or distinct receipt targets stay distinct. */ -function sharedEvidence(record: ReturnType) { - return record && { ...record, taskDigest: null, verification: { ...record.verification, - receipts: record.verification.receipts.map(receipt => ({ ...receipt, - targetCommit: receipt.targetCommit !== undefined && receipt.targetCommit === record.verification.targetCommit - ? null : receipt.targetCommit })), - } }; + root: proof.references.root, tasks: proof.references.tasks }, imports: proof.imports }; } function closedLeadHelper(node: TaskRecord): boolean { @@ -267,7 +231,7 @@ function requiredTasks(input: TaskContextInput, omitted: ContextManifest['omitte // A typed interface must be supplied exactly; advisory tasks have no admitted proposition. if (['lemma', 'goal'].includes(node.task.kind) && !present(frozenHeader(input.problem, node))) return missing(`interface:${id}`); - evidence(node, input.environmentDigest); + taskEvidence(input.problem, node, input.environmentDigest); required.add(id); const proof = node.integratedCheck ?? node.proof; for (const condition of proof?.conditions ?? []) { @@ -341,7 +305,7 @@ function compactTaskReference(node: TaskRecord) { } function checkedHelperReference(input: TaskContextInput, node: TaskRecord, compact?: boolean) { - const proof = evidence(node, input.environmentDigest)!; + const proof = taskEvidence(input.problem, node, input.environmentDigest)!; return { ...(compact ? compactTaskReference(node) : taskRecordReference(node)), theoremName: node.task.theoremName, sharing: node.task.sharing ?? 'problem', source: { commit: proof.commit, path: sourcePath(input.problem, node.task.proofPath!), sourceDigest: proof.sourceDigest }, @@ -402,11 +366,6 @@ function frozenDeclarationOrder(input: TaskContextInput) { })); } -function proofSources(problem: SolverProblem, node: TaskRecord) { - const proof = node.integratedCheck ?? node.proof; - return proof && { path: node.task.proofPath && sourcePath(problem, node.task.proofPath), evidenceFrom: 'evidence' }; -} - const LEAD_RESEARCH_INPUTS = 8, LEAD_RESEARCH_PROPOSALS = 8, LEAD_INLINE_FINDING_BYTES = 2 * 1024; /** Current research deliveries the Lead must review: unadopted lemma proposals, refutations and decision requests. */ @@ -552,6 +511,25 @@ function optionalDeliveries(input: TaskContextInput, required: ReadonlySet + record.taskId === action.task.id && record.status === 'pending')) { + sections.push({ id: 'next-check-response', kind: 'assignment', + text: 'Publish the assigned result with research-observe. In the finding include checkOutcome:{checkId:"HOST_CHECK_ID",conclusion:"supporting"|"refuted"|"inconclusive",summary:"scoped result",evidenceRefs:["retained evidence"]}. Use the current check ID in COOPERATION.json.nextChecks. Unknown remains inconclusive.' }); + } + const guidanceIds = cooperation.humanGuidance?.filter(record => record.status === 'delivered' && !record.decision) + .map(record => record.id); + if (guidanceIds?.length && (action?.kind === 'lead' || action?.kind === 'task' || action?.kind === 'assemble' || action?.kind === 'review')) { + sections.push({ id: 'human-guidance-response', kind: 'assignment', + text: 'Unanswered human guidance is in COOPERATION.json.humanGuidance under these IDs: ' + JSON.stringify(guidanceIds) + '\n' + + 'Include guidanceDecisions:[{guidanceId:"ID",status:"accepted"|"declined"|"needs-info",reason:"specific reason"}] ' + + 'in your normal JSON delivery or final response. Use the current plan if the decision calls for a revision.' }); + } + return sections; +} + /** Compile a task's mathematical interface before dispatch. A budget can omit hints, never hypotheses. */ export function compileTaskContext(input: TaskContextInput): { message: string; manifest: ContextManifest } { const { problem, action } = input; @@ -577,14 +555,12 @@ export function compileTaskContext(input: TaskContextInput): { message: string; if (['lemma', 'goal'].includes(consumer.task.kind) && !present(frozenHeader(problem, consumer))) return missing(`interface:${consumer.task.id}`); } - const references = evidenceReferenceDictionary(); const graph = tasks.map(node => ({ ...leadTaskInterface(node, action, omitted), taskDigest: taskVersion(node.task), status: node.task.status ?? 'active', executionStatus: node.status, attempts: node.attempts, groupId: taskGroup(node.task), producer: node.assignment?.workerId, sharing: node.task.sharing ?? 'problem', - integratedCommit: node.integratedCheck ? null : undefined, checkedSourceDigest: node.integratedCheck ? null : undefined, ...(node.task.kind === 'goal' ? { exactFrozenHeader: frozenHeader(problem, node) } : {}), - evidence: references.encode(sharedEvidence(evidence(node, input.environmentDigest))), source: proofSources(problem, node) })); + evidence: taskEvidence(problem, node, input.environmentDigest) })); const mandatory: ContextSection[] = input.taskSwitch ? [] : [ originalProblemSection(input), section('original-assumptions', 'problem', 'Frozen assumptions and problem identity:', { problemReceiptDigest: problem.receiptDigest, @@ -617,6 +593,7 @@ export function compileTaskContext(input: TaskContextInput): { message: string; text: mathematicalGapContextText(input.cooperation.mathematicalGaps) }); const nextChecks = nextCheckContextText(input.cooperation.nextChecks ?? [], action?.kind === 'task' ? action.task.id : undefined); if (nextChecks) mandatory.push({ id: 'next-checks', kind: 'finding', text: nextChecks }); + mandatory.push(...cooperativeResponseSections(input.cooperation, action)); const progressChecks = action?.kind === 'task' ? goalProgressTaskContext(input.cooperation.goalProgress, action.task) : ''; if (progressChecks) mandatory.push({ id: 'goal-review-next-checks', kind: 'assignment', text: progressChecks }); if (action?.kind === 'lead') { @@ -686,31 +663,9 @@ export function compileTaskContext(input: TaskContextInput): { message: string; const visibleGroups = new Set(tasks.map(node => taskGroup(node.task))); mandatory.push(section('groups', 'groups', 'Route groups and budgets:', input.cooperation.groups?.filter(route => action?.kind !== 'task' || visibleGroups.has(route.group.id)) ?? [])); - if (references.entries.length || references.digests.length) mandatory.push(section('evidence-reference-dictionary', 'sources', - 'Complete evidence reference dictionary (mandatory, recorded-not-replayed):', { - encoding: 'evidence-reference-indices-v3', projectRelative: problem.projectRelative.replaceAll('\\', '/'), - expansion: 'Each numeric element in a task evidence.references.inputs, proof, statement or tasks array indexes entries below. ' + - 'Expand every index in its original array order. A task source.inputsFrom names its evidence.references.inputs; ' + - 'each expanded input retains all fields and uses that task evidence.references.sourceCommit as commit and path.posix.join(projectRelative, input.file) as path. ' + - 'Source commits, verifier target commits and evidence remain distinct. Indexing grants no proof acceptance.', - entries: references.entries, - digestExpansion: 'Each numeric task evidence.references.environmentDigest or contextDigest indexes digests below. ' + - 'Replace that number with the exact original digest string. Digest sharing changes representation only; ' + - 'retain each source commit, verifier target commit, condition and reference inventory separately.', - digests: references.digests, - })); - if (graph.some(node => node.source)) mandatory.push(section('proof-source-reference-encoding', 'sources', - 'Complete proof source reference encoding (mandatory, recorded-not-replayed):', { - encoding: 'proof-source-evidence-v2', - expansion: 'A task row.source with evidenceFrom="evidence" expands to {commit: row.evidence.commit, path: row.source.path, ' + - 'sourceDigest: row.evidence.sourceDigest}. If row.evidence.references exists, add inputsFrom="evidence.references.inputs"; ' + - 'otherwise omit inputsFrom. Preserve the actual source path and all values exactly. The source commit is row.evidence.commit, ' + - 'distinct from row.evidence.verification.targetCommit and row.evidence.references.sourceCommit. ' + - 'This encoding shares metadata only and grants no proof acceptance.', - fieldExpansion: 'A null row.evidence.taskDigest expands to row.taskDigest. A null row.integratedCommit expands to row.evidence.commit; ' + - 'a null row.checkedSourceDigest expands to row.evidence.sourceDigest. A null receipt.targetCommit expands to its enclosing ' + - 'row.evidence.verification.targetCommit. Only null has this meaning; absent fields remain absent, and every distinct explicit value is retained.', - })); + if (graph.some(node => node.evidence)) mandatory.push({ id: 'proof-evidence-location', kind: 'sources', + text: 'For full proof evidence, find the matching task ID in worktree-root COOPERATION.json tasks. Read integratedCheck (or proof if absent) matching the task digest, commit and source digest shown above. ' + + 'Use the displayed commit and path to read frozen Lean source. Missing or changed records grant no proof acceptance.' }); } if (!input.taskSwitch) mandatory.push(section('declaration-order', 'sources', 'Frozen declaration order by file:', frozenDeclarationOrder(input)), section('original-targets', 'problem', 'Original targets:', problem.targets)); @@ -743,6 +698,16 @@ export function compileTaskContext(input: TaskContextInput): { message: string; const rank = scopeRank(active, required); const deferredIds = new Set(deferred.map(node => node.task.id)); const optional: ContextSection[] = []; + if (active) { + const inputs = new Set([active.id, ...active.dependsOn, ...(action?.kind === 'task' + ? (action.assignment.dependencies ?? []).map(dependency => dependency.taskId) : [])]); + for (const node of tasks) { + if (!inputs.has(node.task.id)) continue; + const references = (node.integratedCheck ?? node.proof)?.references; + if (references) optional.push({ ...section(`proof-references:${node.task.id}`, 'sources', + `Lean references for ${node.task.id}:`, references), priority: 0 }); + } + } if (repeatedAttempts.length > 1) optional.push({ ...section('repeated-attempt-history', 'feedback', 'Earlier related failed attempts (advisory; not permission to reuse verification):', repeatedAttempts.slice(1).map(attemptHint)), priority: 0 }); diff --git a/src/solver/cooperation.ts b/src/solver/cooperation.ts index affe612c..61022438 100644 --- a/src/solver/cooperation.ts +++ b/src/solver/cooperation.ts @@ -14,7 +14,7 @@ import { CAPACITY_EXPLORATION_FOCUSES, capacityExplorationInput, createCapacityE TIMED_EXPLORATION_UNANSWERED_WAKES, timedExplorationTargets } from './capacityExploration'; import { hasFreshSolverCheck, proofReceiptsMatch, type ProofCheck } from './modules/evidence'; import { originalGoalTaskFocus, readyResearchTasks, researchCanAdvance, routeAllowsTask, taskCanStart, taskDependenciesReady, selectedTaskRoute, runningTaskDependencies } from './modules/search'; -import { deliveryDetails, reviewVerdict, readMathResponse as block } from './deliveries'; +import { deliveryDetails, hasPlanResponse, reviewVerdict, readMathResponse as block } from './deliveries'; import { checkTaskProof, ownedSourceDigest, taskChanges } from './cooperativeProof'; import { assertStatementSnapshot, isStatementAction, resetStatementReview } from './statementReview'; import { captureProofReferences } from './proofReferences'; @@ -23,6 +23,7 @@ import { attributeTaskReferences } from './taskReferenceAttribution'; import { taskConsumerProjection } from './taskConsumers'; import { parallelQuestions } from './taskQuestions'; import { contextCheckpointRejection } from './contextCheckpoint'; +import { assignmentDeliveryReceipts } from './deliveryReceipts'; import { leadResearchInputs } from './contextCompiler'; import { deliverHumanGuidance, readHumanGuidance } from './humanGuidance'; import { mathematicalGaps, mathematicalGapVisible } from './mathematicalGaps'; @@ -33,11 +34,11 @@ import { TACTIC_BATTERY_TIMEOUT_MS } from './tacticBattery'; import { LIBRARY_APPLICATION_TIMEOUT_MS } from './libraryApplication'; import { knowledgeReferenceCoverage } from './knowledgeUsage'; import { taskTypePreflightEnvironmentIdentity, typeDiagnosticExcerpt, type TaskTypePreflight } from './taskTypePreflight'; -import { assignmentDeliveryFile, isDefinitionTask, isFeasibilityReview, isFinalCandidateReview, taskGroup, type CooperativeTask, type CooperativeAction, type RouteRecord, type TaskAssignment, type TaskRecord } from './tasks'; +import { assignmentDeliveryFile, isActiveFinalCandidateReview, isDefinitionTask, isFeasibilityReview, isFinalCandidateReview, taskGroup, type CooperativeTask, type CooperativeAction, type RouteRecord, type TaskAssignment, type TaskRecord } from './tasks'; import { consumeLeadWakes, dropLeadWakes, LEAD_MAX_BACKOFF, leadWakePending, settleLeadWakes } from './leadWakes'; import { idlePeerEpisode, idlePeersAwaitingLead, IDLE_PEER_WAKE_MS, leadInbox, leadInboxBasis, NO_WORK_STAGES, type LeadInboxBasis } from './leadInbox'; import { restoreResidue } from './stateInvariants'; -import { digest, directDeliveryRejections, isTaskSourceRepairFeedback, leadPlanPublicationTarget, LEAD_PLAN_REPAIR_INSTRUCTION, +import { digest, directDeliveryRejections, isTaskSourceRepairFeedback, LEAD_PLAN_REPAIR_INSTRUCTION, rejectionCode, CooperationState, TaskVersions, DispatchBudget, RETRY_DISPATCH, DispatchResult, bounded } from './cooperationShared'; import { CooperationInputs } from './cooperationInputs'; import { ResearchAdmissionError } from './researchAdmission'; @@ -264,10 +265,9 @@ export class CooperativeResearch extends CooperationInputs { return changed; } /** A live publication never authorizes a superseded dispatch or changed decisions. */ - planSnapshot(action: CooperativeAction) { - return this.current(action) ? this.publishedPlans.get(action)?.plan : undefined; + hasLeadPublication(action: CooperativeAction) { + return this.current(action) && this.leadPublication(action) !== undefined; } - initialPlanSnapshot(action: CooperativeAction) { return this.planSnapshot(action); } start() { this.timer = setInterval(() => { void this.humanGuidanceCheckpoint(); void this.inputs().catch(error => { this.input.emit('cooperation_poll_failed', { reason: error instanceof Error ? error.message : 'unknown' }); @@ -465,6 +465,8 @@ export class CooperativeResearch extends CooperationInputs { } const head = this.archive.canonicalCommit!; if (this.canAssemble(head) && this.lastAssembly !== head) { + // Candidate selection stops the workers. Let integration publish its receipts first. + if (this.integrationQueueDepth) return this.waitForDispatch(); this.syncPlanNotes(); const seed = this.seed(worker, head); this.archive.canonicalCommit = seed; this.cancelStaleTaskTypes(); @@ -589,11 +591,12 @@ export class CooperativeResearch extends CooperationInputs { researchInputs, progressReview, nextCheckOutcomes }; } /** A read or incomplete draft cannot satisfy this dispatch's still-owed decisions. */ - leadCheckpointNeedsHandoff(action: Extract): boolean { - if (!this.current(action) || this.planSnapshot(action) || - this.archive.tasks.length && !this.leadDecisionObligations(action).any) return false; + leadCheckpointHandoff(action: Extract) { + if (!this.current(action) || this.leadPublication(action) || + this.archive.tasks.length && !this.leadDecisionObligations(action).any) return; const draft = this.inspectLeadCheckpointDraft(action); - return !draft || Boolean(draft.reason); + if (draft && !draft.reason) return; + return { reason: draft?.reason }; } /** Re-read this dispatch's still-owed decisions when its checkpoint reminder is delivered. */ leadCheckpointInstruction(action: Extract): string { @@ -611,11 +614,9 @@ export class CooperativeResearch extends CooperationInputs { outcomeDeliveryId: record.outcome?.deliveryId }))) + '.'); if (obligations.feedback) required.push('Repair the current host plan validation feedback; an unchanged saved draft does not answer it. ' + LEAD_PLAN_REPAIR_INSTRUCTION); - const target = this.publishedPlans.has(action) ? undefined : leadPlanPublicationTarget(action); - const { file, ...envelope } = target ?? {}; + const target = this.openLeadPublicationTarget(action); const revision = Boolean(this.archive.tasks.length && action.planVersion); const response = { - ...envelope, ...(revision ? { baseVersion: action.planVersion, upsert: [] } : { tasks: [''] }), ...(obligations.research ? { researchDecisions: obligations.researchInputs.map(record => ({ @@ -632,10 +633,9 @@ export class CooperativeResearch extends CooperationInputs { action: '', reason: '', })) } : {}), }; - const destination = file - ? `Publish the following complete event as a single JSON line in ${file}. Keep kind, dispatchNonce and baseVersion from the template. ` + - 'If you return using RESEARCH.md instead, save the same decision in its math-plan fence without the publication fields kind and dispatchNonce. ' - : 'Save the current decision in a math-plan fence in RESEARCH.md before returning. '; + const destination = target + ? 'Save the decision as .scratch/plan.json and run plan-apply --publish from the Lead tool help. ' + : 'Use plan-apply to save the current decision in RESEARCH.md before returning. '; const schema = revision ? 'Use upsert:[] when the task graph stays unchanged, and include the required decisions in the same object. ' : 'Include a complete tasks array and the required decisions in the same object. '; @@ -644,6 +644,9 @@ export class CooperativeResearch extends CooperationInputs { (obligations.research ? 'For research adoption add taskIds naming newly added or substantively changed tasks; ' + 'for source add sourcePaths naming changed owned Lean files. ' : '') + (obligations.progress ? 'Choose enough progress nextChecks to cover every reviewed goal. ' : '') + + (obligations.nextCheckOutcomes.some(record => record.outcome?.conclusion === 'refuted') + ? 'Continuing after a refutation requires counterEvidenceDeliveryId from a supporting host check of the same target and consumer with retained evidence. Otherwise revise the argument, dependencies or route, assign a new independent feasibility check, or stop. ' + : '') + 'Keep still-unanswered ids and pending decisions in RESEARCH.md when saving an unfinished draft; ' + 'notes alone do not answer these requirements. '; } @@ -763,7 +766,7 @@ export class CooperativeResearch extends CooperationInputs { } private peerTaskCandidates(tasks: readonly TaskRecord[], groups?: readonly RouteRecord[]) { const finalReview = this.finalReviewCommit(); - const ranked = this.input.modules.M3.ready(tasks, groups); + const ranked = this.input.modules.M3.ready(tasks, groups).filter(node => !isFinalCandidateReview(node.task)); const ready = ranked.filter(node => (!finalReview || !ordinaryAdvisoryTask(node.task)) && this.nextCheckDispatchable(node) && !this.taskDispatchBlock(node)); return { ranked, ready }; @@ -1272,6 +1275,14 @@ export class CooperativeResearch extends CooperationInputs { this.livePeers.some(worker => assessTaskResponsibility(node, worker, this.responsibility).kind === 'matches' && this.input.modules.M5.assign([node], worker, this.livePeers, this.archive.groups, this.archive.tasks, this.stoppedWorkers) === node)); } + candidateReady(check: ProofCheck): boolean { + if (check.commit !== this.archive.canonicalCommit || this.candidateSynchronizationBlocked()) return false; + const reviewRequired = this.input.state.planApproval || this.archive.review || this.archive.tasks.some(({ task }) => + task.statementReview || isActiveFinalCandidateReview(task)); + if (!reviewRequired || this.reviewed(check)) return true; + this.requireReview(check); + return false; + } reviewed(check?: ProofCheck) { const required = this.fixedStatementReviewTasks(); if (this.fixedReviewScope && !required) return false; @@ -1380,10 +1391,10 @@ export class CooperativeResearch extends CooperationInputs { planPublicationRejection: (action?.kind === 'lead' || worker?.id === this.lead.id) && this.archive.planPublicationRejection?.baseVersion === this.archive.planVersion ? this.archive.planPublicationRejection : undefined, contextCheckpointRejection: checkpointResearch ? contextCheckpointRejection(checkpointResearch) : undefined, - deliveryReceipts: this.archive.deliveryReceipts?.filter(receipt => worker && receipt.workerId === worker.id && - receipt.environmentDigest === this.input.state.environmentDigest && - (action?.kind === 'task' ? receipt.assignmentKey === assignmentDeliveryFile(action.assignment) : - visible(receipt.taskId, receipt.taskDigest))), + deliveryReceipts: worker && action?.kind === 'task' + ? assignmentDeliveryReceipts(this.archive.deliveryReceipts, action.assignment, this.input.state.environmentDigest, worker.id) + : this.archive.deliveryReceipts?.filter(receipt => receipt.workerId === worker?.id && + receipt.environmentDigest === this.input.state.environmentDigest && visible(receipt.taskId, receipt.taskDigest)), proofReadyRecords: this.archive.proofReadyRecords?.filter(receipt => (action?.kind === 'lead' || worker?.id === this.lead.id || worker && receipt.workerId === worker.id && (action?.kind !== 'task' || receipt.assignmentKey === assignmentDeliveryFile(action.assignment))) && @@ -1424,7 +1435,7 @@ export class CooperativeResearch extends CooperationInputs { const sourceChanged = ownedSourceDigest(this.input.state.problem, worker.worktree, action.seedCommit) !== ownedSourceDigest(this.input.state.problem, worker.worktree, commit); let accepted = false; - const publishedPlan = this.planSnapshot(action); + const publishedPlan = this.leadPublication(action); const previousPlanVersion = this.planVersion(); const obligations = this.leadDecisionObligations(action); const requiredDecision = obligations.any; @@ -1441,10 +1452,14 @@ export class CooperativeResearch extends CooperationInputs { changedNotes = seedNotes?.trim() !== savedNotes.trim(); } catch { /* Without a readable dispatch baseline, validate the saved response normally. */ } } - const notes = savedNotes?.trimStart() ?? ''; - const hasPlanResponse = notes.startsWith('{') || /```(?:math|json|math-[a-z-]+)\b/u.test(notes); - const hasFinalPlan = hasPlanResponse && this.publishedPlans.get(action)?.responseDigest !== this.proposedPlanDigest(); - if (schedulingDraft && (savedNotes === undefined || changedNotes && notes.trim() && !hasPlanResponse)) { + const hasPlan = hasPlanResponse(savedNotes ?? ''); + let hasFinalPlan = hasPlan; + if (publishedPlan && hasPlan && savedNotes !== undefined) { + const seedNotes = this.leadNotes(action.seedCommit); + const baseline = seedNotes.text === undefined ? seedNotes.digest : this.proposedPlanDigest(seedNotes.text); + hasFinalPlan = baseline !== this.proposedPlanDigest(savedNotes); + } + if (schedulingDraft && (savedNotes === undefined || changedNotes && savedNotes.trim() && !hasPlan)) { // A scheduled yield can save fresh mathematical notes before Lead has a decision to submit. this.pin(commit); if (requiredDecision) this.wakeLead('lead-checkpoint-unchanged'); @@ -1481,11 +1496,7 @@ export class CooperativeResearch extends CooperationInputs { const decisionProgress = Boolean(publishedPlan) || accepted && (previousPlanVersion !== this.planVersion() || obligations.research || obligations.progress || obligations.nextCheck); const savedPlan = recovering && recoveryKind === 'request-failure' && decisionProgress; - if (accepted && !recovering && action.kind === 'lead') { - const nonce = action.initialPlanNonce ?? action.planNonce; - for (const publication of [this.archive.planPublication, this.archive.initialPlanPublication]) - if (nonce && publication?.nonce === nonce) publication.finalized = true; - } + if (publishedPlan && accepted && !recovering) publishedPlan.finalized = true; if (accepted && (!recovering || decisionProgress)) this.rememberLeadDecision(action); if (recovering && recoveryKind !== 'request-failure' && action.kind === 'lead' && !action.initialPlanNonce && !decisionProgress && !this.leadDecisionObligations(action).any) { diff --git a/src/solver/cooperationCore.ts b/src/solver/cooperationCore.ts index d2091dcd..c7782b8f 100644 --- a/src/solver/cooperationCore.ts +++ b/src/solver/cooperationCore.ts @@ -11,7 +11,7 @@ import type { WorkerAccess } from './research'; import type { SolverModules } from './modules'; import { originalGoalTaskFocus, originalGoalFrontierSnapshot, plannedTaskDependencyIds, taskDependencyRecords } from './modules/search'; import { type DeliveryRecord } from './deliveries'; -import { rejectedDeliveryReceipt, deliveryReceiptFeedback, type DeliveryReceipt } from './deliveryReceipts'; +import { assignmentDeliveryReceipts, rejectedDeliveryReceipt, deliveryReceiptFeedback, type DeliveryReceipt } from './deliveryReceipts'; import { proofReadyRecord, type ProofReadyRecord } from './proofReady'; import type { ProofCheck } from './modules/evidence'; import { createTaskSourceProjector, isAttributedTaskProof, ownedSourceDigest, TaskProofCache, type TaskProof } from './cooperativeProof'; @@ -39,7 +39,7 @@ import { taskConnectionCheckCurrent } from './taskConnections'; import { TaskTypePreflightCache } from './taskTypePreflight'; import { currentCapacityExploration, plannedTaskRecords } from './capacityExploration'; import { assignmentDeliveryFile, isFeasibilityReview, markTaskAcceptance, markTaskReferences, taskGroup, taskReferenceDependencies, type CooperativeTask, type TaskRecord, type CooperativeAction } from './tasks'; -import { digest, ReviewRecord, HumanEditRecord, CooperationState, TaskVersions, RETRY_DISPATCH, bounded } from './cooperationShared'; +import { digest, ReviewRecord, HumanEditRecord, CooperationState, TaskVersions, RETRY_DISPATCH, bounded, leadPlanPublicationTarget } from './cooperationShared'; import { emptyLeadWakes, leadWakePending, reopenLeadWakes, requestLeadWake, type LeadWakeReason } from './leadWakes'; import { MAX_INVALID_TASK_TRANSITIONS, setTaskStatus, type TaskStatus, type TaskTransitionCause } from './taskLifecycle'; import { planApprovalStatus } from './planApproval'; @@ -91,7 +91,7 @@ export abstract class CooperationCore { requestReady?: () => Promise; requestAdvisoryCheckpoint?: (commit: string) => void; cancelled?: boolean }>(); private freshProofReady = new WeakMap(); protected notifications = new Set>(); - private deliveryReceiptNotifications = new Set(); + private deliveryReceiptNotifications = new WeakMap(); protected pendingPulse?: Promise>>; protected deliveryChecks = new Map>(); protected proofPublications = new Map(); /** Tasks on the routes of the currently stalled goals, recomputed with the stall itself. */ protected goalPathStallTasks: ReadonlySet = new Set(); - protected publishedPlans = new WeakMap; version: string; responseDigest: string }>(); protected checkingTaskInputs = new Map>(); protected leanSourceDigests = new Map(); protected timer?: NodeJS.Timeout; @@ -701,7 +700,7 @@ export abstract class CooperationCore { ...(worker.id === this.lead.id ? { planTool: { problem: { targets: this.input.state.problem.targets, ownedFiles: this.input.state.problem.ownedFiles, frozenFiles: this.input.state.problem.frozenFiles, declarations: this.input.state.problem.declarations }, - base: this.planPatchBase(), goalPath: scoped.goalPathReview, + base: this.planPatchBase(), goalPath: scoped.goalPathReview, publication: this.openLeadPublicationTarget(action), } satisfies PlanToolContext } : {}), ...(scoped.landedHelpers?.length ? { landedHelpers: scoped.landedHelpers } : {}), ...(scoped.retiredRoutes?.length ? { retiredRoutes: scoped.retiredRoutes } : {}), @@ -729,6 +728,7 @@ export abstract class CooperationCore { canonicalProbe: node.assignment?.canonicalProbe, actualReferences: (node.integratedCheck ?? node.proof)?.references } : {}) })), deliveries: deliveries.map(({ evidence: _evidence, researchRecord: _researchRecord, ...record }) => record), + ...(scoped.humanGuidance?.length ? { humanGuidance: scoped.humanGuidance } : {}), deliveryReceipts: scoped.deliveryReceipts ?? [], proofReadyRecords: scoped.proofReadyRecords ?? [], proofSearchRecords: search ? { [search.taskId]: search } : {}, @@ -814,7 +814,8 @@ export abstract class CooperationCore { environmentDigest: this.input.state.environmentDigest, submission, error, now: Date.now(), receipts: this.archive.deliveryReceipts }); const receipts = this.archive.deliveryReceipts ??= []; - const previous = receipts.find(item => item.id === receipt.id); + const previous = assignmentDeliveryReceipts(receipts, action.assignment, this.input.state.environmentDigest, worker.id) + .find(item => item.id === receipt.id); if (previous) return previous; receipts.push(receipt); const node = this.node(action.task.id); @@ -823,18 +824,19 @@ export abstract class CooperationCore { } protected async notifyDeliveryReceipts(worker: ResearchWorker, action: Extract) { const active = this.active?.get(worker.id); - if (!active || active.action !== action || !this.current(action)) return; - const notified = this.deliveryReceiptNotifications ??= new Set(); - for (const receipt of this.archive.deliveryReceipts ?? []) { - if (receipt.status !== 'needs-correction' || receipt.workerId !== worker.id || receipt.assignmentKey !== assignmentDeliveryFile(action.assignment) || - receipt.environmentDigest !== this.input.state.environmentDigest || notified.has(receipt.id)) continue; + if (!active || active.action !== action) return; + const current = () => this.active.get(worker.id) === active && !active.cancelled && + !this.stopping && !this.input.signal.aborted && this.current(action); + if (!current()) return; + const notified = this.deliveryReceiptNotifications ??= new WeakMap(); + for (const receipt of assignmentDeliveryReceipts(this.archive.deliveryReceipts, action.assignment, this.input.state.environmentDigest, worker.id)) { + if (receipt.status !== 'needs-correction' || notified.get(receipt) === active) continue; // Reserve this receipt while its soft notice waits, without blocking later worker deliveries. - notified.add(receipt.id); + notified.set(receipt, active); const pending = Promise.resolve().then(async () => { - if (this.active.get(worker.id) !== active || !this.current(action)) throw new Error('math_notification_assignment_changed'); - await active.notify(deliveryReceiptFeedback(receipt)); + if (current() && receipt.status === 'needs-correction') await active.notify(deliveryReceiptFeedback(receipt)); }).catch(() => { - notified.delete(receipt.id); + if (notified.get(receipt) === active) notified.delete(receipt); this.input.emit('delivery_receipt_notification_deferred', { workerId: worker.id, receiptId: receipt.id }); }); const notifications = this.notifications ??= new Set(); @@ -843,10 +845,7 @@ export abstract class CooperationCore { } protected resolveDeliveryReceipts(worker: ResearchWorker, action: Extract, replacesReceipt?: unknown, complete = false) { - const scoped = (this.archive.deliveryReceipts ?? []).filter(receipt => receipt.workerId === worker.id && - receipt.assignmentKey === assignmentDeliveryFile(action.assignment) && receipt.taskId === action.assignment.taskId && - receipt.taskDigest === action.assignment.taskDigest && receipt.seedCommit === action.assignment.seedCommit && - receipt.environmentDigest === this.input.state.environmentDigest); + const scoped = assignmentDeliveryReceipts(this.archive.deliveryReceipts, action.assignment, this.input.state.environmentDigest, worker.id); const byId = new Map(scoped.map(receipt => [receipt.id, receipt])); const replaced = new Set(); let id = typeof replacesReceipt === 'string' ? replacesReceipt : undefined; @@ -855,18 +854,15 @@ export abstract class CooperationCore { if (!receipt || receipt.status === 'superseded') break; replaced.add(id); id = receipt.replacesReceipt; } + const node = this.node(action.task.id); for (const receipt of scoped) { if (receipt.status !== 'needs-correction' || !complete && !replaced.has(receipt.id)) continue; receipt.status = 'recorded'; - const node = this.node(action.task.id); - if (node.feedback === deliveryReceiptFeedback({ ...receipt, status: 'needs-correction' })) + if (node?.feedback === deliveryReceiptFeedback({ ...receipt, status: 'needs-correction' })) node.feedback = undefined; } - const pending = this.archive.deliveryReceipts?.findLast(receipt => receipt.status === 'needs-correction' && - receipt.workerId === worker.id && receipt.assignmentKey === assignmentDeliveryFile(action.assignment) && - receipt.environmentDigest === this.input.state.environmentDigest); - const node = this.node(action.task.id); - if (pending && !node.feedback) node.feedback = deliveryReceiptFeedback(pending); + const pending = scoped.findLast(receipt => receipt.status === 'needs-correction'); + if (pending && node && !node.feedback) node.feedback = deliveryReceiptFeedback(pending); } protected receiveProofReady(worker: ResearchWorker, action: Extract, submissionId: string) { const created = proofReadyRecord({ assignment: action.assignment, workerId: worker.id, submissionId, @@ -960,6 +956,15 @@ export abstract class CooperationCore { return !node.nextCheckId || this.archive.nextChecks?.some(record => record.id === node.nextCheckId && record.status === 'pending' && currentNextCheck(record, this.archive, this.explorationIdentity)) === true; } + protected leadPublication(action: CooperativeAction) { + if (action.kind !== 'lead') return; + const nonce = action.initialPlanNonce ?? action.planNonce; + const publication = this.archive.planPublication ?? this.archive.initialPlanPublication; + return publication?.nonce === nonce ? publication : undefined; + } + protected openLeadPublicationTarget(action?: CooperativeAction) { + if (action?.kind === 'lead' && this.current(action) && !this.leadPublication(action)) return leadPlanPublicationTarget(action); + } current(action: CooperativeAction) { if (action.kind === 'assemble') return !this.failure && !this.stopping && this.liveWorkers.has(this.lead.id) && this.canAssemble(action.seedCommit); if (action.kind === 'lead' && this.assemblyYieldedLeads.has(action)) return false; @@ -974,7 +979,7 @@ export abstract class CooperationCore { digest(node.task) === action.taskDigest && this.statementReviewAllowed(node.task)); } if (action.kind === 'lead') { - const version = this.publishedPlans.get(action)?.version ?? action.planVersion; + const version = this.leadPublication(action)?.planVersion ?? action.planVersion; return version === undefined || version === this.archive.planVersion; } if (action.kind === 'review') { diff --git a/src/solver/cooperationInputs.ts b/src/solver/cooperationInputs.ts index b81761ef..943d7414 100644 --- a/src/solver/cooperationInputs.ts +++ b/src/solver/cooperationInputs.ts @@ -3,19 +3,19 @@ import path from 'node:path'; import fs from 'node:fs'; import crypto from 'node:crypto'; import { VerificationCheckpointError } from './verificationCheckpoint'; -import { canonicalMathJson, mathDigest, readMathFile } from '../math/mathRuntimeIo'; +import { canonicalMathJson, mathDigest, parseMathJson, readMathFile } from '../math/mathRuntimeIo'; import { assertMathCanonicalPath } from '../math/paths'; import { mathGitResult } from '../math/mathGit'; import { type ResearchWorker } from './modules/organization'; import { taskCanStart } from './modules/search'; -import { deliveryDetails, readDeliveryLines, readMathResponse, parseMathResponse } from './deliveries'; +import { deliveryDetails, pendingDeliveryLines, readMathResponse, parseMathResponse } from './deliveries'; import { assertSolverSources, committedSource, commitSolverProjection, git, withSolverWorktree } from './problem'; import { isStatementAction } from './statementReview'; import { captureDeliveryArtifacts } from './deliveryArtifacts'; import { bindMathematicalGap } from './mathematicalGaps'; import { assignmentDeliveryFile, isFeasibilityReview, isFinalCandidateReview, leadPlanDeliveryFile, type TaskRecord, type CooperativeAction } from './tasks'; -import { directDeliveryRejections, rejectionCode, HumanEditRecord, TaskVersions, bounded, leadPlanPublicationFeedback, parseLeadPlan, - type PlanPublicationRejection } from './cooperationShared'; +import { directDeliveryRejections, rejectionCode, HumanEditRecord, TaskVersions, bounded, leadPlanPublicationFeedback, + leadPlanPublicationTarget, parseLeadPlan, type PlanPublicationRejection } from './cooperationShared'; import { CooperationPlanning } from './cooperationPlanning'; import { ResearchAdmissionError } from './researchAdmission'; import { acceptContextCheckpoint, contextCheckpointRejection, contextCheckpointRejectionFeedback, savedContextCheckpoint } from './contextCheckpoint'; @@ -58,7 +58,6 @@ export abstract class CooperationInputs extends CooperationPlanning { } private planPublicationNotification?: PlanPublicationRejection; private leadDraftBaselines = new WeakMap(); - private leadDraftNotifications = new WeakMap(); private contextCheckpointNotifications?: WeakMap; protected syncEditChecks(nodes: ReadonlyMap, versions: TaskVersions) { for (const edit of this.archive.edits ?? []) { @@ -96,14 +95,14 @@ export abstract class CooperationInputs extends CooperationPlanning { this.schedulePlanSynchronization(); const cursors = this.archive.cursors ??= {}; const file = path.join(path.dirname(this.lead.worktree), 'edits.jsonl'); - const edits = readDeliveryLines(file, cursors.edits ?? 0); - const advance = (offset: number) => { cursors.edits = offset; this.input.save(); }; - for (const entry of edits.entries!) { + // Drain queued edits before considering an approval of the resulting plan. + for (const entry of pendingDeliveryLines(file, cursors, 'edits', () => this.input.save(), 'drain')) { this.input.signal.throwIfAborted(); let id = crypto.randomUUID(); let record: HumanEditRecord | undefined; try { - if (!entry.line?.trim()) { advance(entry.offset); continue; } + if (entry.error) throw new Error(entry.error); + if (!entry.line?.trim()) continue; let edit: any; try { edit = JSON.parse(entry.line); } catch { throw new Error('math_edit_invalid_json'); } @@ -116,7 +115,7 @@ export abstract class CooperationInputs extends CooperationPlanning { this.schedulePlanSynchronization(); this.input.emit('edit_applied', { id, planVersion: record!.planVersion, affectedTasks: record!.affectedTasks, recheck: record!.recheck }); } - advance(entry.offset); continue; + continue; } if (!record) { record = { id, status: 'received', receivedAt: Date.now(), @@ -140,17 +139,16 @@ export abstract class CooperationInputs extends CooperationPlanning { this.input.signal.throwIfAborted(); const reason = error instanceof Error ? error.message : 'math_edit_invalid'; if (record?.status === 'applied' || !(error instanceof Error) || error.name === 'AbortError' || - !/^math_(?:edit_(?:invalid(?:_json|_id)?|version_conflict)$|plan_[a-z_]+(?:$|:))/u.test(reason)) throw error; + (entry.error !== reason && !/^math_(?:edit_(?:invalid(?:_json|_id)?|version_conflict)$|plan_[a-z_]+(?:$|:))/u.test(reason))) + throw error; if (record) { record.status = 'rejected'; record.reason = reason; } else (this.archive.edits ??= []).push({ id, status: 'rejected', reason, receivedAt: Date.now() }); this.changed(); this.input.emit('edit_rejected', { id, reason }); } - advance(entry.offset); } this.readPlanApprovals(cursors); await this.readPlanDelivery(cursors); - this.notifyLeadDraftCorrection(); for (const worker of this.input.workers) { if (this.deliveryChecks.has(worker.id)) continue; const active = this.active.get(worker.id); @@ -195,68 +193,29 @@ export abstract class CooperationInputs extends CooperationPlanning { this.preparePlan(plan, action); } catch (error) { if (error instanceof Error && /^math_plan_/u.test(error.message)) - return { digest, reason: bounded(error.message, 4000) }; + return { reason: bounded(error.message, 4000) }; throw error; } - return { digest, reason: undefined }; - } - /** Saved notes are drafts: offer same-turn corrections without publishing them or changing the graph. */ - private notifyLeadDraftCorrection() { - const active = this.active.get(this.lead.id), action = active?.action; - if (!active || action?.kind !== 'lead' || this.publishedPlans.has(action)) return; - const current = () => this.active.get(this.lead.id) === active && !active.cancelled && - !this.stopping && !this.input.signal.aborted && this.current(action) && !this.publishedPlans.has(action); - const inspect = () => { - if (!current()) return; - const draft = this.inspectLeadCheckpointDraft(action); - return draft?.reason ? { digest: draft.digest, reason: draft.reason } : undefined; - }; - const correction = inspect(); - if (!correction) { this.leadDraftNotifications.delete(action); return; } - const previous = this.leadDraftNotifications.get(action); - if (previous?.digest === correction.digest && previous.reason === correction.reason) return; - this.leadDraftNotifications.set(action, correction); - const pending = Promise.resolve().then(async () => { - if (!current() || this.leadDraftNotifications.get(action) !== correction) return; - const latest = inspect(); - if (!latest || latest.digest !== correction.digest || latest.reason !== correction.reason) { - if (this.leadDraftNotifications.get(action) === correction) this.leadDraftNotifications.delete(action); - return; - } - const file = leadPlanDeliveryFile(action); - await active.notify('The complete math-plan draft saved in RESEARCH.md needs correction before publication: ' + - correction.reason + '. ' + this.leadCheckpointInstruction(action) + - 'Correct the same draft now, before returning or starting another search. Keep the mathematical decisions your own; ' + - 'this preflight has not accepted the plan or any proof. ' + (file - ? 'To publish after correction, append one complete JSON line to ' + file + ' using ' + - JSON.stringify({ kind: 'plan', dispatchNonce: action.initialPlanNonce ?? action.planNonce, baseVersion: action.planVersion }) + - ' plus the complete revision and all required decisions. Preserve the log; RESEARCH.md may retain the single corrected math-plan fence instead.' - : 'Save one complete corrected math-plan JSON fence in RESEARCH.md.')); - this.input.emit('lead_draft_correction_requested', { workerId: this.lead.id, draftDigest: correction.digest, reason: correction.reason }); - }).catch(() => { - if (this.leadDraftNotifications.get(action) === correction) this.leadDraftNotifications.delete(action); - this.input.emit('notification_deferred', { workerId: this.lead.id, reason: 'lead-draft-correction' }); - }); - this.notifications.add(pending); void pending.finally(() => this.notifications.delete(pending)); + return { reason: undefined }; } /** Human approvals queued by queuePlanApproval; each names the exact plan version it opens dispatch for. */ private readPlanApprovals(cursors: Record) { const file = planApprovalLog(path.join(path.dirname(this.lead.worktree), 'state.json')); - for (const entry of readDeliveryLines(file, cursors.planApprovals ?? 0).entries!) { + for (const entry of pendingDeliveryLines(file, cursors, 'planApprovals', () => this.input.save(), 'drain')) { this.input.signal.throwIfAborted(); + if (!entry.error && !entry.line?.trim()) continue; let parsed: PlanApprovalInput | undefined; - try { parsed = planApprovalInputSchema.parse(JSON.parse(entry.line ?? '')); } catch { parsed = undefined; } - if (entry.line?.trim()) this.applyPlanApproval(parsed); - cursors.planApprovals = entry.offset; this.input.save(); + if (entry.line) try { parsed = planApprovalInputSchema.parse(JSON.parse(entry.line)); } catch { /* Report invalid approval below. */ } + this.applyPlanApproval(parsed, entry.error); } } - private applyPlanApproval(approval: PlanApprovalInput | undefined) { + private applyPlanApproval(approval: PlanApprovalInput | undefined, readError?: string) { const record = this.archive.planApproval ??= {}; if (approval && record.approvedId === approval.id) return; const status = planApprovalStatus(this.input.state); - const reason = !approval ? 'math_plan_approval_invalid' : status === 'not-required' ? 'math_plan_approval_not_required' : + const reason = readError ?? (!approval ? 'math_plan_approval_invalid' : status === 'not-required' ? 'math_plan_approval_not_required' : status === 'approved' ? 'math_plan_approval_already_approved' : status === 'awaiting-plan' ? 'math_plan_approval_plan_unavailable' : - approval.planVersion !== this.archive.planVersion ? 'math_plan_approval_version_conflict' : undefined; + approval.planVersion !== this.archive.planVersion ? 'math_plan_approval_version_conflict' : undefined); if (!approval || reason) { const rejection = { id: approval?.id ?? crypto.randomUUID(), reason: reason!, at: Date.now(), ...(approval ? { planVersion: approval.planVersion } : {}) }; @@ -271,18 +230,17 @@ export abstract class CooperationInputs extends CooperationPlanning { private async readPlanDelivery(cursors: Record) { const active = this.active.get(this.lead.id), action = active?.action; if (!action || action.kind !== 'lead') return; - const file = leadPlanDeliveryFile(action); - if (!file) return; - const initial = Boolean(action.initialPlanNonce), nonce = action.initialPlanNonce ?? action.planNonce!; + const target = leadPlanPublicationTarget(action); + if (!target) return; + const { file, dispatchNonce: nonce, baseVersion } = target; + const initial = Boolean(action.initialPlanNonce); const code = (reason: string) => `math_${initial ? 'initial_plan' : 'plan_publication'}_${reason}`; - const key = `${this.lead.id}/${file}`, discardKey = `${key}/discardingOversized`; - const batch = readDeliveryLines(path.join(this.lead.worktree, file), cursors[key] ?? 0, - { discardingOversized: cursors[discardKey] === 1 }); + const key = `${this.lead.id}/${file}`; const research = this.input.state.workers?.find(record => record.id === this.lead.id) ?? this.input.state; const current = () => this.active.get(this.lead.id) === active && !active.cancelled && !this.stopping && !this.input.signal.aborted && this.current(action); - const open = () => current() && - (this.archive.planPublication ?? this.archive.initialPlanPublication)?.nonce !== nonce; + const open = () => current() && !this.leadPublication(action) && + !(initial && (this.archive.initialPlanPublication || this.archive.tasks.length)); let advanced = false, feedbackChanged = false; const reject = (reason: string, offset: number, checkpoint = false) => { this.input.emit(initial ? 'initial_plan_rejected' : 'plan_publication_rejected', { workerId: this.lead.id, file, reason }); @@ -292,69 +250,60 @@ export abstract class CooperationInputs extends CooperationPlanning { checkpoint.request.rejection = { file, offset, reason: bounded(reason, 4000) }; } else { if (!open()) return; - this.archive.planPublicationRejection = { nonce, file, offset, baseVersion: action.planVersion!, reason: bounded(reason, 4000) }; + this.archive.planPublicationRejection = { nonce, file, offset, baseVersion, reason: bounded(reason, 4000) }; } feedbackChanged = true; }; try { - for (const entry of batch.entries!) { + for (const entry of pendingDeliveryLines(path.join(this.lead.worktree, file), cursors, key, () => { advanced = true; })) { this.input.signal.throwIfAborted(); - if (entry.error) reject(entry.error, entry.offset); - else if (entry.line?.trim()) { - // Only a complete explicit event is parsed; RESEARCH.md remains an unpublished draft. - const eventDigest = mathDigest(entry.line); - let response: any; - try { response = JSON.parse(entry.line); } - catch { reject(code('invalid_json'), entry.offset); } - if (response !== undefined) { - try { - if (response?.kind === 'checkpoint') { - await this.input.exclusiveCheck(async () => { - if (!current()) throw new Error(code('superseded')); - acceptContextCheckpoint(research, this.lead.worktree, response); - this.input.emit('context_checkpoint_published', { workerId: this.lead.id, threadId: research.threadId, - requestId: research.contextCheckpoint?.requestId, notesDigest: research.contextCheckpoint?.publishedNotesDigest }); - this.changed(); - }); - } else { - if (!response || typeof response !== 'object' || Array.isArray(response)) - throw new Error(code('invalid') + ': expected a JSON object'); - const fields: string[] = []; - if (response.kind !== 'plan') fields.push('kind must be "plan"'); - if (typeof response.baseVersion !== 'string') fields.push('baseVersion must be the current plan version'); - if ((!initial || response.dispatchNonce !== undefined) && response.dispatchNonce !== nonce) - fields.push('dispatchNonce must match this Lead dispatch'); - if (fields.length) throw new Error(code('invalid') + ': ' + fields.join(', ')); - const details = deliveryDetails(response); - await this.input.exclusiveCheck(async () => { - const publication = this.archive.planPublication ?? this.archive.initialPlanPublication; - if (publication?.nonce === nonce && publication.eventDigest === eventDigest) return; - if (publication?.nonce === nonce || initial && (this.archive.initialPlanPublication || this.archive.tasks.length) || - this.active.get(this.lead.id)?.action !== action || !this.current(action)) - throw new Error(code('superseded')); - if (!action.planVersion || response.baseVersion !== action.planVersion || - response.baseVersion !== this.archive.planVersion) throw new Error(code('version_conflict')); - const plan = parseLeadPlan(this.input.state.problem, response, this.planPatchBase(), { goalPath: this.goalPathReview() }); - await this.acceptPlan(plan, undefined, { action, receipt: { nonce, file, - offset: entry.offset, eventDigest, baseVersion: response.baseVersion, acceptedAt: Date.now() } }); - await this.retainGuidanceDecisions(this.lead, action, response.guidanceDecisions); - this.rememberLeadDecision(action); - this.changed(); - this.input.emit(initial ? 'initial_plan_published' : 'plan_published', { ...this.archive.planPublication, - workerId: this.lead.id, summary: details.summary, taskIds: plan.tasks.map(task => task.id) }); - }); - } - } catch (error) { - this.input.signal.throwIfAborted(); - if (!(error instanceof Error) || !/^math_(?:initial_plan_|plan_|delivery_invalid)/u.test(error.message)) throw error; - reject(error.message, entry.offset, response?.kind === 'checkpoint'); - } + if (entry.error) { reject(entry.error, entry.offset); continue; } + const line = entry.line; + if (!line?.trim()) continue; + let checkpoint = false; + try { + const value = parseMathJson(line, code('invalid_json')); + if (!value || typeof value !== 'object' || Array.isArray(value)) + throw new Error(code('invalid') + ': expected a JSON object'); + const response = value as Record; + checkpoint = response.kind === 'checkpoint'; + if (checkpoint) { + await this.input.exclusiveCheck(async () => { + if (!current()) throw new Error(code('superseded')); + acceptContextCheckpoint(research, this.lead.worktree, response); + this.input.emit('context_checkpoint_published', { workerId: this.lead.id, threadId: research.threadId, + requestId: research.contextCheckpoint?.requestId, notesDigest: research.contextCheckpoint?.publishedNotesDigest }); + this.changed(); + }); + continue; } + const fields: string[] = []; + if (response.kind !== target.kind) fields.push('kind must be "plan"'); + if (typeof response.baseVersion !== 'string') fields.push('baseVersion must be the current plan version'); + if ((!initial || response.dispatchNonce !== undefined) && response.dispatchNonce !== nonce) + fields.push('dispatchNonce must match this Lead dispatch'); + if (fields.length) throw new Error(code('invalid') + ': ' + fields.join(', ')); + const eventDigest = mathDigest(line), details = deliveryDetails(response); + await this.input.exclusiveCheck(async () => { + if (this.leadPublication(action)?.eventDigest === eventDigest) return; + if (!open()) throw new Error(code('superseded')); + if (response.baseVersion !== baseVersion || baseVersion !== this.archive.planVersion) + throw new Error(code('version_conflict')); + const plan = parseLeadPlan(this.input.state.problem, response, this.planPatchBase(), { goalPath: this.goalPathReview() }); + await this.acceptPlan(plan, undefined, { action, receipt: { nonce, file, + offset: entry.offset, eventDigest, baseVersion, acceptedAt: Date.now() } }); + await this.retainGuidanceDecisions(this.lead, action, response.guidanceDecisions); + this.rememberLeadDecision(action); + this.changed(); + this.input.emit(initial ? 'initial_plan_published' : 'plan_published', { ...this.archive.planPublication, + workerId: this.lead.id, summary: details.summary, taskIds: plan.tasks.map(task => task.id) }); + }); + } catch (error) { + this.input.signal.throwIfAborted(); + if (!(error instanceof Error) || !/^math_(?:initial_plan_|plan_|delivery_invalid)/u.test(error.message)) throw error; + reject(error.message, entry.offset, checkpoint); } - cursors[key] = entry.offset; cursors[discardKey] = entry.discardingOversized ? 1 : 0; advanced = true; } - if (cursors[key] !== batch.offset || (cursors[discardKey] === 1) !== batch.discardingOversized) advanced = true; - cursors[key] = batch.offset; cursors[discardKey] = batch.discardingOversized ? 1 : 0; } finally { if (advanced) { if (feedbackChanged) this.changed(); else this.input.save(); } } const rejection = this.archive.planPublicationRejection; if (rejection && rejection.nonce === nonce && open() && this.planPublicationNotification !== rejection) { @@ -418,10 +367,7 @@ export abstract class CooperationInputs extends CooperationPlanning { try { for (const log of [assignmentDeliveryFile(action.assignment), 'DELIVERIES.jsonl']) { const scoped = log !== 'DELIVERIES.jsonl', key = scoped ? `${worker.id}/${log}` : worker.id; - const discardKey = `${key}/discardingOversized`; - const batch = readDeliveryLines(path.join(worker.worktree, log), cursors[key] ?? 0, - { discardingOversized: cursors[discardKey] === 1 }); - for (const entry of batch.entries!) { + for (const entry of pendingDeliveryLines(path.join(worker.worktree, log), cursors, key, () => { advanced = true; })) { this.input.signal.throwIfAborted(); if (entry.error) reject(entry.error, `${key}:${entry.offset}:${entry.error}`); else if (entry.line?.trim()) { @@ -437,13 +383,7 @@ export abstract class CooperationInputs extends CooperationPlanning { } } } - cursors[key] = entry.offset; - cursors[discardKey] = entry.discardingOversized ? 1 : 0; - advanced = true; } - if (cursors[key] !== batch.offset || (cursors[discardKey] === 1) !== batch.discardingOversized) advanced = true; - cursors[key] = batch.offset; - cursors[discardKey] = batch.discardingOversized ? 1 : 0; } } finally { if (advanced) { diff --git a/src/solver/cooperationPlanning.ts b/src/solver/cooperationPlanning.ts index f7f355c9..99d7690e 100644 --- a/src/solver/cooperationPlanning.ts +++ b/src/solver/cooperationPlanning.ts @@ -1,11 +1,11 @@ -import { parseCooperationPlan, isAdvisoryTask as advisory } from './tasks'; +import { parseCooperationPlan, isActiveFinalCandidateReview, isAdvisoryTask as advisory } from './tasks'; import { assertPlanTaskTypeContracts } from './taskTypeContract'; import fs from 'node:fs'; import path from 'node:path'; import { canonicalMathJson, mathDigest, readMathText } from '../math/mathRuntimeIo'; import { commitSolverSources, committedSource, git, solverProofImports, withSolverWorktree } from './problem'; import { originalGoalTaskFocus, routeAllowsTask, taskCanStart, plannedTaskDependencyIds } from './modules/search'; -import { readMathResponse as block, parseMathResponse, isPlanFence as planFence, MAX_RESEARCH_NOTES_BYTES } from './deliveries'; +import { readMathResponse as block, parseMathResponse, replacePlanInNotes, MAX_RESEARCH_NOTES_BYTES } from './deliveries'; import { applyTaskChanges, ownedSourceDigest, taskChanges } from './cooperativeProof'; import { statementSnapshot } from './statementReview'; import { proofReferencesUnchanged } from './proofReferences'; @@ -13,14 +13,14 @@ import { captureObligationSnapshot } from './obligationProgress'; import { taskConnectionCheckCurrent } from './taskConnections'; import { keepRespacedObjectives, taskGroup, taskVersion, taskProofContractVersion, taskReferenceDependencies, invalidatedTaskIds, type TaskRecord, type CooperativeAction } from './tasks'; -import { digest, HumanEditRecord, InitialPlanPublication, RETRY_DISPATCH, DispatchResult, bounded, deliveryInputFields, readCooperationPlan, +import { digest, HumanEditRecord, InitialPlanPublication, RETRY_DISPATCH, DispatchResult, deliveryInputFields, readCooperationPlan, type LeadPlan } from './cooperationShared'; import { formatPlanJson, liftNestedPlanPatch, type PlanPatchBase } from './planPatch'; import { PlanValidationError, type PlanIssue } from './planDiagnostics'; import { collapseTaskFamilies } from './taskFamilies'; import { dropLeadWakes, LEAD_MAX_BACKOFF } from './leadWakes'; import { CooperationIntegration } from './cooperationIntegration'; -import { researchRouteGroups, researchWorkerCanNode } from './modules/organization'; +import { assertPlanAssignments, researchRouteGroups } from './modules/organization'; import { currentCapacityExploration } from './capacityExploration'; import { currentNextCheck, prepareNextCheckDecisions } from './nextChecks'; import { prepareGoalProgressDecision, requireGoalProgressDecision } from './goalProgress'; @@ -67,16 +67,13 @@ export abstract class CooperationPlanning extends CooperationIntegration { const { text: source } = this.leadNotes(); // The accepted graph is already durable. Leave a large journal intact and use the live plan channel. if (source === undefined) return; - const plan = '```math\n' + formatPlanJson({ tasks: collapseTaskFamilies(this.plannedTasks().map(node => node.task)), groups: this.archive.groups?.map(route => route.group), - ...(this.archive.proofRoutes?.length ? { proofRoutes: this.archive.proofRoutes } : {}) }) + '\n```'; - // Replace the first plan fence and drop the rest, so an applied revision cannot be read again. - let replaced = false; - const synced = source.replace(/```([a-z-]+)\s*\n([\s\S]*?)\n```/gu, (fence, label: string, body: string) => { - if (!planFence(label, body)) return fence; - if (replaced) return ''; - replaced = true; return plan; - }); - fs.writeFileSync(file, replaced ? synced : plan + '\n' + bounded(source, 8000)); + const notes = replacePlanInNotes(source, formatPlanJson({ + tasks: collapseTaskFamilies(this.plannedTasks().map(node => node.task)), + groups: this.archive.groups?.map(route => route.group), + ...(this.archive.proofRoutes?.length ? { proofRoutes: this.archive.proofRoutes } : {}), + })); + if (Buffer.byteLength(notes) > MAX_RESEARCH_NOTES_BYTES) return; + if (notes !== source) fs.writeFileSync(file, notes); this.archive.planEdited = false; } /** The accepted Lead graph that a plan revision is written against; family members are rederived on parse. */ @@ -88,13 +85,13 @@ export abstract class CooperationPlanning extends CooperationIntegration { /** A dispatch's own live publication already applied its revision; the final notes may repeat it against the dispatch base. */ protected readLeadPlan(action?: CooperativeAction): LeadPlan { const base = this.planPatchBase(); - const rebased = Boolean(action?.kind === 'lead' && this.current(action) && this.publishedPlans.has(action) && - action.planVersion && action.planVersion !== base?.version); + const dispatchBase = action && this.current(action) ? this.leadPublication(action)?.baseVersion : undefined; + const rebased = dispatchBase !== undefined && dispatchBase !== base?.version; // A rebased repeat of an applied publication already answered the review it was written against. const goalPath = rebased ? undefined : this.goalPathReview(); try { return readCooperationPlan(this.input.state.problem, this.lead.worktree, base, { - acceptedBaseVersions: [...(base ? [base.version] : []), ...(rebased ? [(action as { planVersion: string }).planVersion] : [])], + acceptedBaseVersions: [...(base ? [base.version] : []), ...(rebased ? [dispatchBase] : [])], rebased, restoring: !action, goalPath }); } catch (error) { throw new InvalidLeadPlanDraft(error); } } @@ -354,18 +351,8 @@ export abstract class CooperationPlanning extends CooperationIntegration { const progressDecision = requiredProgressDecision ? prepareGoalProgressDecision(requiredProgressDecision, this.archive.goalProgress, plan, this.archive.nextChecks, this.archive.tasks) : undefined; - for (const task of tasks) if (task.ownerId || task.preferredOwnerId) { - const owner = this.input.workers.find(worker => worker.id === (task.ownerId ?? task.preferredOwnerId)); - const previous = this.archive.tasks.find(node => node.task.id === task.id); - const ownershipTask = previous?.capacityExploration ? { ...task, status: 'active' as const } : task; - if (!owner || !researchWorkerCanNode(owner, { ...(previous ?? { status: 'pending', attempts: 0 }), task: ownershipTask })) - throw new Error('math_plan_task_owner_unavailable'); - } - const configuredGroups = researchRouteGroups(groups, this.input.workers).map(group => { - if (group.engineerId && !this.input.workers.some(worker => worker.id === group.engineerId && worker.role === 'engineer')) - throw new Error('math_plan_group_engineer_unavailable'); - return { ...group }; - }); + assertPlanAssignments(plan, this.archive.tasks, this.input.workers); + const configuredGroups = researchRouteGroups(groups, this.input.workers); return { plan, nextCheckDecisions, researchDecisions, progressDecision, configuredGroups, shown, retirement }; } protected async acceptPlan(planInput?: LeadPlan, edit?: HumanEditRecord, @@ -377,10 +364,12 @@ export abstract class CooperationPlanning extends CooperationIntegration { const { plan, nextCheckDecisions, researchDecisions, progressDecision, configuredGroups, shown, retirement } = this.preparePlan( planInput ?? this.readLeadPlan(leadAction), decidingAction, restoringPlan); const { tasks, proofRoutes } = plan; - const seedNotes = publication ? this.leadNotes(publication.action.seedCommit) : undefined; - const publicationResponseDigest = seedNotes?.text !== undefined ? this.proposedPlanDigest(seedNotes.text) : seedNotes?.digest; const previousGroups = new Map(this.archive.groups?.map(record => [record.group.id, record])); const current = new Map(this.archive.tasks.map(node => [node.task.id, node])); + const previousReviewIds = this.archive.tasks.filter(({ task }) => isActiveFinalCandidateReview(task)).map(({ task }) => task.id); + const reviewIds = tasks.filter(isActiveFinalCandidateReview).map(task => task.id); + // Scheduling status does not change a task's version. A pause or resume can still change the Reviewer's questions. + const reviewScopeChanged = reviewIds.length !== previousReviewIds.length || reviewIds.some(id => !previousReviewIds.includes(id)); const invalidated = this.planInvalidation(plan); const proofChanges = this.planInvalidation(plan, true); const revalidate = new Set([...invalidated].filter(id => !proofChanges.has(id) && current.get(id)?.status === 'integrated')); @@ -416,7 +405,7 @@ export abstract class CooperationPlanning extends CooperationIntegration { this.stopRetiredRouteTasks(); } this.syncProofRoutes(); - if (invalidated.size) { this.archive.review = undefined; this.lastAssembly = undefined; } + if (invalidated.size || reviewScopeChanged) { this.archive.review = undefined; this.lastAssembly = undefined; } const retiredWork: (() => Promise)[] = []; for (const [id, active] of this.active) { if (active.action.kind === 'review' && !this.archive.review && !active.cancelled) { active.cancelled = true; void active.interrupt().catch(() => {}); } @@ -484,8 +473,6 @@ export abstract class CooperationPlanning extends CooperationIntegration { this.archive.planPublication = { ...publication.receipt, planVersion: this.archive.planVersion }; if (publication.action.kind === 'lead' && publication.action.initialPlanNonce) this.archive.initialPlanPublication = this.archive.planPublication; - this.publishedPlans.set(publication.action, { plan, version: this.archive.planVersion, - responseDigest: publicationResponseDigest! }); } // Preserve a Lead's own initial publication, but reclaim turns superseded by a newer plan. for (const active of this.active.values()) if (active.action.kind === 'lead' && !this.current(active.action) && !active.cancelled) { diff --git a/src/solver/cooperationShared.ts b/src/solver/cooperationShared.ts index c29f5cf1..80e3ab9a 100644 --- a/src/solver/cooperationShared.ts +++ b/src/solver/cooperationShared.ts @@ -180,8 +180,7 @@ export function leadPlanPublicationTarget(action: CooperativeAction | undefined) } export const LEAD_PLAN_REPAIR_INSTRUCTION = - 'Validate the candidate JSON from the Lead worktree with theorem-os plan-validate --file .scratch/plan.json. ' + - 'Use theorem-os plan-apply --file .scratch/plan.json to save a validated plan in RESEARCH.md.'; + 'Use plan-apply from the generated Lead tool help to validate and submit the corrected .scratch/plan.json.'; /** Reuse the saved diagnostic across turns while always targeting the current dispatch. */ export function leadPlanPublicationFeedback(action: CooperativeAction | undefined, @@ -189,11 +188,8 @@ export function leadPlanPublicationFeedback(action: CooperativeAction | undefine const rejection = state.planPublicationRejection, target = leadPlanPublicationTarget(action); if (!target || !rejection || rejection.baseVersion !== state.planVersion) return; return 'Host rejected a Lead publication before accepting it:\n' + JSON.stringify(rejection) + '\n' + - 'Correct the reported error and append a new complete JSON event using the current publication target: ' + - JSON.stringify(target) + '. ' + - 'Preserve the log and use the current assignment protocol; a saved rejection may come from an earlier dispatch. ' + - 'Keep kind:"plan", baseVersion and any dispatchNonce at the top level of the same event as tasks or upsert/remove; ' + - 'a bare plan patch is not a publication event. Only the first valid publication in a dispatch is accepted. This intake feedback grants no proof acceptance. ' + + 'Correct the reported error and use plan-apply --publish for the current dispatch. ' + + 'Only the first valid publication in a dispatch is accepted. ' + LEAD_PLAN_REPAIR_INSTRUCTION; } export const deliveryInputFields = (record: DeliveryRecord) => ({ diff --git a/src/solver/deliveries.ts b/src/solver/deliveries.ts index b6271ebd..6fa375ae 100644 --- a/src/solver/deliveries.ts +++ b/src/solver/deliveries.ts @@ -20,6 +20,22 @@ export const MAX_RESEARCH_NOTES_BYTES = 1_000_000; // complete finding. Allow bounded JSON escaping without rejecting existing files. export const MAX_DELIVERY_LINE_BYTES = 16_000_000; +export function appendDeliveryEvent(worktree: string, file: string, event: unknown): void { + if (!/^DELIVERIES-[a-f0-9]{64}\.jsonl$/u.test(file)) throw new Error('math_delivery_log_invalid'); + const output = path.join(worktree, file); + assertMathCanonicalPath(output); + const line = JSON.stringify(event) + '\n'; + if (Buffer.byteLength(line) > MAX_DELIVERY_LINE_BYTES) throw new Error('math_delivery_line_too_large'); + const fd = fs.openSync(output, fs.constants.O_WRONLY | fs.constants.O_APPEND | fs.constants.O_CREAT | + fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK, 0o600); + try { + const stat = fs.fstatSync(fd); + if (!stat.isFile() || stat.nlink !== 1) throw new Error('math_delivery_log_invalid'); + fs.writeFileSync(fd, line); + fs.fsyncSync(fd); + } finally { fs.closeSync(fd); } +} + /** JSON for host decisions, optional Markdown for explanations; legacy fences remain readable. */ export function readMathResponse(worktree: string, legacyFence: string, bindings: Record = {}, textField?: string): any { const file = path.join(worktree, 'RESEARCH.md'); @@ -54,8 +70,9 @@ function researchResponse(text: string, textField?: string): unknown { } const planKeys = /"(?:tasks|groups|proofRoutes|dispatchNonce|baseVersion|upsert|remove)"\s*:/u; +const noteFences = /```([a-z-]+)\s*\n([\s\S]*?)\n```/gu; /** A fence carries Lead control JSON, not illustrative mathematical JSON. */ -export function isPlanFence(label: string, body: string): boolean { +function isPlanFence(label: string, body: string): boolean { if (label === 'math-plan') return true; if (!['math', 'json'].includes(label) || !body.trimStart().startsWith('{')) return false; try { @@ -66,16 +83,38 @@ export function isPlanFence(label: string, body: string): boolean { } /** Select the Lead control object without counting illustrative mathematical JSON as a plan. */ -function planResponse(text: string): unknown { - const blocks = [...text.matchAll(/```([a-z-]+)\s*\n([\s\S]*?)\n```/gu)]; +function planResponseBody(text: string): string | undefined { + const blocks = [...text.matchAll(noteFences)]; const explicit = blocks.filter(block => block[1] === 'math-plan'); if (explicit.length > 1) throw new Error('math_math-plan_requires_one_block'); - if (explicit.length) return JSON.parse(explicit[0][2]); + if (explicit.length) return explicit[0][2]; if (/```math-[a-z-]+\s*\n/u.test(text)) throw new Error('math_math-plan_requires_one_block'); - if (text.startsWith('{')) return JSON.parse(text); + if (text.startsWith('{')) return text; const legacy = blocks.filter(block => isPlanFence(block[1], block[2])); if (legacy.length > 1) throw new Error('math_math-plan_requires_one_block'); - return legacy.length ? JSON.parse(legacy[0][2]) : undefined; + return legacy[0]?.[2]; +} + +/** An explicit but malformed response still needs host validation and feedback. */ +export function hasPlanResponse(notes: string): boolean { + try { return planResponseBody(notes.trim()) !== undefined; } catch { return true; } +} + +/** Save one plan block while keeping the surrounding mathematical notes. */ +export function replacePlanInNotes(source: string, json: string): string { + const fence = '```math-plan\n' + json + '\n```'; + const bare = source.trim(); + if (bare.startsWith('{') && isPlanFence('json', bare)) { + try { JSON.parse(bare); return fence + '\n'; } catch { /* Preserve incomplete text. */ } + } + let replaced = false; + const notes = source.replace(noteFences, (block, label: string, body: string) => { + if (!isPlanFence(label, body)) return block; + if (replaced) return ''; + replaced = true; + return fence; + }); + return replaced ? notes : fence + '\n' + (source ? '\n' + source : ''); } /** The same parser also reads immutable checkpoint text without consulting a live workspace. */ @@ -83,7 +122,9 @@ export function parseMathResponse(text: string, legacyFence: string, bindings: R const errorPrefix = `math_${legacyFence}`; text = text.trim(); if (legacyFence === 'math-result' || legacyFence === 'math-plan') { - const value = legacyFence === 'math-plan' ? planResponse(text) : researchResponse(text, textField); + const body = legacyFence === 'math-plan' ? planResponseBody(text) : undefined; + const value = legacyFence === 'math-result' ? researchResponse(text, textField) : + body === undefined ? undefined : JSON.parse(body); if (value === undefined) throw new Error(errorPrefix + '_requires_one_block'); if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('math_response_invalid'); return { ...bindings, ...value }; @@ -184,47 +225,41 @@ export function deliveryDetails(value: any): Pick 0); - entries.push({ error: 'math_delivery_log_rewritten', offset, discardingOversized: discarding }); + // The rewritten bytes may repeat old events. Skip the snapshot and discard any unfinished line. + const last = Buffer.alloc(1); + const partial = stat.size > 0 && fs.readSync(fd, last, 0, 1, stat.size - 1) === 1 && last[0] !== 10; + const entry: DeliveryLogEntry = { error: 'math_delivery_log_rewritten', offset: stat.size, discardingOversized: partial }; + return { entries: [entry], offset: entry.offset, discardingOversized: partial, hasMore: false }; } const buffer = Buffer.alloc(Math.min(stat.size - offset, MAX_DELIVERY_LINE_BYTES + 1)); const size = fs.readSync(fd, buffer, 0, buffer.length, offset); + const hasMore = offset + size < stat.size; let start = 0; // A rejected long line may span several polls; never parse its trailing fragment. - if (discarding) { + if (discardingOversized) { const newline = buffer.subarray(0, size).indexOf(10); - if (newline < 0) return { lines: [], offset: offset + size, entries, discardingOversized: true }; - start = newline + 1; discarding = false; + if (newline < 0) return { entries: [], offset: offset + size, discardingOversized: true, hasMore }; + start = newline + 1; + discardingOversized = false; } + const entries: DeliveryLogEntry[] = []; while (start < size) { const newline = buffer.subarray(0, size).indexOf(10, start); if (newline < 0) { if (start === 0 && size > MAX_DELIVERY_LINE_BYTES) { - if (!recovery) throw new Error('math_delivery_line_too_large'); - start = size; discarding = true; + start = size; discardingOversized = true; entries.push({ error: 'math_delivery_line_too_large', offset: offset + start, discardingOversized: true }); } break; @@ -233,7 +268,29 @@ export function readDeliveryLines(file: string, offset: number, start = newline + 1; entries.push({ line, offset: offset + start, discardingOversized: false }); } - return { lines: entries.flatMap(entry => entry.line?.trim() ? [entry.line] : []), offset: offset + start, - entries, ...(recovery ? { discardingOversized: discarding } : {}) }; + return { entries, offset: offset + start, discardingOversized, hasMore }; } finally { fs.closeSync(fd); } } + +/** Advance only after the caller handles an entry. Failed intake leaves it available for retry. */ +export function* pendingDeliveryLines(file: string, cursors: Record, key: string, onAdvance: () => void, + mode: 'batch' | 'drain' = 'batch') { + const discardKey = key + '/discardingOversized'; + const advance = ({ offset, discardingOversized }: Pick) => { + const discarding = Number(discardingOversized); + if ((cursors[key] ?? 0) === offset && (cursors[discardKey] ?? 0) === discarding) return; + cursors[key] = offset; + cursors[discardKey] = discarding; + onAdvance(); + }; + for (;;) { + const offset = cursors[key] ?? 0; + const batch = readDeliveryLines(file, offset, cursors[discardKey] === 1); + for (const entry of batch.entries) { + yield entry; + advance(entry); + } + advance(batch); + if (mode === 'batch' || !batch.hasMore || batch.offset <= offset) return; + } +} diff --git a/src/solver/deliveryReceipts.ts b/src/solver/deliveryReceipts.ts index db6c04b1..0de2772a 100644 --- a/src/solver/deliveryReceipts.ts +++ b/src/solver/deliveryReceipts.ts @@ -14,6 +14,14 @@ export const deliveryReceiptSchema = z.object({ }); export type DeliveryReceipt = z.infer; +export function assignmentDeliveryReceipts(receipts: readonly DeliveryReceipt[] | undefined, assignment: TaskAssignment, + environmentDigest: string | undefined, workerId = assignment.workerId): DeliveryReceipt[] { + const assignmentKey = assignmentDeliveryFile(assignment); + return (receipts ?? []).filter(receipt => receipt.workerId === workerId && receipt.assignmentKey === assignmentKey && + receipt.taskId === assignment.taskId && receipt.taskDigest === assignment.taskDigest && + receipt.seedCommit === assignment.seedCommit && receipt.environmentDigest === environmentDigest); +} + /** Protocol feedback is durable evidence about intake, never Lean acceptance. */ export function rejectedDeliveryReceipt(input: { assignment: TaskAssignment; workerId: string; environmentDigest: string; submission: string; error: Error; now: number; @@ -29,11 +37,10 @@ export function rejectedDeliveryReceipt(input: { assignment: TaskAssignment; wor const value = parseMathResponse(input.submission, 'math-result', {}, 'summary'); replacement = value.kind === 'research' ? value.finding?.replacesReceipt : value.replacesReceipt; } catch { /* An unreadable submission cannot establish a correction link. */ } - const prior = typeof replacement === 'string' ? input.receipts?.find(receipt => receipt.id === replacement && - receipt.workerId === input.workerId && receipt.assignmentKey === assignmentKey && - receipt.taskId === input.assignment.taskId && receipt.taskDigest === input.assignment.taskDigest && - receipt.seedCommit === input.assignment.seedCommit && receipt.environmentDigest === input.environmentDigest && - receipt.status !== 'superseded') : undefined; + const prior = typeof replacement === 'string' + ? assignmentDeliveryReceipts(input.receipts, input.assignment, input.environmentDigest, input.workerId) + .find(receipt => receipt.id === replacement && receipt.status !== 'superseded') + : undefined; return { id: mathDigest(canonicalMathJson({ assignmentKey, submissionDigest, code, issues })), submissionDigest, workerId: input.workerId, assignmentKey, taskId: input.assignment.taskId, taskDigest: input.assignment.taskDigest, @@ -49,7 +56,7 @@ export function deliveryReceiptFeedback(receipt: DeliveryReceipt): string { 'Optional previousDeliveryId must come from COOPERATION.json mathematicalGaps[].deliveryId for that goal; an ordinary research delivery is not a scoped prior gap. ' + 'If no such prior gap exists, omit only previousDeliveryId and keep the required previousGap description.' : ''; return 'Host delivery receipt (intake feedback, not proof acceptance):\n' + JSON.stringify(receipt) + - '\nCorrect the indicated fields and append a new complete event to the same assignment delivery log; ' + + '\nCorrect the indicated fields and rerun research-observe. ' + 'include replacesReceipt:' + JSON.stringify(receipt.id) + ' in the corrected finding to resolve this receipt. ' + 'If that correction is rejected again, replace the new receipt; a recorded correction resolves its verified chain of earlier attempts. ' + 'Do not repeat the rejected event or truncate the log. Read COOPERATION.json for current receipts.' + gapFeedback; diff --git a/src/solver/humanEdit.ts b/src/solver/humanEdit.ts index cbf0a087..b59551ee 100644 --- a/src/solver/humanEdit.ts +++ b/src/solver/humanEdit.ts @@ -1,13 +1,30 @@ import fs from 'node:fs'; import path from 'node:path'; import crypto from 'node:crypto'; -import { canonicalMathJson, readMathText, withMathRuntimeLease } from '../math/mathRuntimeIo'; -import { parseCooperationPlan } from './tasks'; +import { canonicalMathJson, parseMathJson, readMathFile, withMathRuntimeLease } from '../math/mathRuntimeIo'; +import { parseCooperationPlan, taskGroup, taskVersion } from './tasks'; +import type { SolverRunState } from './archive'; import { assertPlanTaskTypeContracts } from './taskTypeContract'; import { readRunInspection } from './inspection'; -import { researchWorkerCanNode } from './modules/organization'; +import { assertPlanAssignments } from './modules/organization'; import { planApprovalInputSchema, planApprovalLog, planApprovalStatus } from './planApproval'; +/** A damaged complete record must not block later requests or hide a queued ID. */ +function* readQueuedObjects(log: string, maxBytes: number, incomplete: string): Generator> { + if (!fs.existsSync(log)) return; + const { bytes } = readMathFile(log, maxBytes); + if (bytes.length && bytes[bytes.length - 1] !== 0x0a) throw new Error(incomplete); + for (let start = 0; start < bytes.length;) { + const end = bytes.indexOf(0x0a, start); + const line = bytes.subarray(start, end); + start = end + 1; + if (!line.length) continue; + let value: unknown; + try { value = parseMathJson(line, 'math_human_log_invalid_json'); } catch { continue; } + if (value && typeof value === 'object' && !Array.isArray(value)) yield value as Record; + } +} + /** Append one complete line to a host-owned JSONL log; the solver reads it with its own cursor. */ function appendDurableLine(log: string, bytes: Buffer, invalid: string) { const fd = fs.openSync(log, fs.constants.O_CREAT | fs.constants.O_WRONLY | fs.constants.O_APPEND | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK, 0o600); @@ -20,47 +37,76 @@ function appendDurableLine(log: string, bytes: Buffer, invalid: string) { } finally { fs.closeSync(fd); } } +function summarizeEdit(current: NonNullable, proposed: ReturnType) { + const previous = new Map(current.tasks.map(node => [node.task.id, node.task])); + const changes: { taskId: string; fields: string[] }[] = []; + const oldGroups = new Map(current.groups?.map(record => [record.group.id, record.group]) ?? []); + const affected = new Set(), mathematical = new Set(); + 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)[key] ?? null) !== canonicalMathJson((task as Record)[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)[key] ?? null) !== canonicalMathJson((oldGroup as Record)[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(current.proofRoutes ?? []) !== canonicalMathJson(proposed.proofRoutes ?? [])) { + for (const route of [...(current.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 }; +} + /** Queue an edit through the existing host protocol; never write the checkpoint. */ export async function queueRunEdit(run: string, proposal: unknown, dryRun = false) { if (!proposal || typeof proposal !== 'object') throw new Error('math_edit_invalid'); - const value = proposal as Record; - if (typeof value.baseVersion !== 'string' || !value.baseVersion) throw new Error('math_edit_base_version_required'); + const value = proposal as Record, { baseVersion } = value; + if (typeof baseVersion !== 'string' || !baseVersion) throw new Error('math_edit_base_version_required'); const id = value.id ?? crypto.randomUUID(); if (typeof id !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/u.test(id)) throw new Error('math_edit_invalid_id'); const initial = readRunInspection(run); const directory = path.dirname(initial.stateFile); return withMathRuntimeLease({ lockPath: path.join(directory, 'edits.lock'), flockExecutable: '/usr/bin/flock' }, async lease => { const { state } = readRunInspection(run); - if (!state.cooperation?.planVersion) throw new Error('math_edit_plan_unavailable'); + const current = state.cooperation; + if (!current?.planVersion) throw new Error('math_edit_plan_unavailable'); const plan = parseCooperationPlan(state.problem, value); - assertPlanTaskTypeContracts(plan.tasks, state.cooperation.tasks.map(node => node.task)); - const workers = state.workers ?? []; - for (const task of plan.tasks) if (task.ownerId) { - const previous = state.cooperation.tasks.find(node => node.task.id === task.id); - const ownershipTask = previous?.capacityExploration ? { ...task, status: 'active' as const } : task; - if (!workers.some(worker => worker.id === task.ownerId && researchWorkerCanNode(worker, - { ...(previous ?? { status: 'pending', attempts: 0 }), task: ownershipTask }))) - throw new Error('math_plan_task_owner_unavailable'); - } - for (const group of plan.groups) if (group.engineerId && !workers.some(worker => worker.id === group.engineerId && worker.role === 'engineer')) - throw new Error('math_plan_group_engineer_unavailable'); - const edit = { id, baseVersion: value.baseVersion, ...plan }; + assertPlanTaskTypeContracts(plan.tasks, current.tasks.map(node => node.task)); + assertPlanAssignments(plan, current.tasks, state.workers ?? []); + const edit = { id, baseVersion, ...plan }; + const receipt = (status: 'already_queued' | 'validated' | 'queued') => + ({ id, status, baseVersion, ...summarizeEdit(current, plan) }); const log = path.join(directory, 'edits.jsonl'); - const existing = fs.existsSync(log) ? readMathText(log, 8 * 1024 * 1024) : ''; - if (existing && !existing.endsWith('\n')) throw new Error('math_edit_incomplete_log'); - const previous = existing.split('\n').filter(Boolean).map(line => JSON.parse(line)).find(item => item.id === id); - if (previous) { + for (const previous of readQueuedObjects(log, 8 * 1024 * 1024, 'math_edit_incomplete_log')) { + if (previous.id !== id) continue; if (canonicalMathJson(previous) !== canonicalMathJson(edit)) throw new Error('math_edit_id_conflict'); - return { id, status: 'already_queued', baseVersion: edit.baseVersion }; + return receipt('already_queued'); } - if (state.cooperation.edits?.some(item => item.id === id)) throw new Error('math_edit_id_already_used'); - if (value.baseVersion !== state.cooperation.planVersion) throw new Error('math_edit_version_conflict'); - if (dryRun) return { id, status: 'validated', baseVersion: edit.baseVersion }; + if (current.edits?.some(item => item.id === id)) throw new Error('math_edit_id_already_used'); + if (baseVersion !== current.planVersion) throw new Error('math_edit_version_conflict'); const bytes = Buffer.from(JSON.stringify(edit) + '\n'); if (bytes.length > 1024 * 1024) throw new Error('math_edit_too_large'); + if (dryRun) return receipt('validated'); + const queued = receipt('queued'); lease.assertHeld(); appendDurableLine(log, bytes, 'math_edit_log_invalid'); - return { id, status: 'queued', baseVersion: edit.baseVersion }; + return queued; }); } @@ -76,12 +122,13 @@ export async function queuePlanApproval(run: string, value: unknown) { return withMathRuntimeLease({ lockPath: path.join(directory, 'plan-approvals.lock'), flockExecutable: '/usr/bin/flock' }, async lease => { const { state, stateFile } = readRunInspection(run); const log = planApprovalLog(stateFile); - const existing = fs.existsSync(log) ? readMathText(log, 1024 * 1024) : ''; - if (existing && !existing.endsWith('\n')) throw new Error('math_plan_approval_incomplete_log'); - const lines = existing.split('\n').filter(Boolean).map(line => JSON.parse(line) as { id?: unknown; planVersion?: unknown }); - const previous = lines.find(item => item.id === id); - if (previous) { - if (previous.planVersion !== planVersion) throw new Error('math_plan_approval_id_conflict'); + let approvalCount = 0; + for (const previous of readQueuedObjects(log, 1024 * 1024, 'math_plan_approval_incomplete_log')) { + const approval = planApprovalInputSchema.safeParse(previous); + if (!approval.success) continue; + approvalCount++; + if (approval.data.id !== id) continue; + if (approval.data.planVersion !== planVersion) throw new Error('math_plan_approval_id_conflict'); return { id, status: 'already_queued', planVersion }; } const status = planApprovalStatus(state); @@ -90,7 +137,7 @@ export async function queuePlanApproval(run: string, value: unknown) { if (status === 'approved') throw new Error('math_plan_approval_already_approved'); if (status === 'awaiting-plan') throw new Error('math_plan_approval_plan_unavailable'); if (planVersion !== state.cooperation?.planVersion) throw new Error('math_plan_approval_version_conflict'); - if (lines.length >= 64) throw new Error('math_plan_approval_limit'); + if (approvalCount >= 64) throw new Error('math_plan_approval_limit'); lease.assertHeld(); appendDurableLine(log, Buffer.from(JSON.stringify({ id, planVersion }) + '\n'), 'math_plan_approval_log_invalid'); return { id, status: 'queued', planVersion }; diff --git a/src/solver/modules/context.ts b/src/solver/modules/context.ts index 9587cc0e..aa3b385c 100644 --- a/src/solver/modules/context.ts +++ b/src/solver/modules/context.ts @@ -4,7 +4,7 @@ import { mathDigest, canonicalMathJson, readMathText } from '../../math/mathRunt import { assertMathCanonicalPath } from '../../math/paths'; import { readLeanResidualGoalSnapshot } from '../../math/leanResidualGoals'; import { mathematicsRuntimeInstruction } from '../../math/mathRuntimeEnvironment'; -import { MATH_TOOLS_SHA256_ENV, mathToolsInstruction, mathToolsUsageInstruction, type MathTools } from '../../math/mathTools'; +import { MATH_TOOLS_SHA256_ENV, mathToolsInstruction, type MathTools } from '../../math/mathTools'; import { CERTIFICATE_KERNEL_MODULE, isCertificateSlotFile } from '../../math/certificateSlots'; import { isTheoryModuleFile, THEORY_MODULE_NAMESPACE } from '../../math/theoryModules'; import { DECLARATION_INDEX_FILE } from '../declarationIndex'; @@ -13,10 +13,11 @@ import type { SolverRunState } from '../archive'; import { committedSource, type SolverProblem } from '../problem'; import type { ProofCheck } from './evidence'; import { solverProofFeedback, type SolverFailure } from '../feedback'; -import { assignmentDeliveryFile, leadPlanDeliveryFile, isFeasibilityReview, isFinalCandidateReview, taskGroup, taskVersion, type CooperativeAction } from '../tasks'; +import { assignmentDeliveryFile, leadPlanDeliveryFile, isActiveFinalCandidateReview, isFeasibilityReview, isFinalCandidateReview, taskGroup, taskVersion, type CooperativeAction } from '../tasks'; import type { CooperationState } from '../cooperation'; import { leadPlanPublicationFeedback } from '../cooperationShared'; import { contextCheckpointRejectionFeedback } from '../contextCheckpoint'; +import { assignmentDeliveryReceipts } from '../deliveryReceipts'; import { statementReviewSummary, type StatementAction, type StatementReview } from '../statementReview'; import { buildProofContinuation } from '../progress'; import { originalGoalTaskFocus, originalGoalFrontierSnapshot } from './search'; @@ -28,7 +29,7 @@ import { continuationReferenceSection, referenceQuery } from '../continuationSea import { knowledgeApplicationContextSections } from '../knowledgeApplications'; import { installedLibraryContextSections } from '../installedLibraryContext'; import type { LibraryAccess } from '../libraryAccess'; -import { compileContextSections, compileTaskContext, deliveryIndexRow, frozenSourceContext, landedHelperSection, leadPlanRejectionSection, leadResearchInputSection, portfolioContextSections, TaskContextError, +import { compileContextSections, compileTaskContext, cooperativeResponseSections, deliveryIndexRow, frozenSourceContext, landedHelperSection, leadPlanRejectionSection, leadResearchInputSection, portfolioContextSections, TaskContextError, type CompiledContext, type ContextManifest, type ContextSection, type TaskContextInput } from '../contextCompiler'; import type { CustomResearchModule, ResearchModuleSlot } from './policy'; import { defaultResearchRouteConcurrency, researchTaskRole, type ResearchWorker } from './organization'; @@ -184,10 +185,10 @@ export function buildResearchContext(task: SolverProblem, state: Readonly !Object.hasOwn(task.frozenFiles ?? {}, file))), 'RESEARCH.md', ...(deliveryFile ? [deliveryFile] : [])])}. ` + + `Editable paths: ${JSON.stringify([...(readOnlySources ? [] : task.ownedFiles.filter(file => !Object.hasOwn(task.frozenFiles ?? {}, file))), 'RESEARCH.md', ...(planDraft ? [planDraft] : [])])}. ` + (taskLogPath ? 'You may append to ' + taskLogPath + '. ' : '') + (readOnlySources ? 'Leave every Lean source unchanged. ' : '') + taskRules) + '\n' + (['M1', 'M3', 'M4', 'M5'] as const).map(slot => strategyAdvice(access, slot, '', slot !== 'M5' || cooperative)).join('\n') : `${responsibility} Work only in this isolated worktree. -Edit only ${[...(readOnlySources ? [] : editableOwnedFiles(task.ownedFiles, file => path.join(access.worktree, task.projectRelative, file), task.frozenFiles)), path.join(access.worktree, 'RESEARCH.md'), ...(deliveryFile ? [path.join(access.worktree, deliveryFile)] : []), ...(taskLogPath ? [taskLogPath] : [])].join(', ')}. +Edit only ${[...(readOnlySources ? [] : editableOwnedFiles(task.ownedFiles, file => path.join(access.worktree, task.projectRelative, file), task.frozenFiles)), path.join(access.worktree, 'RESEARCH.md'), ...(planDraft ? [path.join(access.worktree, planDraft)] : []), ...(taskLogPath ? [taskLogPath] : [])].join(', ')}. ${access.assignment ? 'Save RESEARCH.md and delivery logs at these exact worktree-root paths' : 'Save RESEARCH.md at its exact worktree-root path'}, including when a diagnostic command runs inside the Lean project subdirectory. Temporary ${planningLead ? 'mathematical notes and tool output' : 'probes, backups and diagnostic output'} may be written under ${path.join(access.worktree, '.scratch', 'tmp')} or the Lean project's .scratch/tmp directory. The shell's TMPDIR points to the worktree-local directory; run mkdir -p "$TMPDIR" before creating temporary files. /tmp is read-only. Untracked regular scratch files stay advisory and remain outside formal proof checkpoints. Do not git add scratch files or use symlinks there. ${planningLead ? 'Retain useful mathematical findings in RESEARCH.md before returning.' : 'Retain reusable proof code and findings in RESEARCH.md or owned Lean files before returning.'} Preserve original declaration kinds, names, parameters, types, assumptions, options and namespace/section context. Keep all existing imports. ${fixedReview ? 'Review original definition bodies and statement types without changing them.' : planningLead ? 'Inspect original definition bodies and statement types without changing them.' : 'Original goals may include def declarations whose bodies must be filled; retain all other original definition bodies.'} ${readOnlySources ? 'Leave all Lean source files, imports and environment configuration unchanged.' : 'In a Mathlib project, you may add import Mathlib or any pinned Mathlib.* import in owned files. You may also import installed frozen Submission.Library.* modules, frozen local modules already imported by the original owned files, or other owned modules. Avoid import cycles and do not edit trusted problem or package files.'} Proofs you submit for acceptance must not use sorry, admit, native_decide, unsafe or new axioms. Do not read external candidate solutions. @@ -341,7 +342,7 @@ ${access.corpusFile ? `For library lookup, run ${command} search-lean --workspac maxContextBytes: access.maxContextBytes, maxOptionalContextBytes: access.maxOptionalContextBytes, inlineManifest: false }); const continued = singleSkill ? compileSingleContinuation() : undefined; const compiled = access.assignment && cooperation ? buildCooperativeContext(task, cooperation, bundle, access.assignment, - compilation, state.workers, [diagnosticExecutionRules, access.mathTools ? mathToolsUsageInstruction(access.mathTools, access.worktree) : ''].filter(Boolean).join('\n'), skillWorkflow ? access.researchSkill : undefined) : { ...bundle, ...compileFull(), + compilation, state.workers, skillWorkflow ? access.researchSkill : undefined) : { ...bundle, ...compileFull(), ...(continued ? { continuationMessage: continued.message, continuationManifest: continued.manifest } : {}), compileDispatch: (options: ResearchDispatchOptions) => options.continuation && continued ? compileSingleContinuation(options.checkpointInstruction) : compileFull(options.checkpointInstruction) }; @@ -462,6 +463,8 @@ function leadTaskTable(cooperation: CooperationState): string { const statusById = new Map(nodes.map(node => [node.task.id, node.status])); const open = nodes.filter(node => !done(node.status)), checked = nodes.filter(node => done(node.status)); const rows = [...open, ...checked].slice(0, LEAD_TASK_TABLE_ROWS).map(node => { + if (isFinalCandidateReview(node.task)) + return [node.task.id, 'final-review', 'status=' + (node.task.status ?? 'active')].join(' '); const unmet = node.task.dependsOn.filter(id => !done(statusById.get(id) ?? '')); return [node.task.id, node.task.kind, 'status=' + (node.task.status ?? 'active'), 'executionStatus=' + node.status, 'owner=' + (node.assignment?.workerId ?? node.task.ownerId ?? '-'), 'attempts=' + node.attempts, @@ -475,11 +478,9 @@ function leadTaskTable(cooperation: CooperationState): string { /** Add role rules; the compiler selects a scoped, versioned mathematical context for dispatch. */ function buildCooperativeContext(problem: SolverProblem, cooperation: CooperationState, context: ContextBundle, action: CooperativeAction, compilation: Omit, - workers: readonly Pick[] = [], toolGuidance = '', researchSkill?: MathAgentSkill): ContextBundle { + workers: readonly Pick[] = [], researchSkill?: MathAgentSkill): ContextBundle { const skillWorkflow = Boolean(researchSkill); - const contract = cooperativeWorkContract(action, cooperation.tasks, cooperation); - const workContract = skillWorkflow ? Object.fromEntries(Object.entries(contract) - .filter(([key]) => key !== 'deliveryGuidance')) as typeof contract : contract; + const workContract = cooperativeWorkContract(action, cooperation.tasks, cooperation); const capacityExploration = action.kind === 'task' ? cooperation.tasks.find(node => node.task.id === action.task.id)?.capacityExploration : undefined; const organizationRules = action.kind === 'lead' && workers.some(worker => worker.role === 'prover') @@ -510,20 +511,20 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio ? 'Initial planning shares the proof budget. After one focused inspection of the exact targets and definitions, publish the smallest useful executable task graph before further literature searches or proof exploration. ' + 'The first graph must cover every original target exactly once; it does not need a complete proof decomposition. Direct original-goal tasks plus distinct research tasks for specific uncertain inferences are a valid first plan and let peers work in parallel. ' + 'Add a helper only when its full closed Lean type and intended consumer are known; never invent a proposition to fill the graph. Keep original goals independent of advisory research in proof dependencies. ' + - 'Save the current route and exact uncertainties in RESEARCH.md, publish the complete plan through this dispatch\'s delivery log, and return. Later Lead decisions use the accepted graph and new peer evidence to add typed steps or revise a route.\n' + 'Save the current route and exact uncertainties in RESEARCH.md, publish the complete plan with plan-apply --publish, and return. Later Lead decisions use the accepted graph and new peer evidence to add typed steps or revise a route.\n' : ''; const leadDeliveryRules = action.kind === 'lead' - ? 'Once a complete plan has useful executable work, save the plan, or a revision of the accepted graph, and return promptly so peers can start it. Delegate unresolved library or mathematical searches as research tasks to eligible Researchers or the Engineer. For new, unstarted helpers that need no worker-specific context, omit ownerId so eligible peers can claim them. Keep explicit reservations when needed; removing ownerId never releases a saved assignment. Before adding work, inspect ready tasks reserved by ownerId to a busy worker while an eligible generalist is idle. Explicitly reassign an unstarted, unassigned task through the plan when useful, preserving its mathematical contract. Preserve route gates, group scope, independent reviewer eligibility and running assignments; an idle Engineer can do research while its original goal waits on a genuine route prerequisite. Apply this on every decision, including later replanning. Include every original target and preserve checked task contracts and active independent task definitions; publish the plan or revision once through the current dispatch delivery log; keep concise mathematical route notes in RESEARCH.md. If you return without a log publication, save the complete plan or revision in a single math-plan JSON fence in RESEARCH.md. After a successful publication, a second copy of the graph in RESEARCH.md or the final response is unnecessary. The host owns mathematician plan approval; return after publication without polling or waiting for approval. Add only mathematically useful executable tasks. ' + + ? 'Once a complete plan has useful executable work, save the plan, or a revision of the accepted graph, and return promptly so peers can start it. Delegate unresolved library or mathematical searches as research tasks to eligible Researchers or the Engineer. For new, unstarted helpers that need no worker-specific context, omit ownerId so eligible peers can claim them. Keep explicit reservations when needed; removing ownerId never releases a saved assignment. Before adding work, inspect ready tasks reserved by ownerId to a busy worker while an eligible generalist is idle. Explicitly reassign an unstarted, unassigned task through the plan when useful, preserving its mathematical contract. Preserve route gates, group scope, independent reviewer eligibility and running assignments; an idle Engineer can do research while its original goal waits on a genuine route prerequisite. Apply this on every decision, including later replanning. Include every original target and preserve checked task contracts and active independent task definitions; publish the plan or revision once with plan-apply --publish; keep concise mathematical route notes in RESEARCH.md. For intake on return, omit --publish. After a successful publication, a second copy of the graph in RESEARCH.md or the final response is unnecessary. The host owns mathematician plan approval; return after publication without polling or waiting for approval. Add only mathematically useful executable tasks. ' + 'A goal/lemma objective may guide the argument, but cannot replace its frozen proof deliverable with a read-only audit or diagnostic report. Create a separate untyped research/sketch task for those checks. ' + 'consumerGoalIds is allowed only on untyped research/sketch tasks; connect a typed lemma through its actual consumer\'s dependsOn or proofRoutes. ' + 'Plan task.status may be active, paused or stopped; omission means active. Context task interfaces preserve this policy in status and show host scheduling separately in executionStatus. Never copy executionStatus values into a plan task.status; the host determines scheduling and proof acceptance. ' + - 'The delivery, plan and checkpoint formats in these instructions are complete; do not read the TheoremOS runtime source or docs to learn them.\n' + 'Use the generated tool help for command syntax.\n' : ''; // A revision states only changed tasks; the host expands it against the accepted graph and validates the result. const planRevisionRules = action.kind === 'lead' && cooperation.tasks.length - ? 'Revise the accepted graph instead of retyping it. Read the current task graph in COOPERATION.json or grep the host-synced accepted graph in the math fence in RESEARCH.md. If RESEARCH.md exceeds 1,000,000 bytes, use the dispatch delivery log for plan submissions and consult COOPERATION.json for the accepted graph. ' + - `Use this revision schema in the current delivery-log event, or in a math-plan fence in RESEARCH.md if returning without publication: {"baseVersion":${JSON.stringify(action.planVersion ?? '')},"upsert":[{"id":"existing_task","status":"paused"},{"id":"new_helper","kind":"lemma","objective":"...","theoremName":"...","type":"...","dependsOn":[]}],"remove":["obsolete_task"]}. ` + - 'This graph schema must also include every required researchDecisions, progressReview and nextCheckDecisions field from current Lead decision requirements in the same JSON object. An upsert of an existing id replaces only the fields it supplies (null deletes a field; a changed kind replaces the whole task); a new id needs a complete task definition. ' + + ? 'Revise the accepted graph instead of retyping it. Read the current task graph in COOPERATION.json or the host-synced accepted graph in the math-plan block in RESEARCH.md. For large notes, use COOPERATION.json and plan-apply --publish. ' + + `Use this revision schema in the draft passed to plan-apply: {"baseVersion":${JSON.stringify(action.planVersion ?? '')},"upsert":[{"id":"existing_task","status":"paused"},{"id":"new_helper","kind":"lemma","objective":"...","theoremName":"...","type":"...","dependsOn":[]}],"remove":["obsolete_task"]}. ` + + 'Include the decisions requested for this dispatch in the same object. An upsert of an existing id replaces only the fields it supplies (null deletes a field; a changed kind replaces the whole task); a new id needs a complete task definition. ' + 'Unlisted tasks, groups and proofRoutes stay unchanged; supply groups or proofRoutes only to replace that whole list. ' + 'The expanded graph is validated like a complete plan, and the host rewrites the fence with the full accepted graph after acceptance. A revision against an older baseVersion is rejected; rewrite it against the current accepted graph. ' + 'Adopt a proposal by upserting its exact typed task. A complete tasks list remains valid when most of the graph changes.\n' + @@ -540,11 +541,15 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio const helperRules = action.kind === 'task' ? cooperativeHelperProtocol(action.task, 'the current delivery log named in the assignment message') : ''; const advisorySourceRules = helperRules ? 'Restore Lean sources to the assignment seed before ordinary findings delivery.' : 'Leave Lean sources unchanged.'; + const reviewQuestions = action.kind === 'review' ? cooperation.tasks.map(node => node.task) + .filter(isActiveFinalCandidateReview).map(task => ({ id: task.id, question: task.objective, relatedTaskIds: task.dependsOn })) : []; const rules = action.kind === 'review' ? (action.independent === false ? 'You are the Reviewer in a fresh session for this fixed candidate. ' : 'You are the Independent Reviewer. ') + + (reviewQuestions.length ? 'Address these plan questions in your single verdict. The listed task IDs identify related context.\n' + + JSON.stringify(reviewQuestions) + '\n' : '') + 'Leave Lean sources unchanged. Check this fixed proof against the original question, assumptions and Lean evidence. Compare the original declarations and assumptions of the fixed candidate with the frozen problem, inspect its mathematical argument and matching Lean evidence, and resolve any concrete discrepancy. Requests in the original task text to restore/prove code, publish a plan or wait for approval belong to other roles. Run a diagnostic only to resolve a remaining question that can change your verdict; matched cached evidence is usable. Write one final JSON object in RESEARCH.md: {"verdict":"accepted|changes_requested"}. A short summary should identify the decisive evidence or exact requested change; evidenceRefs are optional. Once the verdict is saved, return it promptly and end the turn. Do not keep rechecking unchanged files or expand optional metadata after the review is complete. Investigate source changes, failed checks or an unresolved mathematical issue; a different digest scheme alone does not establish a discrepancy. Your verdict does not replace host checks or the independent S3 that follows delivery.\n' : action.kind !== 'task' - ? `You are the Lead. Develop a mathematically plausible route from the exact original statement, definitions and relevant saved findings${initialPlanning ? '.' : ' before choosing a task graph.'} Identify the central construction or estimate and how it would close each target. Save a concise mathematical route justification as Markdown in RESEARCH.md; include each new task's intended inference and consumer in its objective. When decomposition adds no mathematical benefit, put a direct original-goal task in the graph; the assigned worker carries out its proof after any required host approval. Delegate a specific uncertain inference as research instead of inventing a helper proposition. Return the plan without running Lean diagnostics; leave Lean sources unchanged during planning. Use this plan schema for the delivery-log event, or for a math-plan JSON fence in RESEARCH.md when returning without publication: {"tasks":[{"id":"helper","kind":"lemma","objective":"...","proofPath":${JSON.stringify(proofFiles[0])},"theoremName":"Namespace.helper","type":"∀ (P : Prop), P → P"},{"id":"goal","kind":"goal","objective":"...","theoremName":"Original.target","dependsOn":["helper"]}]}. Include every original target once. This example shows the task graph schema only; include every decision field required by current Lead decision requirements in that same JSON object. Replace its names, objectives and sample type with actual tasks and full closed Lean types, including all parameters and hypotheses. Never copy placeholder types. If no exact helper proposition is known, use an untyped research/sketch task. Choose proofPath from ${JSON.stringify(proofFiles)}${proofFiles.length < leanFiles.length ? '; workers generate Submission/Certificates modules and import them from these files' : ''}${theoryPlanning}; goals infer it from theoremName, and lemmas may omit it only when one Lean file is owned. Use lemma tasks whenever workers should save proofs; research/sketch tasks without an exact typed target only return advisory findings and restore temporary probes. Typed research tasks are normalized to lemma tasks. dependsOn defaults to []; revision to 0. Keep accepted task definitions stable; record progress in notes rather than rewriting objectives, which invalidates their checked deliveries. Revise a mathematical contract to change a route; changing only prose or revision does not resolve a recorded blocker. conditional:true allows fixed typed lemma premises. statementReview:true with informalStatement requests meaning review. Optional blueprint fields informalProof (the intended argument in at most 2000 characters) and citations (up to 8 short source references such as "Bhargava–Hanke 2005, Thm 2") guide the assigned worker; they never change the task contract or act as premises. A new concept is a lemma task with declaration:"definition" and its Lean type (e.g. "ℕ → ℕ → Prop"); put its intended meaning in objective, and list it in the dependsOn of lemmas whose types mention it. Consumers wait for its checked body. Pair each definition with a typed sanity lemma in the same proofPath that pins its intended meaning on a characterizing or small case, so a vacuous or mistaken body fails before consumers rely on it. Optional groups set ownership, sharing and budgets.\n` + ? `You are the Lead. Develop a mathematically plausible route from the exact original statement, definitions and relevant saved findings${initialPlanning ? '.' : ' before choosing a task graph.'} Identify the central construction or estimate and how it would close each target. Save a concise mathematical route justification as Markdown in RESEARCH.md; include each new task's intended inference and consumer in its objective. When decomposition adds no mathematical benefit, put a direct original-goal task in the graph; the assigned worker carries out its proof after any required host approval. Delegate a specific uncertain inference as research instead of inventing a helper proposition. Return the plan without running Lean diagnostics; leave Lean sources unchanged during planning. Use this plan schema in the draft passed to plan-apply: {"tasks":[{"id":"helper","kind":"lemma","objective":"...","proofPath":${JSON.stringify(proofFiles[0])},"theoremName":"Namespace.helper","type":"∀ (P : Prop), P → P"},{"id":"goal","kind":"goal","objective":"...","theoremName":"Original.target","dependsOn":["helper"]}]}. Include every original target once. This example shows the task graph schema only; include every decision field required by current Lead decision requirements in that same JSON object. Replace its names, objectives and sample type with actual tasks and full closed Lean types, including all parameters and hypotheses. Never copy placeholder types. If no exact helper proposition is known, use an untyped research/sketch task. Choose proofPath from ${JSON.stringify(proofFiles)}${proofFiles.length < leanFiles.length ? '; workers generate Submission/Certificates modules and import them from these files' : ''}${theoryPlanning}; goals infer it from theoremName, and lemmas may omit it only when one Lean file is owned. Use lemma tasks whenever workers should save proofs; research/sketch tasks without an exact typed target only return advisory findings and restore temporary probes. Typed research tasks are normalized to lemma tasks. dependsOn defaults to []; revision to 0. Keep accepted task definitions stable; record progress in notes rather than rewriting objectives, which invalidates their checked deliveries. Revise a mathematical contract to change a route; changing only prose or revision does not resolve a recorded blocker. conditional:true allows fixed typed lemma premises. statementReview:true with informalStatement requests meaning review. Optional blueprint fields informalProof (the intended argument in at most 2000 characters) and citations (up to 8 short source references such as "Bhargava–Hanke 2005, Thm 2") guide the assigned worker; they never change the task contract or act as premises. A new concept is a lemma task with declaration:"definition" and its Lean type (e.g. "ℕ → ℕ → Prop"); put its intended meaning in objective, and list it in the dependsOn of lemmas whose types mention it. Consumers wait for its checked body. Pair each definition with a typed sanity lemma in the same proofPath that pins its intended meaning on a characterizing or small case, so a vacuous or mistaken body fails before consumers rely on it. Optional groups set ownership, sharing and budgets.\n` : ['research', 'sketch'].includes(action.task.kind) ? 'You are a Mathematical Researcher. Explore the assigned mathematical question. ' + advisorySourceRules + ' Deliver a concise mathematical argument or counterexample with its exact assumptions, unresolved inference and intended original-goal application, so another solver can continue the work. Use library searches to resolve specific uncertainties in that argument. Save a scoped negative library result or a classification gap in worktree-root RESEARCH.md as soon as it is established, rather than waiting for a proof or the end of the turn. Record the pinned library/environment version, searched paths, queries or method, exact result and the missing mathematical inference. A scoped search failure is not proof of global absence. Replace inherited RESEARCH.md with findings for this assignment before returning; ordinary Markdown is supported. Timed checkpoints preserve progress and resume the same assignment without completing it. When a negative result or classification gap needs a route decision, promptly publish the existing research finding with needsDecision:true, conclusion:"inconclusive", a summary stating the precise gap, evidenceRefs and remainingObligations; use conclusion:"refuted" only for an actual refutation of the scoped claim. Otherwise ordinary findings may use JSON {"summary":"findings and evidence","needsDecision":true} to request a route change. Optional conclusion is supporting, refuted or inconclusive; findings remain advisory. To turn a useful bridge into proof work, add lemmaRequests:[{id,kind:"lemma",objective,theoremName,type,proofPath,dependsOn:[]}]. Supply new ids and full closed Lean types in your own route group. The host validates these proposals and presents them to Lead; adoption in the Lead plan creates a separate typed assignment whose proof requires independent checking. A proposal does not authorize edits to Lean sources.\n' : (action.task.kind === 'lemma' ? 'You are a Lean Prover. Write and deliver the assigned auxiliary proof for its declared consumers. ' @@ -553,21 +558,10 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio 'Prove the assigned Lean declaration with its exact requested type. ' + proofDeliverableRules + 'Save argument, consumer use and gap in RESEARCH.md; separate math from library/type/tactic issues and discharge every premise. An original goal may be a def: fill only its body. Helpers must be theorems/lemmas. Repair solver-created lemma bodies, preserving statements/placement. Preserve unrelated seed proofs, sorry and diagnostics; do not prove or rewrite them to make the whole file pass. Conditional proofs use fixed dependency lemmas, no stubs or extra assumptions. Check the saved target and imports; a Helpers-only check does not check Submission. The host checks this declaration in a disposable projection and checks the full candidate after integration.\n'; const researchSourcesRules = action.kind === 'task' && ['lemma', 'goal'].includes(action.task.kind) - ? 'When supporting Lean code is saved but the assigned declaration is still unproved, bind the research finding to those exact sources: add a top-level sources object to the kind:"research" event. Its keys must be exactly ' + - JSON.stringify(leanFiles) + - ', with each value the complete saved UTF-8 file content (total at most 1,000,000 bytes). Read all files and append the complete JSON line in one local script; do not copy large source text by hand. Omit commit when using sources. The host freezes these supplied bytes in an isolated snapshot and retains the supporting declarations for separate typed checks. Without sources or an existing commit, the finding is bound to the assignment seed. If blocked, include needsDecision:true, conclusion:"inconclusive", the exact mathematicalGap and remainingObligations for this snapshot. Source changes after that report require a fresh source-bound finding. Auxiliary code and a reported gap never accept the assigned proof.\n' : ''; - const dispatchNonce = action.kind === 'lead' ? action.initialPlanNonce ?? action.planNonce : undefined; + ? 'Use research-observe --snapshot-sources when a finding depends on changed saved Lean code. Otherwise it is bound to the assignment seed. Publish a fresh snapshot if the supporting files change.\n' : ''; const sharing = action.kind === 'task' - ? 'To share before returning, append JSON to the current delivery log named in the assignment message: {"summary":"progress or gap"}. Create it by appending if absent, even when an earlier assignment\'s log is present; do not publish to those older logs. To share an advisory finding or an unresolved proof gap, append {"kind":"research","finding":{"summary":"complete argument, exact assumptions and gap","conclusion":"inconclusive","needsDecision":true,"evidenceRefs":[],"remainingObligations":["precise unresolved mathematical inference"],"lemmaRequests":[]}}. Inline the full finding; the host snapshots notes. Supporting commits must descend from the assignment seed; publishing does not finish or park your proof task. For typed proofs, save files, append {"kind":"ready","summary":"saved proof"}, stop editing and return. Omit commit/targets. The host freezes the saved sources and independently checks and integrates them after turn settlement and confirmed shutdown. Receipts: COOPERATION.json proofReadyRecords. Retry failures with a new id; unconfirmed shutdown quarantines this workspace. Returning naturally also submits. Do not run git add or git commit. Do not truncate the delivery log.\n' - : leadPlanDeliveryFile(action) ? `Once a useful executable plan is ready, publish it promptly: append one complete JSON line to ${leadPlanDeliveryFile(action)}. Create this current dispatch log by appending if absent; its absence is normal and does not require searching older logs. ` + - `Use {"kind":"plan","baseVersion":${JSON.stringify(action.kind === 'lead' ? action.planVersion : '')},` + - (dispatchNonce ? `"dispatchNonce":${JSON.stringify(dispatchNonce)},` : '') + - '"summary":"mathematical route and intended consumers","tasks":[...],"groups":[...],"proofRoutes":[...]}. ' + - 'Inline the complete valid graph covering every original target exactly once as the tasks array, or omit tasks and put a revision of the accepted graph (upsert/remove as described for RESEARCH.md) at the top level of the same line; optional groups and proofRoutes may be omitted. The host freezes the line and can start peers before you return. ' + - 'For a shared construction or estimate, dispatch small typed foundation lemmas first and connect their consumers through dependsOn. Delegate exploratory computations. To retire a refuted group or proof route, add retireRoutes:[{routeId,reason,evidenceRefs}] to the plan. ' + - 'Only the first valid publication in this dispatch is accepted. A partial line, ordinary RESEARCH.md save, or an external file reference does not publish a plan. Do not truncate the log. ' + - 'Copy the dispatchNonce and baseVersion fields exactly as shown; a human edit or another accepted revision supersedes stale work. Preserve checked contracts and unrelated active assignments. ' + - 'After publication, return promptly; a notes-only final keeps the published graph. Further changes in this dispatch use the normal final response, as a revision against this dispatch baseVersion that may repeat the published changes. The next Lead dispatch may publish its own revision.\n' : ''; + ? 'Use research-observe for findings that need to reach peers before you return. For typed proofs, save the assigned declaration and return for host checking.\n' + : leadPlanDeliveryFile(action) ? 'Use plan-apply --publish for live intake, then return promptly. The host accepts only one publication per dispatch. A notes-only return keeps the published graph. Further changes in the same dispatch can use plan-apply without --publish for intake on return.\n' : ''; const visibleIds = new Set(cooperation.tasks.map(node => node.task.id)); const proofRoutes = (cooperation.proofRoutes ?? cooperation.tasks.flatMap(node => node.alternativeRoutes ?? [])) .filter(route => visibleIds.has(route.targetTaskId) && @@ -592,15 +586,12 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio const boundedFrontier = action.kind === 'task' && proofRoutes.length > 0; const focusRules = skillWorkflow ? '' : action.kind === 'lead' || action.kind === 'task' ? 'Prioritize a ready typed step proving a substantive missing construction or quantitative estimate on the original-goal frontier. First check the key mathematical premise and structural bridge against the exact definitions; a normed space alone does not supply inner-product identities. Choose genuinely weaker, independently Lean-checkable sublemmas with closed types. If a route requires a stronger result than the target, such as an exact construction for an approximation claim, justify its necessity and feasibility before expanding it; otherwise investigate a weaker sufficient construction. For an algorithmic target, separate the mathematical output bound, correctness of the concrete implementation and its running-time bound; bounded output size alone supplies no running-time proof. Record the actual consumer with explicit dependsOn or proofRoutes and show the concrete application, discharged inference and remaining premises. A checked conditional wrapper establishes sufficiency under its explicit conditions; keep its unproved conditions on the frontier. Pairing or renaming the original branches, or assuming the unresolved core result, does not close the original goal. Advisory dependencies identify questions, not proved premises. Preserve checked contracts and independent investigations. Let consumers do short glue; add helpers only for useful reusable results. Split independent core proof, strength/counterexample audit and library adaptation questions.\n' : ''; - const nextCheckRules = ['lead', 'task'].includes(action.kind) ? - 'To test one unresolved inference, add mathematicalGap.nextCheck:{action:"feasibility"|"apply-lemma"|"construction-check",objective:"one discriminating check",expectedEvidence:"the exact evidence that would support or challenge this step",targetTaskId:"OPTIONAL_VISIBLE_TASK"}. The host schedules an independent feasibility task, binds its parent/target/original consumer and retains it in COOPERATION.json.nextChecks. Shared unproved definition interfaces on the original-goal path may also receive one host-origin definition-contract check; it needs no invented research delivery. This checks a method; it supplies no proved premise. A check worker must finish with checkOutcome:{checkId:"HOST_CHECK_ID",conclusion:"supporting"|"refuted"|"inconclusive",summary:"scoped result",evidenceRefs:["retained evidence"]}. Unknown remains inconclusive. An outcome publication ends this check. Lead answers each presented outcome in nextCheckDecisions:[{checkId,outcomeDeliveryId,action:"continue"|"revise"|"stop",reason}]. Continuing after a refuted outcome additionally requires counterEvidenceDeliveryId naming another current supporting host check of the same target and consumer with retained evidence. Otherwise revise the actual target argument, dependencies or route, assign a new active independent feasibility check inspecting the target in the same plan, or stop the target. An objective rewrite is not a revision. These decisions remain advisory; they never establish truth or acceptance. Host check IDs cannot become proof dependencies.\n' : ''; + const nextCheckProposal = action.kind === 'task' && !isFinalCandidateReview(action.task) + ? 'To request an independent check of an unresolved inference, include mathematicalGap.nextCheck:{action:"feasibility"|"apply-lemma"|"construction-check",objective:"one discriminating check",expectedEvidence:"the observation that would decide it",targetTaskId:"OPTIONAL_VISIBLE_TASK"}. The host binds the check to the original consumer. Its result is advisory.\n' : ''; const observationRules = action.kind === 'task' ? - (['lemma', 'goal'].includes(action.task.kind) - ? 'For an unfinished typed proof, publish a research observation only for a substantive intermediate finding or gap. Once the assigned proof is complete and saved, use the ready delivery protocol above and return; no separate research observation is required. To publish an intermediate finding, use ' - : 'Publish a single research observation promptly with ') + - 'theorem-os research-observe --worktree WORKTREE --finding FINDING_FILE [--probe LEAN_FILE] [--snapshot-sources]. Save the finding object shown above in the JSON file FINDING_FILE. Use --finding FILE with a JSON file path. From your worktree, replace this example finding:\n```sh\nmkdir -p .scratch\nprintf \'%s\\n\' \'{"conclusion":"inconclusive","summary":"The construction remains unresolved.","remainingObligations":["Establish the missing bound."]}\' > .scratch/finding.json\ntheorem-os research-observe --worktree "$PWD" --finding .scratch/finding.json\n```\nThis validates fields before appending the current assignment event. Probe files retain exact Lean code as advisory artifacts; include precise scope and check results in the finding, and use check-lean for actual local diagnostics. The host snapshots the event and independently verifies any later typed proof. Read the command result and COOPERATION.json.deliveryReceipts for corrections.\n' : ''; + 'Use research-observe from .scratch/theoremos-help.md for a substantive finding or unresolved gap. Save the finding object in .scratch/finding.json: {"summary":"exact argument and scope","conclusion":"inconclusive","remainingObligations":["precise unresolved inference"]}. Set needsDecision:true only if Lead must decide. Use --probe to retain a checked Lean probe, and read COOPERATION.json.deliveryReceipts for corrections. Ordinary findings share progress; return with RESEARCH.md to deliver an advisory assignment.\n' : ''; const gapRules = ['lead', 'task'].includes(action.kind) ? - 'Report gaps in research/progress JSON: mathematicalGap:{consumer:{taskId:"ORIGINAL_GOAL_ID",taskDigest:"EXACT_GOAL_DIGEST"},previousGap:"prior inference",reduced:"established result",remaining:"exact quantifiers, strength, nondegeneracy and uniformity needed",evidenceScope:"checked assumptions and scope",reconsiderWhen:["new inputs or evidence"]}. In a kind:"research" delivery, put mathematicalGap, blockers and lemmaRequests inside finding. lemmaRequests contains typed task objects; use [] when no exact contract is known. Use a visible kind:"goal" original consumer and its exact digest, not the assigned lemma or research task. Submit the complete object on every correction. Optional previousDeliveryId must be a mathematicalGaps[].deliveryId in COOPERATION.json for this goal; ordinary research delivery IDs are not prior gap references. If none exists, omit only previousDeliveryId and keep the required previousGap description. Read full reports in COOPERATION.json mathematicalGaps. Historical reports are advisory; review changed inputs. A weaker bound or renamed route does not establish the stronger gap; conditional checks establish sufficiency only.\n' : ''; + 'Report gaps in research/progress JSON: mathematicalGap:{consumer:{taskId:"ORIGINAL_GOAL_ID",taskDigest:"EXACT_GOAL_DIGEST"},previousGap:"prior inference",reduced:"established result",remaining:"exact quantifiers, strength, nondegeneracy and uniformity needed",evidenceScope:"checked assumptions and scope",reconsiderWhen:["new inputs or evidence"]}. Put mathematicalGap, blockers and lemmaRequests in the finding file passed to research-observe. lemmaRequests contains typed task objects; use [] when no exact contract is known. Use a visible kind:"goal" original consumer and its exact digest, not the assigned lemma or research task. Submit the complete object on every correction. Optional previousDeliveryId must be a mathematicalGaps[].deliveryId in COOPERATION.json for this goal; ordinary research delivery IDs are not prior gap references. If none exists, omit only previousDeliveryId and keep the required previousGap description. Read full reports in COOPERATION.json mathematicalGaps. Historical reports are advisory; review changed inputs. A weaker bound or renamed route does not establish the stronger gap; conditional checks establish sufficiency only.\n' : ''; const focusPacket = { goalTaskIds: continuation.goals.filter(goal => goal.status !== 'integrated' || goal.recordedProof !== 'checked').map(goal => goal.taskId), frontierTaskIds: boundedFrontier ? [...localFrontier] : [...focus.frontier], @@ -659,13 +650,11 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio 'Current assignments, contracts and feedback supply the exact runtime values; examples are placeholders.\n' + (action.kind === 'lead' ? 'Available worker responsibilities: ' + JSON.stringify(workers.map(({ id, role }) => ({ id, role }))) + `. Unspecified route maxConcurrent: ${defaultResearchRouteConcurrency(workers)}. Leave every Lean source unchanged.\n` : '') + - (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' + (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 + + : context.instructions + '\n' + (action.kind === 'lead' ? leadPlanToolInstruction : '') + initialPlanningRules + rules + helperRules + organizationRules + leadDeliveryRules + planRevisionRules + familyRules + feasibilityRules + earlyRouteRules + connectionRules + familyMemberRules + attemptRules + focusRules + gapRules + nextCheckProposal + 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' : '') + + (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 independently verifies the full candidate. Use reviewScope:"final-candidate" to send a specific question to the fixed Reviewer after the complete candidate passes the host check. 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' : '') + (action.kind === 'task' && ['research', 'sketch'].includes(action.task.kind) ? 'Before restoring a temporary Lean probe, retain its complete reusable code, namespace/context, exact declaration names and proposed consumer in a lean fence in worktree-root RESEARCH.md. A prose claim that Lean passed is not a recoverable proof. To report a successful local check explicitly, use leanChecks:[{status:"passed",path:"RESEARCH.md",declarations:["Qualified.name"]}] in the single JSON response and keep the complete code outside that JSON in a lean fence. The host binds retained artifacts to this problem, assignment and commit; every local check remains advisory until a separate typed host check passes.\n' : '') + routeRules + proposalRules + leadRouteRules + @@ -676,12 +665,6 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio 'COOPERATION.json contains scoped live peer work, findings, gaps and checked results; leave it and CONTEXT-MANIFEST.json unchanged. The manifest records included/omitted material and reasons. Exact mathematical interfaces and original assumptions are mandatory; retrieve full proof sources/context by immutable commit/path. ' + (action.kind === 'lead' ? 'Follow the publication protocol above: after a successful live publication, keep concise notes and return without repeating the graph; only a further substantive change requires another final plan response. ' : 'Replace old responses with one JSON object, plain or in a math/json fence. ') + 'The host manages versions, receipts and budgets and independently checks all original targets. Unproved dependencies and reviews remain advisory.\n' + - 'For human guidance actually delivered to you, report top-level guidanceDecisions:[{guidanceId:"DELIVERED_ID",status:"accepted"|"declined"|"needs-info",reason:"specific reason",evidenceRefs:[]}]. ' + - (action.kind === 'lead' ? 'Include these guidanceDecisions in the same plan log event or in the same RESEARCH.md plan object when returning an unpublished plan. After live publication, keep RESEARCH.md as concise route notes; put any later guidance-only metadata in the final response instead of writing a new JSON object to RESEARCH.md. ' : 'Include it in your normal JSON delivery or the single RESEARCH.md response. ') + - 'Optional evidenceRefs use {kind:"task",id:"TASK_ID",version:"EXACT_TASK_VERSION"}, {kind:"plan",version:"ACCEPTED_PLAN_VERSION"} or {kind:"edit",id:"APPLIED_HUMAN_EDIT_ID"}. ' + - (action.kind === 'lead' ? 'Answer undecided guidance before further searches: include the decision with the smallest useful plan publication or revision, then return. If the accepted plan needs no change, return the guidance-only metadata in the final response. Delegate unresolved searches as research tasks; if a missing premise prevents a decision, report needs-info with the exact question. A checkpoint or a delivery receipt does not answer the guidance. ' : '') + - 'After an initial decision, keep its status and reason and send additional evidenceRefs when later task, plan or applied-edit records become available; the host merges valid additions without dropping earlier references. ' + - 'The host checks delivery ownership, its task/plan scope and these references. A handling decision is advisory and never executes edits or supplies proof acceptance. Previously delivered notes and recorded decisions appear in COOPERATION.json.humanGuidance.\n' + sharing + roleText; const optional: ContextSection[] = [ ...(compilation.optional ?? []), @@ -692,23 +675,17 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio ]; const taskContinuation = action.kind === 'task' && !isFeasibilityReview(action.task) && !isFinalCandidateReview(action.task); const assignedNode = action.kind === 'task' ? cooperation.tasks.find(node => node.task.id === action.task.id) : undefined; - const taskReceipts = action.kind === 'task' ? cooperation.deliveryReceipts?.filter(receipt => - receipt.status === 'needs-correction' && receipt.workerId === action.assignment.workerId && receipt.taskId === action.task.id && - receipt.taskDigest === action.assignment.taskDigest && receipt.seedCommit === action.assignment.seedCommit && - receipt.assignmentKey === assignmentDeliveryFile(action.assignment) && receipt.environmentDigest === compilation.environmentDigest) ?? [] : []; + const taskReceipts = action.kind === 'task' + ? assignmentDeliveryReceipts(cooperation.deliveryReceipts, action.assignment, compilation.environmentDigest) + .filter(receipt => receipt.status === 'needs-correction') + : []; const receiptIndex: ContextSection[] = taskReceipts.length && action.kind === 'task' ? [{ id: 'assignment-receipt-index', kind: 'feedback', text: 'Pending assignment correction receipts (retrieve all before correcting deliveries):\n' + JSON.stringify({ file: 'COOPERATION.json', field: 'deliveryReceipts', count: taskReceipts.length, - digest: mathDigest(canonicalMathJson(taskReceipts)), - scope: { status: 'needs-correction', workerId: action.assignment.workerId, taskId: action.task.id, - taskDigest: action.assignment.taskDigest, seedCommit: action.assignment.seedCommit, - assignmentKey: assignmentDeliveryFile(action.assignment), environmentDigest: compilation.environmentDigest }, - retrieval: 'Read every matching deliveryReceipts row in worktree-root COOPERATION.json, in stored array order; require the count and ' + - 'SHA-256(canonicalMathJson(rows)) to match this index. Every pending receipt remains a correction obligation, including receipts ' + - 'not shown inline. Correct its issues and append a complete event with replacesReceipt set to its id; rejected corrections name the ' + - 'new receipt. If this live set changed or is unavailable, refresh the current receipts before correcting; never treat missing rows as resolved. ' + - 'These intake receipts grant no proof acceptance.', + status: 'needs-correction', + retrieval: 'Read every current needs-correction row in the assignment-scoped deliveryReceipts field. ' + + 'Fix its issues and rerun research-observe with replacesReceipt set to its id. If a correction is rejected, use the new receipt.', }), }] : []; const receiptDetails: ContextSection[] = taskReceipts.length ? [{ id: 'assignment-receipts', kind: 'feedback', priority: 0, @@ -736,22 +713,18 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio initialPlanning ? 'Continue the initial Lead responsibility in this saved thread. No task graph has been accepted; peers are waiting for the first published plan.' : 'Continue the current Lead responsibility in this saved thread. The original problem and unchanged task graph are already in its history.', - skillWorkflow ? '' : initialPlanning ? initialPlanningRules - : 'This turn is one planning decision: from the changes and task table below, revise the accepted graph or return it unchanged. Read COOPERATION.json only for the specific records you need, and delegate open searches as research tasks. Record the current argument and precise unresolved inference in worktree-root RESEARCH.md together with the decision.', + !initialPlanning ? 'Use the changes below to revise the accepted graph or return it unchanged. Save the current argument and unresolved inference in RESEARCH.md.' : '', 'Current cooperative assignment (replaces every previous dispatch nonce and receipt):\n' + JSON.stringify(action), - skillWorkflow ? 'Current delivery log: ' + leadPlanDeliveryFile(action) : '', + leadPlanDeliveryFile(action) ? 'Use plan-apply --publish from the Lead tool help when the plan is ready for peers.' : '', leadInboxText, leadTaskTable(cooperation), 'Current host work contract:\n' + JSON.stringify(workContract), gapContext, - nextCheckContext, skillWorkflow ? '' : nextCheckRules, + nextCheckContext, planningEvidence ? leadPlanningEvidenceText(planningEvidence) : '', compilation.feedback ? 'Current host feedback:\n' + compilation.feedback : '', leadPlanPublicationFeedback(action, cooperation), contextCheckpointRejectionFeedback(cooperation.contextCheckpointRejection, leadPlanDeliveryFile(action)), - ...(skillWorkflow ? [] : [checkpointRules, mathematicalInterfaceRules, inheritedFindingRules, toolGuidance, - leadDeliveryRules, planRevisionRules, sharing, proposalRules, - 'Review new findings and proposals, then publish a useful plan or revision promptly; retain the exact mathematical gap if it is unresolved. A checkpoint, unchanged control plan, or activity report does not establish decision progress or proof acceptance.']), ].filter(Boolean).join('\n\n') : taskContinuation ? [ 'Continue the current task responsibility in this saved thread. Its frozen problem, exact interfaces, and unchanged source rules are already in the thread history.', 'Current cooperative assignment:\n' + JSON.stringify(action), @@ -759,18 +732,13 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio 'Current host work contract:\n' + JSON.stringify(workContract), gapContext, nextCheckContext, progressCheckContext, - ...(skillWorkflow ? [] : [nextCheckRules, observationRules, canonicalProbeRules, mathematicalInterfaceRules, inheritedFindingRules, toolGuidance]), + canonicalProbeRules, compilation.feedback ? 'Current host feedback:\n' + compilation.feedback : '', contextCheckpointRejectionFeedback(cooperation.contextCheckpointRejection, action.kind === 'task' ? assignmentDeliveryFile(action.assignment) : undefined), assignedNode?.feedback ? 'Current task feedback:\n' + assignedNode.feedback : '', 'Current scoped inbox references (retrieve full records before using them):\n' + JSON.stringify(taskInbox), - skillWorkflow ? '' : 'Read the latest worktree-root COOPERATION.json before continuing. Inspect referenced deliveries, mathematicalGaps, blockers, peers and their saved source references for new scoped input. A matching task digest does not mean its feedback or inbox is unchanged. Missing or unavailable referenced evidence supplies no premise.', - skillWorkflow ? '' : 'Correct every needs-correction receipt by appending a new complete event to ' + - (action.kind === 'task' ? assignmentDeliveryFile(action.assignment) : '') + - '; include replacesReceipt with the receipt id inside the corrected finding, and preserve the log and earlier valid work. If a correction is rejected again, replace its new receipt; acceptance resolves its verified chain of attempts, while independent rejected submissions still require their own corrections. Read RESEARCH.md and resume the saved argument, exact unresolved inference and retry trigger. Do not repeat an unchanged negative search without new input or a different mathematical method.', - ...(skillWorkflow ? [] : ['Save useful progress and use the current assignment delivery protocol. A progress report, retained draft or intake receipt is advisory; only independent host checking can establish proof acceptance.', - proofDeliverableRules, researchSourcesRules, sharing]), + 'Resume the saved argument from RESEARCH.md. Read the relevant new records in COOPERATION.json.', ].filter(Boolean).join('\n\n') : undefined; const leadDecision = action.kind === 'lead' && cooperation.leadDecisionInstruction ? { id: 'lead-decision-requirements', kind: 'assignment' as const, @@ -809,7 +777,7 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio const continuationOptional = (compilation.optional ?? []).filter(section => section.kind === 'feedback' || currentLibraryHint(section)); const helperIndex = landedHelperSection(cooperation); const compileContinuation = (checkpointInstruction?: string) => compileContextSections({ instructions, - mandatory: [...dispatchPrefix(checkpointInstruction), ...(leadDecision ? [leadDecision] : []), + mandatory: [...dispatchPrefix(checkpointInstruction), ...cooperativeResponseSections(cooperation, action), ...(leadDecision ? [leadDecision] : []), { id: 'same-thread-continuation', kind: 'continuation', text: continuationText! }, ...(researchInputs ? [researchInputs] : []), ...(planRejection ? [planRejection] : []), ...(helperIndex ? [helperIndex] : []), ...receiptIndex], diff --git a/src/solver/modules/contracts.ts b/src/solver/modules/contracts.ts index 4a89c005..f388c889 100644 --- a/src/solver/modules/contracts.ts +++ b/src/solver/modules/contracts.ts @@ -2,39 +2,6 @@ import { isAdvisoryTask, isFeasibilityReview, taskVersion, type CooperativeActio import { contextTaskConsumers, type TaskConsumerContext } from '../taskConsumers'; import { researchSourceContract } from '../researchReferences'; -/** A route-changing claim needs an application check, not just declaration lookup. */ -export const criticalInferenceGuidance = 'For a new construction interface or a reduction that claims a core obligation is vacuous, ' + - 'identically zero or automatic, first isolate the decisive inference and unfold the actual definitions and argument positions. ' + - 'Check inferred structures and one discriminating small or boundary instance in the pinned environment before expanding the route. ' + - 'Retain the exact Lean probe, assumptions and actual result. #check establishes only a declaration name and type; ' + - 'type elaboration does not establish inhabitation, and an argument copied from peer notes is still unverified. ' + - 'A failed tactic is inconclusive; report refuted only with a scoped counterexample or invalid inference and evidence. ' + - 'Refuting an argument does not prove its claimed statement or the original theorem false. ' + - 'Publish decisive negative evidence promptly so Lead can revise the contract or request an independent check. '; - -const finiteWorkGuidance = 'A finite range of target values is not an enumerable proof task while it still quantifies over an infinite family of objects. ' + - 'State the finite reduction or a uniform argument before proposing enumeration.'; -const planningDeliveryGuidance = 'For each new parallel task, use objective to state its distinct scope relative to in-flight work, ' + - 'a concrete first construction, proof step or discriminating check, and the intended consumer with its application. ' + - 'Use the existing type and dependsOn fields for exact proof interfaces and actual inputs. ' + - 'For an uncertain route, record its hardest premise, the first discriminating feasibility check and what remains after the nearest consumer application. ' + - 'Connect an executable local package through actual consumer dependencies or proofRoutes; if its connection is unknown, keep it as exploration with the precise missing bridge. ' + - 'Changing the bound or restating an unresolved theorem does not supply a new method. ' + - 'When a helper or glue step is implementable from available inputs, publish a typed lemma or original-goal proof task promptly; ' + - 'give the Engineer executable proof work instead of repeatedly assigning the same research. ' + - 'Keep unresolved mathematical questions as scoped research; no task is required merely to occupy an idle worker. ' + - criticalInferenceGuidance + finiteWorkGuidance; -const researchDeliveryGuidance = 'As soon as a useful helper or glue step has an exact interface and a concrete implementation method, ' + - 'publish it promptly in lemmaRequests with a full closed Lean type and actual typed input dependencies. ' + - 'When using a source, save sourceUses with its kind, exact reference and locator, full assumptions, definition adaptation, ' + - 'visible consumer taskId/taskDigest, related lemmaRequestIds and remaining premises. Search the installed catalog before requesting a new dependency. ' + - 'In its objective, state the distinct scope, first construction or Lean step, and intended consumer with the application back to it. ' + - 'Name the nearest consumer task/declaration and its remaining premises; include the typed glue consumer as a sibling lemmaRequest when that step is implementable. ' + - 'Record the known typed inputs and consumers; an unrecorded consumer is a question for Lead, not an invented proof edge. ' + - 'Retain reusable Lean probe code in RESEARCH.md and request a Lead decision; do not keep researching an already implementable step. ' + - 'If the method is still unknown, report the precise missing inference instead of presenting another form of the same gap as ready proof work. ' + - criticalInferenceGuidance + finiteWorkGuidance + ' Proposals remain advisory and require a separate proof assignment and independent checking.'; - /** One work product per dispatch; worker slots and mathematical responsibilities are separate. */ export function cooperativeWorkContract(action: CooperativeAction, tasks: readonly TaskRecord[], context: TaskConsumerContext = {}) { const exploration = action.kind === 'task' ? tasks.find(node => node.task.id === action.task.id)?.capacityExploration : undefined; @@ -44,18 +11,15 @@ export function cooperativeWorkContract(action: CooperativeAction, tasks: readon action.kind === 'assemble' ? 'integration' : action.kind; const products = { 'route-planning': { owner: 'lead', output: 'validated-task-graph', - consumer: 'M3-ready-selection-and-M5-assignment', acceptance: 'host-plan-validation', sourcePolicy: 'host-checks-any-source-repair', - deliveryGuidance: planningDeliveryGuidance }, + consumer: 'M3-ready-selection-and-M5-assignment', acceptance: 'host-plan-validation', sourcePolicy: 'host-checks-any-source-repair' }, investigation: { owner: 'researcher', output: 'advisory-finding-retained-code-and-exact-lemma-proposals', - consumer: 'lead-plan-decision', acceptance: 'advisory-only', sourcePolicy: 'read-only', deliveryGuidance: researchDeliveryGuidance }, + consumer: 'lead-plan-decision', acceptance: 'advisory-only', sourcePolicy: 'read-only' }, 'capacity-exploration': { owner: 'idle-proof-or-research-worker', output: 'distinct-frontier-finding-retained-lean-probe-and-exact-interface', - consumer: 'target-owner-and-lead-plan-decision', acceptance: 'advisory-only', sourcePolicy: 'read-only', deliveryGuidance: researchDeliveryGuidance }, + consumer: 'target-owner-and-lead-plan-decision', acceptance: 'advisory-only', sourcePolicy: 'read-only' }, 'feasibility-review': { owner: 'independent-researcher', output: 'core-inference-risk-and-discriminating-evidence', - consumer: 'lead-route-decision', acceptance: 'advisory-only', sourcePolicy: 'read-only', - deliveryGuidance: criticalInferenceGuidance }, + consumer: 'lead-route-decision', acceptance: 'advisory-only', sourcePolicy: 'read-only' }, 'formal-proof': { owner: 'proof-worker', output: 'saved-exact-typed-declaration', - consumer: 'M2-then-canonical-integration', acceptance: 'independent-exact-source-check', sourcePolicy: 'owned-proof-sources', - deliveryGuidance: criticalInferenceGuidance }, + consumer: 'M2-then-canonical-integration', acceptance: 'independent-exact-source-check', sourcePolicy: 'owned-proof-sources' }, 'consumer-connection': { owner: 'proof-worker', output: 'consumer-proof-from-fixed-typed-inputs', consumer: 'M2-then-input-proofs-and-unconditional-integration', acceptance: 'conditional-check-only', sourcePolicy: 'owned-proof-sources' }, integration: { owner: 'host', output: 'fixed-original-proof-check', diff --git a/src/solver/modules/moduleIdentity.ts b/src/solver/modules/moduleIdentity.ts index 0d9f2015..2219fa1d 100644 --- a/src/solver/modules/moduleIdentity.ts +++ b/src/solver/modules/moduleIdentity.ts @@ -9,9 +9,9 @@ export const directSolverModuleIdentity: SolverModuleIdentity = { versions: { M1: 'bounded-codex-turn-v15/distinct-recovery-delivery-v1/provider-diagnostics-v1/saved-plan-recovery-v1/closed-writer-ownership-v1/advisory-draft-recovery-v1/session-admission-v1/closed-statement-ownership-v1/feasibility-session-v1/observed-turn-ledger-v1/session-scoped-usage-v1/persistent-provider-cooldown-v1/context-overflow-recovery-v1/initial-planning-budget-v1/trusted-local-stop-v1/initial-plan-publication-v1/observed-knowledge-use-v1/diagnostic-log-ownership-v1/turn-ledger-removed-v1/advisory-scratch-ownership-v1/durable-reasoning-checkpoint-v1/lead-thread-continuation-v1/bounded-coordination-checkpoints-v1/live-saved-context-yield-v1/published-context-checkpoint-v1/compaction-aware-checkpoints-v1/cooperative-stray-quarantine-v1/bounded-proof-search-v1/installed-library-before-model-v1/installed-library-reference-observation-v1/agent-library-request-v1/context-proof-ready-handoff-v1/scoped-research-save-notice-v1/early-initial-plan-notice-v1/scoped-advisory-backoff-v1/conditional-connection-checkpoints-v1/sent-responsibility-context-v1/checkpoint-research-handoff-v1/durable-research-handoff-wait-v1/retained-notes-attribution-v1/feasibility-notice-only-handoff-v1/host-library-before-research-v1/final-review-checkpoint-v1', M2: 'lean-kernel-v14/declaration-prefix-projection-v1/task-root-references-v1/conditional-child-changes-v1/scoped-conditional-projection-v1/exact-input-failure-reuse-v1/conditional-projection-identity-v1/attributed-batch-evidence-v1/fixed-candidate-references-v1/exact-projection-cache-v1/shared-source-index-v1/host-consumer-connection-v1/content-projection-reuse-v1/ready-integration-batches-v1/coded-lean-diagnostics-v1/live-exact-projection-recheck-v1/lean-diagnostic-word-classification-v1/advisory-scratch-checkout-v1/host-tactic-battery-v1/definition-tasks-v1/battery-vacuity-probe-v1/untouched-seed-request-failure-v1/isolated-module-builds-v1/frozen-library-modules-v1/host-family-assembly-v1/projection-dependency-diagnostics-v1/installed-library-application-v1/installed-library-candidate-pool-v1/installed-library-iff-application-v1/installed-library-equality-application-v1/installed-library-named-requests-v1/installed-library-rewrite-v1/installed-library-lemma-pool-v1/installed-library-premise-application-v1/installed-library-premise-retrieval-v1/installed-library-fair-premise-pool-v1/installed-library-composed-applications-v1/import-closure-diagnostics-cache-v1/proof-import-before-theorem-v1/typed-helper-command-rejection-v1/installed-library-conclusion-relevance-v1/notation-source-inputs-v1/implicit-instance-cleanup-v1/persistent-tactic-failure-reuse-v1/notation-quotation-context-v1/static-notation-analysis-v1/conditional-source-context-v1/universe-polymorphic-conditional-projection-v1/original-definition-kind-canonical-check-v1/conditional-lemma-macro-normalization-v1', - M3: 'route-budget-v12/blocker-or-routes-v1/structured-provider-failure-v1/assignable-work-v1/advisory-settlement-v3/goal-scoped-advancement-v1/early-route-checks-v1/ready-consumers-v1/evidence-ranked-routes-v2/capacity-free-ranking-v1/active-or-frontier-v1/context-overflow-recovery-v1/pending-validation-v1/trusted-local-stop-v1/host-consumer-connection-v1/definition-task-readiness-v1/scoped-next-checks-v1/yielded-advisory-proof-frontier-v1/consumer-goal-attribution-v1', - M4: 'task-interface-context-v31/original-goal-frontier-v3/finished-objective-refs-v1/work-contract-v2/research-handoff-batches-v3/resume-drafts-v1/assignment-knowledge-hints-v1/deferred-handoff-inputs-v1/mathematical-route-planning-v1/complete-research-findings-v1/consumer-interfaces-v1/current-feedback-v1/complete-checkpoints-v1/early-feasibility-v1/parallel-questions-v2/local-attempt-feedback-v1/compact-handoff-sources-v1/exact-interface-diversity-v1/bounded-route-focus-v1/compact-inline-manifest-v1/adopted-research-use-v1/bounded-knowledge-metadata-v1/interface-idf-v1/overflow-optional-budget-v1/initial-planning-budget-v1/required-research-challenges-v1/initial-plan-publication-v1/scoped-route-findings-v1/observed-knowledge-use-v1/lean-json-diagnostics-v1/host-consumer-connection-v1/finite-boolean-evidence-v1/live-research-publication-v1/current-residual-goal-v1/continuation-attachments-v1/accepted-consumer-knowledge-v1/single-delivery-protocol-v1/route-focused-knowledge-v1/independent-goal-knowledge-batch-v1/route-finding-batch-v1/primary-led-removed-v1/assigned-proof-only-diagnostics-v1/lean-prover-v1/host-capacity-exploration-v1/explicit-handoff-publication-v1/advisory-scratch-roots-v1/exact-gap-checkpoint-context-v1/lead-continuation-context-v1/shared-new-helper-ownership-v1/compact-proof-role-context-v1/precise-gap-correction-context-v1/full-plan-adoption-context-v1/coordination-first-context-v1/explicit-research-source-context-v1/short-challenge-assessments-v1/live-plan-rejection-feedback-v1/request-scoped-checkpoint-feedback-v1/worker-checkpoint-feedback-v1/lead-planning-inputs-v1/plan-revision-context-v1/lead-inbox-context-v1/definition-task-context-v1/reference-search-context-v1/definition-knowledge-context-v1/math-tools-context-v1/kernel-certificates-v1/goal-path-review-v1/blueprint-fields-v1/theory-modules-v1/definition-sanity-lemmas-v1/goal-path-decisions-context-v1/owned-declaration-index-v1/library-packs-v1/task-families-v1/team-progress-review-context-v1/source-dependency-review-context-v1/atomic-observations-and-application-hints-v1/scoped-relation-pool-v1/executable-next-check-v1/proof-search-context-v1/installed-library-retrieval-v1/installed-library-application-context-v1/reusable-knowledge-index-v1/installed-library-named-requests-v1/conclusion-focused-knowledge-v1/agent-full-library-context-v1/critical-premise-context-v1/executable-initial-plan-context-v1/bounded-owned-declaration-lookup-v1/continuation-query-batches-v1/critical-inference-guidance-v1/plan-connection-guidance-v1/warm-lead-plan-rejection-v1/host-library-context-revalidation-v1/knowledge-candidate-refill-v1/mathematical-knowledge-ranking-v1/scoped-finding-relevance-v1/decorated-quantifier-fallback-v1/bounded-mathematical-reference-recall-v1/review-independence-context-v1', - M5: 'route-cooperation-v33/persistent-failed-input-v1/continuous-frontier-input-v1/research-handoff-batches-v3/assignable-work-v1/resumable-lead-drafts-v1/assignment-deliveries-v1/scoped-research-drafts-v1/review-dispatches-v1/recoverable-delivery-cursors-v1/recoverable-human-edits-v1/recoverable-proof-integration-v1/deferred-handoff-reactivation-v1/concurrent-frontier-recovery-v1/complete-research-findings-v1/consumer-interface-projection-v1/independent-feasibility-v1/ranked-assignment-v1/local-checkpoint-evidence-v1/stable-handoff-inputs-v1/local-attempt-identity-v1/exact-inflight-questions-v1/description-source-recheck-v1/conditional-restore-v1/live-capacity-exploration-v1/snapshot-statement-review-reuse-v1/concurrent-merged-check-v1/adopted-research-use-v1/fixed-candidate-statement-scope-v1/semantic-dependency-review-v1/nonblocking-plan-validation-v1/exact-projection-cache-v1/required-research-challenges-v1/initial-plan-publication-v1/observed-knowledge-use-v1/host-consumer-connection-v1/live-research-publication-v1/typed-helper-preflight-v1/stale-preflight-cancellation-v1/type-projection-preflight-reuse-v1/stale-plan-recheck-stop-v1/shared-statement-preparation-v1/scoped-statement-types-v1/empty-route-list-v1/route-evidence-obligations-v1/primary-led-removed-v1/source-contract-local-repair-v1/unlimited-dispatch-recovery-v1/assignment-condition-snapshot-v1/conditional-dependency-order-v1/original-goal-capacity-coverage-v1/assigned-source-diagnostic-preflight-v1/current-batch-projection-v1/stalled-plan-continuous-recovery-v1/actual-dependency-invalidation-v1/lean-prover-v1/host-capacity-exploration-v1/explicit-handoff-publication-v1/semantic-lead-checkpoints-v1/continuation-handoff-provenance-v1/advisory-stagnation-recovery-v1/explicit-mathematical-gap-recovery-v1/shared-responsibility-assessment-v1/recorded-dispatch-waits-v1/full-plan-explicit-adoption-v1/scoped-delivery-correction-chain-v1/legacy-research-without-finding-v1/research-source-snapshots-v1/source-bound-mathematical-gap-v1/large-delivery-lines-v1/executable-work-assessment-v1/lead-planning-only-v1/plan-revision-patches-v1/lead-inbox-v1/stopped-worker-release-v1/definition-task-dependencies-v1/goal-path-stall-wake-v1/goal-path-answer-coverage-v1/substantive-goal-path-decisions-v1/source-dependency-connect-v1/active-goal-progress-review-v1/executable-goal-review-v1/host-search-checkpoint-v1/executable-next-check-v1/installed-library-dispatch-v1/ascii-forall-statement-shapes-v1/missing-declaration-environment-stability-v1/fresh-goal-progress-v1/missing-research-delivery-recovery-v1/superseded-reservation-release-v1/reseeded-connection-permission-v1/question-bound-advisory-blockers-v1/plan-helper-type-contract-v1/library-probe-advisory-feedback-v1/conditional-research-screening-v1/typed-connection-draft-resume-v1/task-draft-continuation-v1/checkpoint-research-handoff-v1/canonical-dependency-snapshots-v1/verified-canonical-publication-v1/saved-research-transfer-v1/retained-notes-attribution-v1/host-definition-contract-checks-v1/negative-outcome-decisions-v1/definite-type-parser-errors-v1/retained-source-input-discovery-isolation-v1/source-bound-feasibility-drafts-v1/lead-plan-rejection-inbox-v1/checkpointed-connection-prerequisite-yield-v1/fresh-conditional-continuation-reuse-v1/frozen-import-preflight-v1/successor-checked-proof-handoff-v1/final-review-priority-v1/consumer-finding-notice-v1', + M3: 'route-budget-v12/blocker-or-routes-v1/structured-provider-failure-v1/assignable-work-v1/advisory-settlement-v3/goal-scoped-advancement-v1/early-route-checks-v1/ready-consumers-v1/evidence-ranked-routes-v2/capacity-free-ranking-v1/active-or-frontier-v1/context-overflow-recovery-v1/pending-validation-v1/trusted-local-stop-v1/host-consumer-connection-v1/definition-task-readiness-v1/scoped-next-checks-v1/yielded-advisory-proof-frontier-v1/consumer-goal-attribution-v1/fixed-review-requests-v1', + M4: 'task-interface-context-v31/original-goal-frontier-v3/finished-objective-refs-v1/work-contract-v2/research-handoff-batches-v3/resume-drafts-v1/assignment-knowledge-hints-v1/deferred-handoff-inputs-v1/mathematical-route-planning-v1/complete-research-findings-v1/consumer-interfaces-v1/current-feedback-v1/complete-checkpoints-v1/early-feasibility-v1/parallel-questions-v2/local-attempt-feedback-v1/compact-handoff-sources-v1/exact-interface-diversity-v1/bounded-route-focus-v1/compact-inline-manifest-v1/adopted-research-use-v1/bounded-knowledge-metadata-v1/interface-idf-v1/overflow-optional-budget-v1/initial-planning-budget-v1/required-research-challenges-v1/initial-plan-publication-v1/scoped-route-findings-v1/observed-knowledge-use-v1/lean-json-diagnostics-v1/host-consumer-connection-v1/finite-boolean-evidence-v1/live-research-publication-v1/current-residual-goal-v1/continuation-attachments-v1/accepted-consumer-knowledge-v1/single-delivery-protocol-v1/route-focused-knowledge-v1/independent-goal-knowledge-batch-v1/route-finding-batch-v1/primary-led-removed-v1/assigned-proof-only-diagnostics-v1/lean-prover-v1/host-capacity-exploration-v1/explicit-handoff-publication-v1/advisory-scratch-roots-v1/exact-gap-checkpoint-context-v1/lead-continuation-context-v1/shared-new-helper-ownership-v1/compact-proof-role-context-v1/precise-gap-correction-context-v1/full-plan-adoption-context-v1/coordination-first-context-v1/explicit-research-source-context-v1/short-challenge-assessments-v1/live-plan-rejection-feedback-v1/request-scoped-checkpoint-feedback-v1/worker-checkpoint-feedback-v1/lead-planning-inputs-v1/plan-revision-context-v1/lead-inbox-context-v1/definition-task-context-v1/reference-search-context-v1/definition-knowledge-context-v1/math-tools-context-v1/kernel-certificates-v1/goal-path-review-v1/blueprint-fields-v1/theory-modules-v1/definition-sanity-lemmas-v1/goal-path-decisions-context-v1/owned-declaration-index-v1/library-packs-v1/task-families-v1/team-progress-review-context-v1/source-dependency-review-context-v1/atomic-observations-and-application-hints-v1/scoped-relation-pool-v1/executable-next-check-v1/proof-search-context-v1/installed-library-retrieval-v1/installed-library-application-context-v1/reusable-knowledge-index-v1/installed-library-named-requests-v1/conclusion-focused-knowledge-v1/agent-full-library-context-v1/critical-premise-context-v1/executable-initial-plan-context-v1/bounded-owned-declaration-lookup-v1/continuation-query-batches-v1/critical-inference-guidance-v1/plan-connection-guidance-v1/warm-lead-plan-rejection-v1/host-library-context-revalidation-v1/knowledge-candidate-refill-v1/mathematical-knowledge-ranking-v1/scoped-finding-relevance-v1/decorated-quantifier-fallback-v1/bounded-mathematical-reference-recall-v1/review-independence-context-v1/optional-final-review-context-v1/fixed-review-questions-v1', + M5: 'route-cooperation-v33/persistent-failed-input-v1/continuous-frontier-input-v1/research-handoff-batches-v3/assignable-work-v1/resumable-lead-drafts-v1/assignment-deliveries-v1/scoped-research-drafts-v1/review-dispatches-v1/recoverable-delivery-cursors-v1/recoverable-human-edits-v1/recoverable-proof-integration-v1/deferred-handoff-reactivation-v1/concurrent-frontier-recovery-v1/complete-research-findings-v1/consumer-interface-projection-v1/independent-feasibility-v1/ranked-assignment-v1/local-checkpoint-evidence-v1/stable-handoff-inputs-v1/local-attempt-identity-v1/exact-inflight-questions-v1/description-source-recheck-v1/conditional-restore-v1/live-capacity-exploration-v1/snapshot-statement-review-reuse-v1/concurrent-merged-check-v1/adopted-research-use-v1/fixed-candidate-statement-scope-v1/semantic-dependency-review-v1/nonblocking-plan-validation-v1/exact-projection-cache-v1/required-research-challenges-v1/initial-plan-publication-v1/observed-knowledge-use-v1/host-consumer-connection-v1/live-research-publication-v1/typed-helper-preflight-v1/stale-preflight-cancellation-v1/type-projection-preflight-reuse-v1/stale-plan-recheck-stop-v1/shared-statement-preparation-v1/scoped-statement-types-v1/empty-route-list-v1/route-evidence-obligations-v1/primary-led-removed-v1/source-contract-local-repair-v1/unlimited-dispatch-recovery-v1/assignment-condition-snapshot-v1/conditional-dependency-order-v1/original-goal-capacity-coverage-v1/assigned-source-diagnostic-preflight-v1/current-batch-projection-v1/stalled-plan-continuous-recovery-v1/actual-dependency-invalidation-v1/lean-prover-v1/host-capacity-exploration-v1/explicit-handoff-publication-v1/semantic-lead-checkpoints-v1/continuation-handoff-provenance-v1/advisory-stagnation-recovery-v1/explicit-mathematical-gap-recovery-v1/shared-responsibility-assessment-v1/recorded-dispatch-waits-v1/full-plan-explicit-adoption-v1/scoped-delivery-correction-chain-v1/legacy-research-without-finding-v1/research-source-snapshots-v1/source-bound-mathematical-gap-v1/large-delivery-lines-v1/executable-work-assessment-v1/lead-planning-only-v1/plan-revision-patches-v1/lead-inbox-v1/stopped-worker-release-v1/definition-task-dependencies-v1/goal-path-stall-wake-v1/goal-path-answer-coverage-v1/substantive-goal-path-decisions-v1/source-dependency-connect-v1/active-goal-progress-review-v1/executable-goal-review-v1/host-search-checkpoint-v1/executable-next-check-v1/installed-library-dispatch-v1/ascii-forall-statement-shapes-v1/missing-declaration-environment-stability-v1/fresh-goal-progress-v1/missing-research-delivery-recovery-v1/superseded-reservation-release-v1/reseeded-connection-permission-v1/question-bound-advisory-blockers-v1/plan-helper-type-contract-v1/library-probe-advisory-feedback-v1/conditional-research-screening-v1/typed-connection-draft-resume-v1/task-draft-continuation-v1/checkpoint-research-handoff-v1/canonical-dependency-snapshots-v1/verified-canonical-publication-v1/saved-research-transfer-v1/retained-notes-attribution-v1/host-definition-contract-checks-v1/negative-outcome-decisions-v1/definite-type-parser-errors-v1/retained-source-input-discovery-isolation-v1/source-bound-feasibility-drafts-v1/lead-plan-rejection-inbox-v1/checkpointed-connection-prerequisite-yield-v1/fresh-conditional-continuation-reuse-v1/frozen-import-preflight-v1/successor-checked-proof-handoff-v1/final-review-priority-v1/optional-final-review-v1/consumer-finding-notice-v1/fixed-review-requests-v1', }, }; diff --git a/src/solver/modules/organization.ts b/src/solver/modules/organization.ts index 141a7452..9a4c24fd 100644 --- a/src/solver/modules/organization.ts +++ b/src/solver/modules/organization.ts @@ -31,6 +31,23 @@ export function researchWorkerCanNode(worker: Pick[]): void { + const byId = new Map(workers.map(worker => [worker.id, worker])); + const previousById = new Map(previous.map(node => [node.task.id, node])); + for (const task of plan.tasks) { + const ownerId = task.ownerId ?? task.preferredOwnerId; + if (!ownerId) continue; + const owner = byId.get(ownerId), node = previousById.get(task.id); + const ownershipTask = node?.capacityExploration ? { ...task, status: 'active' as const } : task; + if (!owner || !researchWorkerCanNode(owner, { ...(node ?? { status: 'pending', attempts: 0 }), task: ownershipTask })) + throw new Error('math_plan_task_owner_unavailable'); + } + for (const group of plan.groups) if (group.engineerId && byId.get(group.engineerId)?.role !== 'engineer') + throw new Error('math_plan_group_engineer_unavailable'); +} + export function researchTaskRole(task: CooperativeTask): ResearchRole { return isFeasibilityReview(task) ? 'reviewer' : task.kind === 'goal' ? 'engineer' : task.kind === 'lemma' ? 'prover' : 'researcher'; } diff --git a/src/solver/modules/search.ts b/src/solver/modules/search.ts index 164deae7..409a5214 100644 --- a/src/solver/modules/search.ts +++ b/src/solver/modules/search.ts @@ -7,7 +7,7 @@ import { proofRouteReady, type ProofRoute } from '../proofRoutes'; import { createRecordedTaskSettlement } from '../progress'; import { createProofRoutePriority } from '../routePriority'; import { automaticTaskConnection, freshTaskConnection } from '../taskConnections'; -import { allRoutesParked, assumableLemma, checkedUnconditionally, freshlyAccepted, groupOpen, isAdvisoryTask, isFeasibilityReview, isFinalCandidateReview, +import { allRoutesParked, assumableLemma, checkedUnconditionally, groupOpen, isAdvisoryTask, isFeasibilityReview, isFinalCandidateReview, openRoutes, taskGroup, taskReferenceDependencies, taskVersion, type TaskRecord, type RouteRecord, type CooperativeAction } from '../tasks'; export type ResearchBudget = Readonly<{ maxTurns: number; remainingMs: number; aborted: boolean }>; @@ -27,12 +27,6 @@ export function routeAllowsTask(task: TaskRecord['task'], tasks: readonly TaskRe (route.busy ?? tasks.filter(node => node.status === 'running' && taskGroup(node.task) === route.group.id).length) < (route.group.maxConcurrent ?? 3); } -/** Advisory final review still needs a complete, freshly accepted original candidate. */ -export function finalCandidateReviewReady(tasks: readonly TaskRecord[]): boolean { - const goals = tasks.filter(node => node.task.kind === 'goal'); - return goals.length > 0 && goals.every(node => !node.pendingValidation && freshlyAccepted(node, taskVersion(node.task))); -} - function dispatchRouteReady(route: ProofRoute, tasks: readonly TaskRecord[]) { if (!proofRouteReady(route, tasks)) return false; const nodes = new Map(tasks.map(node => [node.task.id, node])), visited = new Set(); @@ -119,11 +113,11 @@ function taskReadiness(tasks: readonly TaskRecord[], groups?: readonly RouteReco return ready; }; const canStart = (task: TaskRecord['task']): boolean => { + if (isFinalCandidateReview(task)) return false; // These are requests for the fixed-candidate Reviewer. const node = nodes.get(task.id); if (node?.pendingValidation || node?.alternativeRoutes?.length && !openRoutes(node).some(route => dispatchRouteReady(route, tasks))) return false; - return isFinalCandidateReview(task) ? finalCandidateReviewReady(tasks) && dependenciesReady(task) - : ['research', 'sketch'].includes(task.kind) || dependenciesReady(task) || - Boolean((task.conditional || automaticTaskConnection(task, tasks, groups)) && task.dependsOn.every(dependencyAvailable)); + return isAdvisoryTask(task) || dependenciesReady(task) || + Boolean((task.conditional || automaticTaskConnection(task, tasks, groups)) && task.dependsOn.every(dependencyAvailable)); }; return { dependenciesReady, canStart }; } @@ -233,6 +227,7 @@ export function goalsFirstResearchTasks(tasks: readonly TaskRecord[], groups?: r /** Unit-cost dependency depth is a scheduling heuristic, not a proof-time estimate. */ export function criticalPathResearchTasks(tasks: readonly TaskRecord[], groups?: readonly RouteRecord[]): TaskRecord[] { const unfinished = new Map(tasks.filter(node => !['integrated', 'completed'].includes(node.status) && + !isFinalCandidateReview(node.task) && (node.task.status ?? 'active') === 'active' && (!groups || groupOpen(groups.find(record => record.group.id === taskGroup(node.task))))) .map(node => [node.task.id, node])); const consumers = new Map(); @@ -398,8 +393,7 @@ export function researchCanAdvance(tasks: readonly TaskRecord[], groups: readonl if (memo.has(id)) return memo.get(id)!; memo.set(id, false); const node = nodes.get(id); - if (!node || node.status === 'blocked') return false; - if (isFinalCandidateReview(node.task) && !finalCandidateReviewReady(tasks)) return false; + if (!node || node.status === 'blocked' || isFinalCandidateReview(node.task)) return false; if (node.status === 'completed' && isAdvisoryTask(node.task)) { const ready = node.task.dependsOn.every(visit); memo.set(id, ready); return ready; diff --git a/src/solver/planTool.ts b/src/solver/planTool.ts index c32ae892..0e5fa2f3 100644 --- a/src/solver/planTool.ts +++ b/src/solver/planTool.ts @@ -2,8 +2,8 @@ import fs from 'node:fs'; import path from 'node:path'; import { canonicalMathJson, mathDigest, readMathText, writeMathTextDurable } from '../math/mathRuntimeIo'; import { assertMathCanonicalPath } from '../math/paths'; -import { parseLeadPlan } from './cooperationShared'; -import { isPlanFence, MAX_RESEARCH_NOTES_BYTES, parseMathResponse } from './deliveries'; +import { leadPlanPublicationTarget, parseLeadPlan } from './cooperationShared'; +import { appendDeliveryEvent, MAX_RESEARCH_NOTES_BYTES, parseMathResponse, replacePlanInNotes } from './deliveries'; import type { GoalPathReview } from './goalPathReview'; import { invalidPlanField, PlanValidationError, type PlanIssue } from './planDiagnostics'; import { liftNestedPlanPatch, type PlanPatchBase } from './planPatch'; @@ -11,7 +11,8 @@ import { readSolverProblem } from './problem'; import type { CooperationPlanProblem } from './tasks'; /** Lead-only snapshot. The running host still validates every proposal against live state. */ -export type PlanToolContext = { problem: CooperationPlanProblem; base?: PlanPatchBase; goalPath?: GoalPathReview }; +export type PlanToolContext = { problem: CooperationPlanProblem; base?: PlanPatchBase; goalPath?: GoalPathReview; + publication?: ReturnType }; type PlanValidation = { ok: true; planVersion: string; baseVersion?: string; summary: string; tasksCount: number; groupsCount: number; retireRoutesCount: number }; type PlanFailure = { ok: false; error: string; issues: PlanIssue[] }; @@ -81,19 +82,29 @@ export function validateCooperationPlanFile(input: PlanInput): PlanValidation | try { return prepare(input).result; } catch (error) { return failure(error); } } -function replacePlanFence(source: string, fence: string): string { - // The complete bare JSON response from an older Lead is also a plan block. - if (isPlanFence('json', source.trim()) && source.trimStart().startsWith('{')) { - try { JSON.parse(source); return fence + '\n'; } catch { /* Preserve surrounding prose. */ } - } - let replaced = false; - const notes = source.replace(/```([a-z-]+)\s*\n([\s\S]*?)\n```/gu, (block, label: string, body: string) => { - if (!isPlanFence(label, body)) return block; - if (replaced) return ''; - replaced = true; - return fence; - }); - return replaced ? notes : fence + '\n' + (source ? '\n' + source : ''); +/** Bind a draft to the projected dispatch. The host still admits it against live state. */ +export function publishCooperationPlanFile(input: PlanInput): (PlanValidation & { file: string; status: 'queued' }) | PlanFailure { + try { + const worktree = fs.realpathSync(input.workspace); + assertMathCanonicalPath(worktree); + const context = workspacePlanContext(worktree); + const target = context.publication; + if (!target) throw invalidPlanField('math_plan_publication_unavailable', '--publish', + 'Use the current Lead dispatch, or omit --publish to save a draft in RESEARCH.md.'); + if (context.base && context.base.version !== target.baseVersion) + throw invalidPlanField('math_plan_publication_version_conflict', 'baseVersion', 'The live dispatch base has changed.'); + const draft = liftNestedPlanPatch(readCandidate(input)); + if (!draft || typeof draft !== 'object' || Array.isArray(draft)) + throw invalidPlanField('math_plan_invalid', '$', 'Supply one JSON object containing a complete plan or revision.'); + const value = draft as Record; + if (value.baseVersion !== undefined && value.baseVersion !== target.baseVersion) + throw invalidPlanField('math_plan_patch_version_conflict', 'baseVersion', 'Rewrite this draft against the current accepted graph.'); + const { file, ...binding } = target; + const event = { ...value, ...binding }; + const { result } = validated(event, context); + appendDeliveryEvent(worktree, file, event); + return { ...result, file, status: 'queued' }; + } catch (error) { return failure(error); } } /** Write a validated draft in one rename. Any revision keeps its baseVersion and decision fields until host intake. */ @@ -105,7 +116,7 @@ export function applyCooperationPlanFile(input: PlanInput): (PlanValidation & { try { assertMathCanonicalPath(file); const source = fs.existsSync(file) ? readMathText(file, MAX_RESEARCH_NOTES_BYTES) : ''; - const next = replacePlanFence(source, '```math-plan\n' + canonical + '\n```'); + const next = replacePlanInNotes(source, canonical); if (Buffer.byteLength(next) > MAX_RESEARCH_NOTES_BYTES) throw invalidPlanField('math_plan_notes_too_large', 'RESEARCH.md', 'Shorten the existing notes or the plan so they fit within 1 MB.'); if (canonicalMathJson(parseMathResponse(next, 'math-plan')) !== canonical) diff --git a/src/solver/research.ts b/src/solver/research.ts index b312cb75..87f26d1f 100644 --- a/src/solver/research.ts +++ b/src/solver/research.ts @@ -32,6 +32,7 @@ import { inspectKnowledgeUses } from './knowledgeUsage'; import { checkKnowledgeApplications } from './knowledgeApplications'; import { parseMathResponse, readMathResponse } from './deliveries'; import { readCheckpointNotesDigest, savedContextCheckpoint } from './contextCheckpoint'; +import { checkpointCommand, researchToolCommand } from './researchToolGuide'; import { committedSource } from './problem'; import type { ContinuationSnapshot } from './continuationInput'; import type { MathTools } from '../math/mathTools'; @@ -405,14 +406,8 @@ export async function runResearchWorkers(input: { const currentCheckpointNotesDigest = () => savedContextCheckpoint(research, worker.worktree); const researchFindingInstruction = (assignment?: CooperativeAction) => { if (assignment?.kind !== 'task' || !['research', 'sketch'].includes(assignment.task.kind)) return ''; - return 'If an established finding is useful to another task or a scoped gap requires a route decision, save the exact argument, ' + - 'assumptions, evidence and unresolved inference in worktree-root RESEARCH.md and publish it now. ' + - 'Append one complete JSON line to ' + JSON.stringify(path.join(worker.worktree, assignmentDeliveryFile(assignment.assignment))) + - ': ' + JSON.stringify({ kind: 'research', finding: { summary: 'REPLACE_WITH_THE_SAVED_ARGUMENT_AND_EVIDENCE', - conclusion: 'inconclusive', remainingObligations: ['REPLACE_WITH_THE_PRECISE_UNRESOLVED_INFERENCE'] } }) + '. ' + - 'Replace the example fields with the actual saved finding; use supporting or refuted only when the evidence supports that conclusion. ' + - 'Add needsDecision:true inside finding only when Lead must choose a route or resolve a blocker; ordinary progress does not need a decision. ' + - 'Do not invent a finding to satisfy this reminder. Publication remains advisory and does not accept a proof. '; + return 'If a finding can help a peer or requires a Lead decision, save the argument and exact gap in RESEARCH.md ' + + 'and publish it with research-observe from the worktree root. '; }; const proofFindingInstruction = 'If a precise mathematical finding needs a Lead decision, publish it through the current assignment log, ' + 'or save a JSON math-result code block in RESEARCH.md with summary, conclusion ("refuted" for an actual counterexample), ' + @@ -438,10 +433,8 @@ export async function runResearchWorkers(input: { 'A local check or a DONE note is not host acceptance. For an unfinished declaration, use the checkpoint acknowledgment below. ' : '') + (file && request?.requestId ? (proof ? 'Only if the assigned declaration remains unfinished, after saving all notes and source drafts, ' : 'After saving all notes and source drafts and publishing any findings or planning decisions, ') + - 'finish this checkpoint by appending one complete JSON line to ' + JSON.stringify(path.join(worker.worktree, file)) + - ': ' + JSON.stringify({ kind: 'checkpoint', requestId: request.requestId, notesDigest: 'SHA256_OF_SAVED_RESEARCH_MD' }) + - '. notesDigest is the lowercase hex SHA-256 of the exact saved RESEARCH.md bytes, as printed by sha256sum RESEARCH.md. ' + - 'Append this control event last, then stop editing and return. ' + + 'run this command to acknowledge the checkpoint, then stop editing and return:\n' + + checkpointCommand(researchToolCommand(input.root, modules.M4.tools), worker.worktree, file, request.requestId) + '\n' + 'Unchanged but accurate notes and an unfinished argument are allowed; this event yields writing and never claims a proof. ' + 'A notes save alone is not checkpoint completion.' : ''); }; @@ -777,7 +770,7 @@ export async function runResearchWorkers(input: { noProgressStreak, protected: false, reason: 'no-durable-progress' }); let noticeSequence = 0; const sendNotice = () => { - if (!current() || noticeSent || assignment?.kind === 'lead' && cooperation?.planSnapshot(assignment)) return; + if (!current() || noticeSent || assignment?.kind === 'lead' && cooperation?.hasLeadPublication(assignment)) return; noticeSent = true; const sequence = ++noticeSequence; noticeDelivery = activeSession.notify ? 'pending' : 'unavailable'; @@ -785,7 +778,7 @@ export async function runResearchWorkers(input: { void Promise.resolve().then(() => { // An accepted live plan already fulfilled this decision, including while human approval // is pending. Recheck at delivery in case publication raced the queued notification. - if (!current() || assignment?.kind === 'lead' && cooperation?.planSnapshot(assignment)) return; + if (!current() || assignment?.kind === 'lead' && cooperation?.hasLeadPublication(assignment)) return; // A goal turn is never yielded, so its reminder must not promise a checkpoint that will // not come: it asks for the durable handoff and leaves the writing turn running. return activeSession.notify?.(assignment?.kind === 'task' && isFeasibilityReview(assignment.task) @@ -798,14 +791,9 @@ export async function runResearchWorkers(input: { ? 'Save the current mathematical argument, the exact unresolved step and useful references in RESEARCH.md now. ' + 'This turn keeps running: no checkpoint will interrupt or end it, so save notes incrementally and continue proving.' : initialPlan - ? cooperation?.initialPlanSnapshot(assignment) - ? 'The first plan is already published. Save the current argument and precise unresolved inference in RESEARCH.md, ' + - 'then return promptly; eligible peers can continue the published work and later Lead decisions use their evidence.' - : 'If the first plan is still unpublished, publish it now before further searches or experiments: append the complete ' + - 'plan JSON line to this assignment\'s delivery log as described in your instructions. A direct goal task for each ' + - 'original target plus research tasks for specific open questions is a valid first plan; later Lead turns refine it. ' + - 'If the host accepted it while this notice was waiting, save the current argument and exact uncertainties in ' + - 'RESEARCH.md and return promptly. This is a reminder, not an interruption.' + ? 'If the first plan is still unpublished, publish it now with plan-apply --publish from the Lead tool help. ' + + 'Start with a direct goal task for each original target and separate research tasks for specific open questions. ' + + 'Save the route and uncertainties in RESEARCH.md and return once the host has the plan.' : revision ? 'Decide now, before further searches or experiments. ' + cooperation!.leadCheckpointInstruction(assignment!) + 'Delegate any open search as a research task instead of ' + @@ -847,8 +835,9 @@ export async function runResearchWorkers(input: { let handoffRequested = false; const cut = (boundary: 'request-returned' | 'wait-limit' | 'notice-failed') => { if (!current() || compactionStartedAt !== undefined || checkpointRequested || readyRequested) return; - if (boundary === 'request-returned' && assignment?.kind === 'lead' && noticeDelivery === 'delivered' && - cooperation?.leadCheckpointNeedsHandoff(assignment)) { + const leadHandoff = boundary === 'request-returned' && assignment?.kind === 'lead' && noticeDelivery === 'delivered' + ? cooperation?.leadCheckpointHandoff(assignment) : undefined; + if (leadHandoff && assignment?.kind === 'lead') { // Reading the current graph is not a decision. Give this dispatch the remainder of // the same wait window to save a complete answer before freezing its workspace. if (!handoffRequested) { @@ -857,7 +846,10 @@ export async function runResearchWorkers(input: { remainingMs: Math.max(0, advisoryRequestWaitMs - (Date.now() - waitStartedAt)) }); void Promise.resolve().then(() => { if (!current() || checkpointRequested || readyRequested) return; - return activeSession.notify?.(cooperation!.leadCheckpointInstruction(assignment) + + const handoff = cooperation!.leadCheckpointHandoff(assignment); + if (!handoff) return; + const correction = handoff.reason ? 'Correct the saved math-plan draft. ' + handoff.reason + '\n' : ''; + return activeSession.notify?.(correction + cooperation!.leadCheckpointInstruction(assignment) + 'Save the complete decision now, before another search. The host is waiting only until the existing ' + 'checkpoint deadline; reading the inherited plan or saving prose does not answer the required decisions.'); }).catch(error => { @@ -914,7 +906,7 @@ export async function runResearchWorkers(input: { // Notes may become visible before their writing tool finishes; wait for its result before freezing them. const waitForHandoffTool = noticeDelivery === 'delivered' && (researchAssignment || assignment?.kind === 'lead'); const pendingLeadHandoff = handoff && noticeDelivery === 'delivered' && assignment?.kind === 'lead' && - cooperation?.leadCheckpointNeedsHandoff(assignment); + cooperation?.leadCheckpointHandoff(assignment); const modelOutputStale = lastModelOutputAt === undefined || Date.now() - lastModelOutputAt > advisoryModelStreamingMs; if ((requestWaited && !handoff) || (toolsRunning ? !waitForHandoffTool : modelOutputStale && !pendingLeadHandoff)) { clearTimeout(requestWaitTimer); checkpoint(); return; @@ -1343,9 +1335,16 @@ export async function runResearchWorkers(input: { }; const maintainContext = async (assignment?: CooperativeAction): Promise<'unchanged' | 'compacted' | 'rotated'> => { const recoverNative = nativeContextRecovery === 'pending'; - if (skillMode && !recoverNative || !research.threadId || !session || !sessionHasHistory) return 'unchanged'; - const threadId = research.threadId, lastInputTokens = Math.max(session.lastInputTokens ?? 0, research.lastInputTokens ?? 0); + if (skillMode && !recoverNative || !research.threadId) return 'unchanged'; + const threadId = research.threadId; const notesDigest = currentCheckpointNotesDigest(); + if (!session) { + if (!notesDigest) return 'unchanged'; + emit('context_checkpoint_ready', { threadId, notesDigest }); + await rotateSession('context'); return 'rotated'; + } + if (!sessionHasHistory) return 'unchanged'; + const lastInputTokens = Math.max(session.lastInputTokens ?? 0, research.lastInputTokens ?? 0); if (!recoverNative && lastInputTokens < 96_000 && !notesDigest) return 'unchanged'; if (recoverNative) nativeContextRecovery = 'attempted'; if (session.compact && (recoverNative || compactedUsageVersion !== contextUsageVersion || notesDigest)) { @@ -1421,7 +1420,7 @@ export async function runResearchWorkers(input: { } lastCheck = research.check; save(); if (research.check.passed) { - if (cooperation && !cooperation.reviewed(research.check)) { cooperation.requireReview(research.check); return; } + if (cooperation && !cooperation.candidateReady(research.check)) return; state.check = research.check; state.candidate = candidate; if (parallel) state.winningWorker = worker.id; winner = { worktree: worker.worktree, check: research.check }; diff --git a/src/solver/researchGuidance.ts b/src/solver/researchGuidance.ts index b0ce8b09..b7aa1ad0 100644 --- a/src/solver/researchGuidance.ts +++ b/src/solver/researchGuidance.ts @@ -15,7 +15,7 @@ import { materializeResearchToolHelp } from './researchToolHelp'; import { buildResearchToolGuide } from './researchToolGuide'; import { researchSkillIdentity } from './researchSkill'; import { skillResearchContinuationSection } from './skillResearchContext'; -import { assignmentDeliveryFile, isAdvisoryTask, isFeasibilityReview, isFinalCandidateReview, leadPlanDeliveryFile, type CooperativeTask } from './tasks'; +import { assignmentDeliveryFile, isAdvisoryTask, isFeasibilityReview, isFinalCandidateReview, type CooperativeTask } from './tasks'; /** Static shared guidance also serves a native single-task baseline without manufacturing solver state. */ export function buildCommonResearchGuide(problem: SolverProblem, @@ -72,10 +72,7 @@ export function buildCommonResearchContext(problem: SolverProblem, state: Readon let workContract: ContextBundle['workContract']; const taskContinuation = action?.kind === 'task' && !isFeasibilityReview(action.task) && !isFinalCandidateReview(action.task); if (action && cooperation) { - // deliveryGuidance contains legacy mathematical heuristics. The comparison keeps - // the actual ownership/evidence contract and obtains methods solely from the shared skill. - const contract = cooperativeWorkContract(action, cooperation.tasks, cooperation); - workContract = Object.fromEntries(Object.entries(contract).filter(([key]) => key !== 'deliveryGuidance')) as typeof contract; + workContract = cooperativeWorkContract(action, cooperation.tasks, cooperation); mandatory.push({ id: 'work-contract', kind: 'assignment', text: 'Host execution contract:\n' + JSON.stringify(workContract) }); if (cooperation.leadDecisionInstruction && action.kind === 'lead') mandatory.push({ id: 'lead-decisions', kind: 'assignment', text: 'Required fields for this host decision:\n' + cooperation.leadDecisionInstruction }); @@ -125,34 +122,30 @@ 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 const leadPlanToolInstruction = 'Use plan-apply from Lead plan submission in .scratch/theoremos-help.md. 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 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. ' + - 'Include researchDecisions, nextCheckDecisions and any progressReview requested by the host in that same object. ' + + 'Save the plan or revision in .scratch/plan.json and run plan-apply --publish. ' + + 'Include the decisions requested for this dispatch in the 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. ' + + 'To submit on return, omit --publish to save the validated decision in RESEARCH.md. ' + 'Do not truncate delivery logs, modify run state, accept unchecked tasks or wait for human plan approval yourself. '; } if (action.kind === 'task') { const log = taskLog ?? assignmentDeliveryFile(action.assignment); const helpers = cooperativeHelperProtocol(action.task, log); - if (isAdvisoryTask(action.task)) return `Append {"kind":"research","finding":{"summary":"complete finding","conclusion":"supporting|refuted|inconclusive",` + - `"evidenceRefs":[],"remainingObligations":[],"lemmaRequests":[]}} as a JSON line to ${log}, then return. ` + - 'Use exactly one conclusion value. Retain complete notes and reproducible evidence. Findings are advisory. ' + - 'Leave Lean files as in the assignment seed on ordinary findings delivery. Do not truncate logs or submit fabricated proof receipts. ' + helpers; + if (isAdvisoryTask(action.task)) return 'Save findings and reproducible evidence in RESEARCH.md and return to complete the assignment. ' + + 'Use research-observe from the generated tool help to share a finding during the turn. ' + + 'Leave Lean files as in the assignment seed on ordinary findings delivery. ' + helpers; return 'Save only the assigned exact declaration in its allowed proof file; preserve other original goals, helper interfaces and seed proofs. ' + - `Append {"kind":"ready","summary":"saved assigned proof"} as a JSON line to ${log}, then stop writing and return. ` + - 'Natural return also submits saved work. Do not run git add/commit or provide commit/targets/receipts; the host freezes and checks them. ' + + 'Return after saving. The host selects and checks the assigned source. ' + + `For early handoff only, append {"kind":"ready","summary":"saved assigned proof"} to ${log} and stop editing. ` + 'Conditional assignments use their fixed dependencies; no stub or additional assumption establishes unconditional acceptance. ' + helpers; } return 'Return saved evidence through the current host assignment; the host performs integration and proof acceptance. '; diff --git a/src/solver/researchObservation.ts b/src/solver/researchObservation.ts index 66b83435..9c3cf8c0 100644 --- a/src/solver/researchObservation.ts +++ b/src/solver/researchObservation.ts @@ -1,8 +1,7 @@ -import fs from 'node:fs'; import path from 'node:path'; import { assertMathCanonicalPath, isMathPathWithin } from '../math/paths'; import { canonicalMathJson, mathDigest, readMathText } from '../math/mathRuntimeIo'; -import { MAX_DELIVERY_LINE_BYTES, MAX_RESEARCH_NOTES_BYTES } from './deliveries'; +import { appendDeliveryEvent, MAX_RESEARCH_NOTES_BYTES } from './deliveries'; import { prepareResearchDelivery, ResearchAdmissionError, type ResearchAdmissionScope } from './researchAdmission'; import { researchPublicationNotes } from './researchPublication'; import { assignmentDeliveryFile, taskVersion, type TaskAssignment, type TaskRecord } from './tasks'; @@ -33,7 +32,10 @@ export function queueResearchObservation(input: { identity: { problemReceiptDigest: delivery.problemReceiptDigest, environmentDigest: delivery.environmentDigest }, tasks: context.tasks, deliveries: context.deliveries, ...(context.nextChecks ? { nextChecks: context.nextChecks } : {}), ...(context.proofSearchRecords ? { proofSearchRecords: context.proofSearchRecords } : {}) }; - const admission = prepareResearchDelivery({ kind: 'event', value: input.finding }, scope); + const object = typeof input.finding === 'object' && input.finding !== null && !Array.isArray(input.finding) + ? input.finding as Record : undefined; + const { guidanceDecisions, ...finding } = object ?? {}; + const admission = prepareResearchDelivery({ kind: 'event', value: object ? finding : input.finding }, scope); if (admission.status === 'rejected') throw new ResearchAdmissionError(admission); const probes = input.probes?.map(file => ({ source: path.relative(worktree, local(file)), code: readMathText(local(file), MAX_RESEARCH_NOTES_BYTES) })); @@ -47,12 +49,9 @@ export function queueResearchObservation(input: { if (Object.values(sources).reduce((bytes, source) => bytes + Buffer.byteLength(source), 0) > MAX_RESEARCH_NOTES_BYTES) throw new Error('math_observation_sources_too_large'); } - const value = { kind: 'research', finding: admission.finding, ...(probes ? { probes } : {}), ...(sources ? { sources } : {}) }; - const file = assignmentDeliveryFile(delivery.assignment), output = local(file); - const line = JSON.stringify(value) + '\n'; - if (Buffer.byteLength(line) > MAX_DELIVERY_LINE_BYTES) throw new Error('math_observation_too_large'); - const fd = fs.openSync(output, fs.constants.O_WRONLY | fs.constants.O_APPEND | fs.constants.O_CREAT | fs.constants.O_NOFOLLOW, 0o600); - try { fs.writeFileSync(fd, line); fs.fsyncSync(fd); } finally { fs.closeSync(fd); } + const value = { kind: 'research', finding: admission.finding, guidanceDecisions, ...(probes ? { probes } : {}), ...(sources ? { sources } : {}) }; + const file = assignmentDeliveryFile(delivery.assignment); + appendDeliveryEvent(worktree, file, value); return { status: 'queued', authority: 'advisory-unverified', submissionId: mathDigest(canonicalMathJson({ file, value })), file, taskId: delivery.assignment.taskId, taskDigest: delivery.assignment.taskDigest, diff --git a/src/solver/researchToolGuide.ts b/src/solver/researchToolGuide.ts index 8df21c25..3f855d64 100644 --- a/src/solver/researchToolGuide.ts +++ b/src/solver/researchToolGuide.ts @@ -7,6 +7,11 @@ import { ResearchToolHelpBuilder } from './researchToolHelp'; const quote = (value: string) => "'" + value.replaceAll("'", "'\\''") + "'"; +export const researchToolCommand = (root: string, tools?: string) => `bun ${quote(tools ?? path.join(root, 'bin/math.ts'))}`; + +export const checkpointCommand = (command: string, worktree: string, file: string, requestId: string) => + `${command} checkpoint --worktree ${quote(worktree)} --log ${quote(file)} --request-id ${quote(requestId)}`; + export const longCommandGuidance = 'For a long calculation, record the inputs, print progress and save completed batches in .scratch/tmp. Use unbuffered output for Python (python3 -u). ' + 'With native exec_command, keep the session ID returned after a short yield_time_ms. Poll with write_stdin and empty chars. ' + @@ -18,11 +23,13 @@ export function buildResearchToolGuide(problem: Pick, environmentDigest: string, teamTransport?: AgentTeamTransport) { - const command = `bun ${quote(access.tools ?? path.join(access.root, 'bin/math.ts'))}`; + const command = researchToolCommand(access.root, access.tools); 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`, ''); + `Save one plan or revision in .scratch/plan.json. Omit progressReview on the initial plan.\n` + + `Publish for immediate host intake: ${command} plan-apply --publish --file .scratch/plan.json\n` + + `To save the plan in RESEARCH.md for intake on return: ${command} plan-apply --file .scratch/plan.json\n` + + 'Both validate the draft. Live publication binds the current dispatch automatically.', ''); 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/tasks.ts b/src/solver/tasks.ts index 134c7691..ee64814c 100644 --- a/src/solver/tasks.ts +++ b/src/solver/tasks.ts @@ -110,7 +110,7 @@ export function taskReferenceDependencies(node: TaskRecord): DeliveryRecord['dep } export const markTaskReferences = (proof: TaskProof) => checkedReferences.add(proof); export const hasTaskReferences = (proof: TaskProof) => checkedReferences.has(proof); -// Restored JSON cannot authorize final-candidate dispatch before the host rechecks it. +// Archived receipts do not count as task acceptances in the current process. const freshTaskAcceptances = new WeakMap(); const acceptanceIdentity = (proof: TaskProof) => canonicalMathJson({ commit: proof.commit, sourceDigest: proof.sourceDigest, taskDigest: proof.taskDigest, conditions: proof.conditions, projection: proof.projection, verification: proof.verification && { @@ -178,6 +178,8 @@ export const assumableLemma = (task: CooperativeTask | undefined): boolean => Boolean(task && task.kind === 'lemma' && task.type?.trim() && !isDefinitionTask(task)); export const isFinalCandidateReview = (task: CooperativeTask) => isAdvisoryTask(task) && (task.reviewScope === 'final-candidate' || task.id === 'independent_candidate_review'); +export const isActiveFinalCandidateReview = (task: CooperativeTask) => + isFinalCandidateReview(task) && (task.status ?? 'active') === 'active'; export const isFeasibilityReview = (task: CooperativeTask) => isAdvisoryTask(task) && task.reviewScope === 'feasibility' && !isFinalCandidateReview(task); /** Pin a deferred decision's `waitsOn` ids to their current typed, non-advisory task versions. `invalid` rejects a malformed diff --git a/tests/agentResearchTeam.test.ts b/tests/agentResearchTeam.test.ts index 3cfa7f67..bf0de4f9 100644 --- a/tests/agentResearchTeam.test.ts +++ b/tests/agentResearchTeam.test.ts @@ -275,7 +275,7 @@ describe('Agent-led sustained collaboration with real Git and Lean', () => { expect(fast.options.tools!.definitions.find(item => item.name === 'theoremos_team')!.inputSchema) .toMatchObject({ properties: { operation: { enum: [ 'progress', 'yield', 'history', 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'submit', - 'submit_helpers', 'route_summary'] } } }); + 'route_summary'] } } }); expect(fast.options.skills![0]!.digest).toBe(f.state.researchSkill!.digest); const help = fs.readFileSync(path.join(fastWorker.worktree, RESEARCH_TOOL_HELP_FILE), 'utf8'); expect(fast.options.instructions).toContain(path.join(fastWorker.worktree, RESEARCH_TOOL_HELP_FILE)); @@ -993,7 +993,7 @@ describe('Agent-led sustained collaboration with real Git and Lean', () => { const f = fixture(); expect(f.team.tools('lead').definitions.find(item => item.name === 'theoremos_team')!.inputSchema) .toMatchObject({ properties: { operation: { enum: [ - 'spawn', 'assign', 'amend', 'finish', 'coordinate', 'budget', 'resume', 'history', 'publish', 'cancel', + 'spawn', 'assign', 'amend', 'finish', 'budget', 'resume', 'history', 'publish', 'cancel', 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'adopt', 'stop', 'retire_route', 'route_summary'] } } }); const spawn = { operation: 'spawn', agentId: 'child', message: 'Study independently.' }; await f.call(spawn, 'lead', 'one-handle'); diff --git a/tests/agentTeamNativeControl.test.ts b/tests/agentTeamNativeControl.test.ts index 56f97947..3c612dc7 100644 --- a/tests/agentTeamNativeControl.test.ts +++ b/tests/agentTeamNativeControl.test.ts @@ -362,7 +362,7 @@ describe('native AgentControl mathematical-team host routing', () => { } expect(operations).toEqual(['finish', 'history', 'inspect', 'inspect-research', 'adopt', 'retire_route', 'route_summary']); const memberTool = agentTeamToolDefinition('analyst', false, 'native-agent-control'); - expect((memberTool.inputSchema.properties as Json).operation.enum).toEqual(['yield', 'history', 'inspect', 'inspect-research', 'submit', 'submit_helpers', 'route_summary']); + expect((memberTool.inputSchema.properties as Json).operation.enum).toEqual(['yield', 'history', 'inspect', 'inspect-research', 'submit', 'route_summary']); expect(agentTeamInstructions({ id: 'lead', role: 'lead' }, 4, 'native-agent-control')).toContain('native collaboration tools'); expect(agentTeamInstructions({ id: 'lead', role: 'lead' }, 4, 'native-agent-control')).not.toContain('Built-in spawn/fork is disabled'); expect(agentTeamInstructions({ id: 'lead', role: 'lead' }, 4)).toContain('Built-in spawn/fork is disabled'); diff --git a/tests/agentTeamNativeLifecycle.test.ts b/tests/agentTeamNativeLifecycle.test.ts index 75e52ccd..39ee1418 100644 --- a/tests/agentTeamNativeLifecycle.test.ts +++ b/tests/agentTeamNativeLifecycle.test.ts @@ -446,17 +446,18 @@ describe('native AgentControl preserves the mathematical team lifecycle', () => }); it('can reuse a yielded worker for a different route and return to its original task', async () => { - const f = fixture(); await f.spawn('analyst', 'Route: initial\nInvestigate the first approach.'); + const f = fixture(); await f.spawn('analyst', 'Route: initial\nProfiles: prover, D006\nInvestigate the first approach.'); const worker = f.state.agentTeam!.workers[0], original = worker.tasks[0]; + expect(original).toMatchObject({ routeId: 'initial', profileEvidence: { selected: ['prover', 'D006'] } }); expect(await f.tool({ operation: 'yield', reason: 'Awaiting a dependency.' }, worker.id)).toMatchObject({ status: 'pending-writer-stop' }); await f.sessions[0].complete(); await expect.poll(() => f.team.hasActiveWorkers).toBe(false); const followup = (text: string) => f.native('send', { caller: ROOT, target: { kind: 'id', threadId: worker.native!.threadId }, input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text } } }); - await followup('Route: other\nCheck an independent approach while the first waits.'); + await followup('Route: other\nProfiles: engineer\nCheck an independent approach while the first waits.'); expect(worker.tasks).toHaveLength(2); expect(original.status).toBe('paused'); - expect(worker.tasks[1]).toMatchObject({ routeId: 'other', status: 'running' }); + expect(worker.tasks[1]).toMatchObject({ routeId: 'other', status: 'running', profileEvidence: { selected: ['engineer'] } }); expect(f.sessions[1].message).toContain('Check an independent approach'); await f.sessions[1].complete(); await expect.poll(() => f.team.hasActiveWorkers).toBe(false); diff --git a/tests/agentTeamNativeTools.test.ts b/tests/agentTeamNativeTools.test.ts index 5501c4a9..e92c478c 100644 --- a/tests/agentTeamNativeTools.test.ts +++ b/tests/agentTeamNativeTools.test.ts @@ -20,12 +20,12 @@ const executable = process.env.THEOREMOS_TEST_CODEX_EXECUTABLE ?? 'codex'; const nativeAvailable = spawnSync(executable, ['--version'], { env: { PATH: process.env.PATH }, timeout: 5000, stdio: 'ignore', }).status === 0; -const operations = ['spawn', 'assign', 'amend', 'finish', 'coordinate', 'budget', 'resume', 'history', 'publish', 'cancel', +const operations = ['spawn', 'assign', 'amend', 'finish', 'budget', 'resume', 'history', 'publish', 'cancel', 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'adopt', 'stop', 'retire_route', 'route_summary']; const memberOperations = ['progress', 'yield', 'history', 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'submit', - 'submit_helpers', 'route_summary']; + 'route_summary']; const nativeLeadOperations = ['finish', 'history', 'inspect', 'inspect-research', 'adopt', 'retire_route', 'route_summary']; -const nativeMemberOperations = ['yield', 'history', 'inspect', 'inspect-research', 'submit', 'submit_helpers', 'route_summary']; +const nativeMemberOperations = ['yield', 'history', 'inspect', 'inspect-research', 'submit', 'route_summary']; /** Codex may normalize validation keywords, but it must preserve every branch and field. */ function expectAdvertisedOperations(host: Json, expected: string[], schema: Json) { @@ -192,12 +192,13 @@ describe.skipIf(!nativeAvailable)('real Codex dynamic team tool transport withou expect(advertised?.parameters.properties.includeRetired).toMatchObject({ type: 'boolean' }); expect(advertised?.parameters.properties.routeId).toMatchObject({ type: 'string' }); if (actor === 'lead') { - expect(advertised?.description).toContain('coordinate: required decision, reason, nextStep;'); + expect(advertised?.description).not.toContain('coordinate'); expect(advertised?.description).toContain('retire_route: required routeId, reason; optional evidenceRefs; other fields forbidden.'); - expect(advertised?.parameters.properties).toMatchObject({ decision: { type: 'string', enum: ['defer', 'continue'] }, - reason: { type: 'string' }, nextStep: { type: 'string' }, evidenceRefs: { type: 'array', items: { type: 'string' } } }); + expect(advertised?.parameters.properties).not.toHaveProperty('decision'); + expect(advertised?.parameters.properties).toMatchObject({ reason: { type: 'string' }, + evidenceRefs: { type: 'array', items: { type: 'string' } } }); } else { - expect(advertised?.description).toContain('submit: required summary, declarations; optional objectiveRevision; other fields forbidden.'); + expect(advertised?.description).toContain('submit: required summary, declarations; optional objectiveRevision, helpersOnly; other fields forbidden.'); const submitSchema = advertised?.parameters.oneOf.find((branch: Json) => branch.properties.operation.enum[0] === 'submit'); expect(submitSchema.required).toEqual(['operation', 'summary', 'declarations']); expect(submitSchema.properties).not.toHaveProperty('agentId'); diff --git a/tests/agentTeamSolver.test.ts b/tests/agentTeamSolver.test.ts index fa35e789..888ba307 100644 --- a/tests/agentTeamSolver.test.ts +++ b/tests/agentTeamSolver.test.ts @@ -250,7 +250,7 @@ describe.skipIf(process.platform !== 'linux')('Agent team through native tool RP expect(childResumes[0]!.params.dynamicTools).toBeUndefined(); const childToolSchema = childStart.params.dynamicTools[0].inputSchema; const childOperations = ['progress', 'yield', 'history', 'message', 'poll', 'wait', 'inspect', 'inspect-research', - 'submit', 'submit_helpers', 'route_summary']; + 'submit', 'route_summary']; expect(childToolSchema.properties.operation.enum).toEqual(childOperations); expect(childToolSchema.oneOf.map((branch: { properties: { operation: { enum: string[] } } }) => branch.properties.operation.enum[0])).toEqual(childOperations); @@ -272,7 +272,7 @@ describe.skipIf(process.platform !== 'linux')('Agent team through native tool RP const leadTrace = trace(worktree), leadFrames = leadTrace.filter(frame => frame.direction === 'host'); const leadToolSchema = leadFrames.find(frame => frame.method === 'thread/start')!.params.dynamicTools[0].inputSchema; - expect(leadToolSchema.properties.operation.enum).toEqual(['spawn', 'assign', 'amend', 'finish', 'coordinate', 'budget', + expect(leadToolSchema.properties.operation.enum).toEqual(['spawn', 'assign', 'amend', 'finish', 'budget', 'resume', 'history', 'publish', 'cancel', 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'adopt', 'stop', 'retire_route', 'route_summary']); expect(leadToolSchema).not.toHaveProperty('oneOf'); diff --git a/tests/agentTeamSourceRecovery.test.ts b/tests/agentTeamSourceRecovery.test.ts index 58283799..7fef3dff 100644 --- a/tests/agentTeamSourceRecovery.test.ts +++ b/tests/agentTeamSourceRecovery.test.ts @@ -3,7 +3,7 @@ import os from 'node:os'; import path from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { bootstrapLeanTask } from '../src/math/leanTask'; -import { mathDigest } from '../src/math/mathRuntimeIo'; +import { canonicalMathJson, mathDigest } from '../src/math/mathRuntimeIo'; import { readMathAgentSkill } from '../src/runtime/agentSkills'; import type { MathAgentOptions, MathAgentSession } from '../src/runtime/agentSession'; import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; @@ -104,7 +104,7 @@ describe('recoverable team source rejections', () => { activity({ event: 'item_completed', itemType: 'contextCompaction' }); expect(session.notices).toEqual([]); activity({ event: 'item_completed', itemType: 'contextCompaction' }); - expect(session.notices).toEqual([expect.stringContaining('submit_helpers')]); + expect(session.notices).toEqual([expect.stringContaining('submit with helpersOnly:true')]); expect(f.events).toContainEqual({ event: 'compaction_circuit_breaker_triggered', details: expect.objectContaining({ workerId: worker.id, taskId: worker.tasks[0]!.id, completedCompactions: 2, }) }); @@ -149,7 +149,7 @@ describe('recoverable team source rejections', () => { fs.writeFileSync(f.source(producer.worktree), original.replace('theorem goal', helperProofs + 'theorem goal')); fs.writeFileSync(f.source(consumer.worktree), original.replace('end Recovery', draft + 'end Recovery')); const names = [...declarations, { ...declarations[0]!, name: 'Recovery.second' }]; - expect(await f.call({ operation: 'submit_helpers', summary: 'Verified standalone facts.', declarations: names }, 'member')) + expect(await f.call({ operation: 'submit', helpersOnly: true, summary: 'Verified standalone facts.', declarations: names }, 'member')) .toMatchObject({ ok: true, status: 'pending-writer-stop' }); expect(f.team.archive.canonicalCommit).toBeUndefined(); expect(a.options.requestGate!.checkpoint!()).toBe(true); @@ -188,6 +188,20 @@ describe('recoverable team source rejections', () => { expect(f.state.check).toBeUndefined(); }, 60_000); + it('replays a recorded submit_helpers call from an older member thread', async () => { + const f = fixture(); + const originalCall = { operation: 'submit_helpers', summary: 'Verified standalone facts.', declarations }; + const context = { threadId: 'old-member-thread', turnId: 'old-turn', callId: 'old-submit', signal: f.controller.signal }; + const result = { ok: true, status: 'pending-writer-stop', taskId: 'old-task' }; + f.team.archive.operations.push({ + key: canonicalMathJson(['member', context.threadId, context.turnId, context.callId]), + digest: mathDigest(canonicalMathJson(originalCall)), result, + }); + const tools = f.team.tools('member'); + await expect(tools.call('theoremos_team', originalCall, context)).resolves.toEqual(result); + expect(f.team.archive.operations).toHaveLength(1); + }); + it('preserves the rejected Lean interface and check receipt for the producer, a repair peer and restored history', async () => { const f = fixture(3); await f.call({ operation: 'spawn', agentId: 'member', message: 'Prove the helper.' }); const first = await f.session(0), worker = f.team.archive.workers[0]!; diff --git a/tests/agentTeamTool.test.ts b/tests/agentTeamTool.test.ts index f9a4fef2..3cbb8d48 100644 --- a/tests/agentTeamTool.test.ts +++ b/tests/agentTeamTool.test.ts @@ -92,11 +92,21 @@ describe('operation-specific team tool contracts', () => { const finite = agentTeamToolDefinition('lead', true); expect(finite.inputSchema).not.toHaveProperty('oneOf'); expect(finite.inputSchema.properties).toHaveProperty('budget'); - expect(finite.description).toContain('coordinate: required decision, reason, nextStep;'); + }); + + it.each([false, true])('keeps coordinate off the Lead menu with finite budget = %s while accepting explicit legacy calls', async finite => { + const tool = agentTeamToolDefinition('lead', finite); + expect((tool.inputSchema as Json).properties.operation.enum).not.toContain('coordinate'); + expect(tool.inputSchema.properties).not.toHaveProperty('decision'); + expect(tool.description).not.toContain('coordinate'); const invalid = agentTeamRequestSchema.safeParse({ operation: 'coordinate', decision: 'continue' }); - if (invalid.success) throw new Error('Incomplete finite-budget operation must remain invalid.'); - expect(agentTeamArgumentFeedback('lead', true, { operation: 'coordinate' }, invalid.error).contract.required) - .toEqual(['operation', 'decision', 'reason', 'nextStep']); + if (invalid.success) throw new Error('Incomplete legacy operation must remain invalid.'); + expect(agentTeamArgumentFeedback('lead', finite, { operation: 'coordinate' }, invalid.error).allowedOperations) + .not.toContain('coordinate'); + const f = fixture('lead'), note = { decision: 'continue', reason: 'Checked the interface.', nextStep: 'Explore the bound.' }; + const result = await f.call({ operation: 'coordinate', ...note }, 'legacy-coordinate'); + expect(result.value).toMatchObject({ ok: true, advisory: true }); + expect(f.state.agentTeam?.coordination).toMatchObject({ ...note, revision: 1 }); }); it('returns the exact selected operation contract for a missing recipient or extra identity', () => { diff --git a/tests/agentTools.test.ts b/tests/agentTools.test.ts index 241e32d5..f010cbea 100644 --- a/tests/agentTools.test.ts +++ b/tests/agentTools.test.ts @@ -11,7 +11,7 @@ import { writeLibraryCatalog } from '../src/solver/libraryCatalog'; import { readSolverProblem } from '../src/solver/problem'; const commands = ['check-finite', 'check-lean', 'continuation', 'declarations', 'hub', 'kernel-certificate', 'knowledge', 'library', - 'plan-apply', 'plan-validate', 'proof-search', 'research-observe', 'search-lean']; + 'checkpoint', 'plan-apply', 'plan-validate', 'proof-search', 'research-observe', 'search-lean']; const fixture = path.resolve('examples/finite/old-b1-nine-constraints.json'); let directory = ''; let tools = ''; diff --git a/tests/certificateSlots.test.ts b/tests/certificateSlots.test.ts index f3f4c684..2582113a 100644 --- a/tests/certificateSlots.test.ts +++ b/tests/certificateSlots.test.ts @@ -142,9 +142,9 @@ describe('certificate slot guidance in research prompts', () => { assignment: task ? { kind: 'task', task, assignment: { taskId: task.id, taskDigest: taskVersion(task), workerId: 'worker', seedCommit: 'fixed-commit' } } : { kind: 'lead', seedCommit: 'fixed-commit' } }).instructions; - it('collapses certificate parts, freezes the library and keeps research source keys complete', () => { + it('collapses certificate parts and keeps the frozen kernel out of planning and edits', () => { const lead = build(fixture(ownedFiles)); - expect(lead).toContain('Edit only /proof/RESEARCH.md.'); + expect(lead).toContain('Edit only /proof/RESEARCH.md, /proof/.scratch/plan.json.'); expect(lead).toContain('Leave all Lean source files, imports and environment configuration unchanged.'); expect(lead).toContain('Choose proofPath from ["Helper.lean","Submission.lean"]; workers generate Submission/Certificates modules'); expect(lead).toContain('"proofPath":"Helper.lean"'); @@ -153,11 +153,11 @@ describe('certificate slot guidance in research prompts', () => { `/proof/${parts[0]} … /proof/${parts[2]}, /proof/RESEARCH.md, `); expect(worker).toContain(`kernel-certificate --json 'SPEC' --workspace '/proof'`); expect(worker).toContain(`"kernelModule":"${CERTIFICATE_KERNEL_MODULE}"`); - expect(worker).toContain('frozen local modules already imported by the original owned files, or other owned modules, without import cycles'); - expect(worker).toContain(`Its keys must be exactly ${JSON.stringify(ownedFiles)}`); + expect(worker).toContain('frozen local modules already imported by the original owned files, or other owned modules. Avoid import cycles'); + expect(worker.split('\n').find(line => line.startsWith('Edit only '))).not.toContain(CERTIFICATE_KERNEL_MODULE); const plain = build(fixture(['Submission.lean'])); - expect(plain).toContain('Edit only /proof/RESEARCH.md.'); + expect(plain).toContain('Edit only /proof/RESEARCH.md, /proof/.scratch/plan.json.'); expect(plain).toContain('Choose proofPath from ["Submission.lean"]; goals infer'); expect(plain).not.toContain('kernel-certificate'); }); diff --git a/tests/commonResearchGuidance.test.ts b/tests/commonResearchGuidance.test.ts index b87df4aa..b75b3154 100644 --- a/tests/commonResearchGuidance.test.ts +++ b/tests/commonResearchGuidance.test.ts @@ -6,7 +6,7 @@ import { agentTeamOperationAllowed } from '../src/solver/agentTeamTool'; import { buildResearchContext, finalizeResearchDispatch } from '../src/solver/modules/context'; import { researchSkillIdentity } from '../src/solver/researchSkill'; import { buildSkillResearchContext } from '../src/solver/skillResearchContext'; -import { assignmentDeliveryFile, leadPlanDeliveryFile, taskVersion, type CooperativeTask } from '../src/solver/tasks'; +import { assignmentDeliveryFile, taskVersion, type CooperativeTask } from '../src/solver/tasks'; import { localExample, solverState } from './helpers/solver'; const roots: string[] = []; @@ -134,8 +134,9 @@ describe('common mathematical guidance across research strategies', () => { f.state.cooperation = { tasks: [], leadDecisionInstruction: 'Include researchDecisions for delivery d1.' }; const context = buildResearchContext(f.problem, f.state, { ...f.access, assignment: action }); expect(context.message).toContain('Include researchDecisions for delivery d1.'); - expect(context.instructions).toContain(leadPlanDeliveryFile(action)); - expect(context.instructions).toContain('frozen-publication-nonce'); + expect(context.message).toContain(JSON.stringify(action)); + expect(fs.readFileSync(path.join(f.workspace, '.scratch/theoremos-help.md'), 'utf8')) + .toContain('plan-apply --publish --file .scratch/plan.json'); expect(context.instructions).toContain('Leave all Lean sources unchanged'); expect(context.instructions).toContain('covering every original target exactly once'); for (const text of ['Before expanding an uncertain decomposition', 'hardest substantive inference', diff --git a/tests/contextCompiler.test.ts b/tests/contextCompiler.test.ts index 6730f7ef..b570a51c 100644 --- a/tests/contextCompiler.test.ts +++ b/tests/contextCompiler.test.ts @@ -248,13 +248,9 @@ it('keeps executable parallel-work guidance mandatory for Lead decisions', () => assignment: { kind: 'lead', seedCommit: baseCommit, planVersion: 'v1', planNonce: 'dispatch' }, frozenContexts: input([]).frozenContexts, maxOptionalContextBytes: 0 }); expect(context.workContract).toMatchObject({ stage: 'route-planning', output: 'validated-task-graph', acceptance: 'host-plan-validation' }); - const guidance = context.workContract && 'deliveryGuidance' in context.workContract ? context.workContract.deliveryGuidance : ''; - expect(guidance).toContain('distinct scope relative to in-flight work'); - expect(guidance).toContain('concrete first construction, proof step or discriminating check'); - expect(guidance).toContain('intended consumer with its application'); - expect(guidance).toContain('give the Engineer executable proof work'); - expect(guidance).toContain('no task is required merely to occupy an idle worker'); - expect(guidance).toContain('infinite family of objects'); + expect(context.workContract).not.toHaveProperty('deliveryGuidance'); + expect(context.instructions).toContain('Delegate unresolved library or mathematical searches as research tasks'); + expect(context.continuationMessage).not.toContain('Delegate unresolved library or mathematical searches as research tasks'); expect(context.message).toContain(JSON.stringify(context.workContract)); expect(context.continuationMessage).toContain(JSON.stringify(context.workContract)); expect(context.manifest).toMatchObject({ maxOptionalBytes: 0, optionalBytes: 0 }); @@ -275,13 +271,9 @@ it.each(['research', 'sketch', 'capacity-exploration'] as const)( frozenContexts: input([]).frozenContexts, maxOptionalContextBytes: 0 }); expect(context.workContract).toMatchObject({ stage: kind === 'capacity-exploration' ? kind : 'investigation', acceptance: 'advisory-only', sourcePolicy: 'read-only' }); - const guidance = context.workContract && 'deliveryGuidance' in context.workContract ? context.workContract.deliveryGuidance : ''; - expect(guidance).toContain('publish it promptly in lemmaRequests'); - expect(guidance).toContain('full closed Lean type and actual typed input dependencies'); - expect(guidance).toContain('distinct scope, first construction or Lean step, and intended consumer'); - expect(guidance).toContain('do not keep researching an already implementable step'); - expect(guidance).toContain('finite reduction or a uniform argument'); - expect(guidance).toContain('separate proof assignment and independent checking'); + expect(context.workContract).not.toHaveProperty('deliveryGuidance'); + expect(context.instructions).toContain('lemmaRequests'); + expect(context.continuationMessage).not.toContain('For a substantive finding or unresolved gap'); expect(context.message).toContain(JSON.stringify(context.workContract)); expect(context.continuationMessage).toContain(JSON.stringify(context.workContract)); expect(context.manifest).toMatchObject({ maxOptionalBytes: 0, optionalBytes: 0 }); @@ -477,8 +469,7 @@ it('projects advisory deliveries into recoverable references without duplicating expect(visible.actualReferences).toBeUndefined(); expect(visible.actualReferenceSource.sourceCommit).toBe(proof.references!.sourceCommit); expect(context.message).not.toMatch(/LOCAL_ONLY_ARTIFACT_HEADER|LOCAL_ONLY_DIAGNOSTICS|DUPLICATE_DELIVERY_RECEIPT/u); - expect(compiledGraph(context.message)[0].evidence.references.inputs).toHaveLength(proof.references!.inputs.length); - expect(compiledDictionary(context.message).entries).toHaveLength(2); + expect(contextLine(context.message, 'Lean references for consumer:')).toEqual(proof.references); expect(context.manifest.omitted).toContainEqual({ id: 'delivery:recoverable:details', kind: 'delivery', reason: 'advisory-details-by-reference' }); expect(context.manifest.usedBytes).toBeLessThan(16000); expect(record).toEqual(original); @@ -773,26 +764,7 @@ it('fails closed for unavailable frozen context instead of substituting a contex }); const contextLine = (message: string, label: string) => JSON.parse(message.split(`${label}\n`)[1].split('\n')[0]); -const encodedGraph = (message: string): any[] => contextLine(message, 'Lead task graph and host feedback:'); -const compiledGraph = (message: string): any[] => { - const dictionary = message.includes('Complete evidence reference dictionary (mandatory, recorded-not-replayed):') - ? compiledDictionary(message) : undefined; - return encodedGraph(message).map(row => { - if (!row.evidence) return row; - if (row.evidence.taskDigest === null) row.evidence.taskDigest = row.taskDigest; - if (row.integratedCommit === null) row.integratedCommit = row.evidence.commit; - if (row.checkedSourceDigest === null) row.checkedSourceDigest = row.evidence.sourceDigest; - for (const receipt of row.evidence.verification.receipts) - if (receipt.targetCommit === null) receipt.targetCommit = row.evidence.verification.targetCommit; - if (row.evidence.references?.tasks) row.evidence.references.tasks = row.evidence.references.tasks.map((entry: number) => dictionary!.entries[entry]); - return row; - }); -}; -const compiledDictionary = (message: string): { entries: any[]; digests: string[]; projectRelative: string; - encoding: string; digestExpansion: string } => - contextLine(message, 'Complete evidence reference dictionary (mandatory, recorded-not-replayed):'); -const expandedProofSource = (row: any) => row.source && { commit: row.evidence.commit, path: row.source.path, - sourceDigest: row.evidence.sourceDigest, ...(row.evidence.references ? { inputsFrom: 'evidence.references.inputs' } : {}) }; +const compiledGraph = (message: string): any[] => contextLine(message, 'Lead task graph and host feedback:'); function referenceProof(task: CooperativeTask, sourceCommit = proofCommit): TaskProof { const input = { file: 'Submission.lean', name: 'shared_support', digest: 'same-interface-digest' }, @@ -805,183 +777,46 @@ function referenceProof(task: CooperativeTask, sourceCommit = proofCommit): Task ({ ...result, receiptId: `receipt-${task.id}`, targetCommit: 'd'.repeat(40) })) } }; } -it('losslessly expands deduplicated references, their order, proof source paths and all mandatory evidence identities', () => { - const tasks = [lemma('first'), lemma('second')], proofs = tasks.map(task => referenceProof(task)); - // Equal objects with different property insertion order still share one dictionary entry. - proofs[1].references!.inputs[0] = { digest: 'same-interface-digest', name: 'shared_support', file: 'Submission.lean' }; - const context = compileTaskContext(input(tasks.map((task, index) => ({ ...node(task), status: 'integrated', integratedCheck: proofs[index] })))); - const graph = compiledGraph(context.message), dictionary = compiledDictionary(context.message); - expect(dictionary.entries).toHaveLength(2); - expect(context.manifest.included).toContainEqual(expect.objectContaining({ id: 'evidence-reference-dictionary', required: true })); - expect(context.manifest.included).toContainEqual(expect.objectContaining({ id: 'proof-source-reference-encoding', required: true })); - for (const [index, row] of graph.entries()) { - const references = row.evidence.references, original = proofs[index].references!; - for (const key of ['inputs', 'proof', 'statement'] as const) - expect(references[key].map((id: number) => dictionary.entries[id])).toEqual(original[key]); - expect(references.inputs[0]).toBe(references.inputs[1]); - expect(references.sourceCommit).toBe(original.sourceCommit); - expect(dictionary.digests[references.contextDigest]).toBe(original.contextDigest); - expect(dictionary.digests[references.environmentDigest]).toBe(original.environmentDigest); - expect(references.root).toEqual(original.root); - expect(references.tasks).toEqual(original.tasks); - expect(row.type).toBe(tasks[index].type); - expect(row.evidence.conditions).toEqual(proofs[index].conditions); - expect(row.evidence.verification.receipts).toEqual(proofs[index].verification.results); - expect(row.source.inputs).toBeUndefined(); - expect(row.source.evidenceFrom).toBe('evidence'); - expect(expandedProofSource(row)).toEqual({ commit: proofs[index].commit, - path: `${problem.projectRelative}/${tasks[index].proofPath}`, sourceDigest: proofs[index].sourceDigest, - inputsFrom: 'evidence.references.inputs' }); - const expandedSources = references.inputs.map((id: number) => ({ ...dictionary.entries[id], - commit: references.sourceCommit, path: `${dictionary.projectRelative}/${dictionary.entries[id].file}` })); - expect(expandedSources).toEqual(original.inputs.map(item => ({ ...item, commit: original.sourceCommit, - path: `${problem.projectRelative}/${item.file}` }))); - } -}); - -it('renders a mandatory digest dictionary when all declaration reference arrays are empty', () => { - const task = lemma('empty_references'), proof = referenceProof(task); - proof.references = { ...proof.references!, inputs: [], statement: [], proof: [] }; - const original = structuredClone(proof), context = compileTaskContext(input([ - { ...node(task), status: 'integrated', integratedCheck: proof }, - ])), dictionary = compiledDictionary(context.message), references = compiledGraph(context.message)[0].evidence.references; - expect(dictionary.encoding).toBe('evidence-reference-indices-v3'); - expect(dictionary.entries).toEqual([]); - expect(dictionary.digests).toEqual([proof.references.environmentDigest, proof.references.contextDigest]); - expect(dictionary.digestExpansion).toContain('environmentDigest or contextDigest'); - expect(dictionary.digestExpansion).toContain('exact original digest string'); - expect(context.manifest.included).toContainEqual(expect.objectContaining({ id: 'evidence-reference-dictionary', required: true })); - expect({ ...references, environmentDigest: dictionary.digests[references.environmentDigest], - contextDigest: dictionary.digests[references.contextDigest] }).toEqual(proof.references); - expect(proof).toEqual(original); -}); - -it('restores identical and distinct environment and context digests without changing any evidence identity', () => { - const tasks = [lemma('shared'), lemma('distinct_context'), lemma('distinct_environment')], - proofs = tasks.map((task, index) => referenceProof(task, String(index + 1).repeat(40))); - proofs[0].references = { ...proofs[0].references!, environmentDigest: 'a'.repeat(64), contextDigest: 'a'.repeat(64) }; - proofs[1].references = { ...proofs[1].references!, environmentDigest: 'a'.repeat(64), contextDigest: 'b'.repeat(64) }; - proofs[2].references = { ...proofs[2].references!, environmentDigest: 'c'.repeat(64), contextDigest: 'b'.repeat(64) }; - const original = structuredClone(proofs), context = compileTaskContext(input(tasks.map((task, index) => - ({ ...node(task), status: 'integrated', integratedCheck: proofs[index] })))), - graph = compiledGraph(context.message), dictionary = compiledDictionary(context.message); - expect(dictionary.digests).toEqual(['a'.repeat(64), 'b'.repeat(64), 'c'.repeat(64)]); - expect(graph[0].evidence.references.environmentDigest).toBe(graph[0].evidence.references.contextDigest); - for (const [index, row] of graph.entries()) { - const references = row.evidence.references; - expect({ ...references, environmentDigest: dictionary.digests[references.environmentDigest], - contextDigest: dictionary.digests[references.contextDigest], - ...Object.fromEntries(['inputs', 'statement', 'proof'].map(key => - [key, references[key].map((id: number) => dictionary.entries[id])])), - }).toEqual(proofs[index].references); - expect(row.evidence.commit).toBe(proofs[index].commit); - expect(row.evidence.verification.targetCommit).toBe(proofs[index].verification.targetCommit); - expect(row.evidence.verification.receipts).toEqual(proofs[index].verification.results); - expect(row.evidence.conditions).toEqual(proofs[index].conditions); - } - expect(proofs).toEqual(original); -}); - -it('expands shared source metadata for conditional and unconditional proofs without conflating the source or verifier commits', () => { - const dependency = lemma('condition'), conditional = { ...lemma('conditional', [dependency.id]), conditional: true }, - unconditional = lemma('unconditional'), withReferences = referenceProof(unconditional, '1'.repeat(40)), - withoutReferences = checked(conditional, [{ taskId: dependency.id, taskDigest: taskVersion(dependency) }]); - const context = compileTaskContext(input([{ ...node(unconditional), status: 'integrated', integratedCheck: withReferences }, - { ...node(conditional), status: 'conditional', proof: withoutReferences }, node(dependency)])); - const encoding = contextLine(context.message, 'Complete proof source reference encoding (mandatory, recorded-not-replayed):'), - graph = compiledGraph(context.message); - expect(encoding.encoding).toBe('proof-source-evidence-v2'); - expect(encoding.expansion).toContain('row.evidence.commit'); - expect(encoding.expansion).toContain('otherwise omit inputsFrom'); - expect(expandedProofSource(graph[0])).toEqual({ commit: withReferences.commit, sourceDigest: withReferences.sourceDigest, - path: `${problem.projectRelative}/${unconditional.proofPath}`, inputsFrom: 'evidence.references.inputs' }); - expect(expandedProofSource(graph[1])).toEqual({ commit: withoutReferences.commit, sourceDigest: withoutReferences.sourceDigest, - path: `${problem.projectRelative}/${conditional.proofPath}` }); - expect(graph[0].evidence.references.sourceCommit).toBe('1'.repeat(40)); - expect(graph[0].evidence.verification.targetCommit).toBe('d'.repeat(40)); - expect(expandedProofSource(graph[0]).commit).toBe(proofCommit); - expect(graph[1].evidence.conditions).toEqual(withoutReferences.conditions); - expect(graph[1]).toMatchObject({ status: 'active', executionStatus: 'conditional' }); -}); - -it('shares identical reference metadata without conflating distinct source commits or changed input digests', () => { - const tasks = [lemma('one'), lemma('two'), lemma('three')], commits = ['1'.repeat(40), '2'.repeat(40), '3'.repeat(40)], - proofs = tasks.map((task, index) => referenceProof(task, commits[index])); - proofs[2].references!.inputs = proofs[2].references!.inputs.map(item => ({ ...item, digest: 'changed-interface-digest' })); - const context = compileTaskContext(input(tasks.map((task, index) => ({ ...node(task), status: 'integrated', integratedCheck: proofs[index] })))); - const graph = compiledGraph(context.message), dictionary = compiledDictionary(context.message); - expect(graph[0].evidence.references.inputs).toEqual(graph[1].evidence.references.inputs); - expect(graph[0].evidence.references.sourceCommit).not.toBe(graph[1].evidence.references.sourceCommit); - expect(graph.map(row => row.evidence.references.sourceCommit)).toEqual(commits); - expect(graph[0].evidence.references.inputs).not.toEqual(graph[2].evidence.references.inputs); - expect(dictionary.entries[graph[2].evidence.references.inputs[0]].digest).toBe('changed-interface-digest'); - expect(graph[0].evidence.commit).toBe(proofCommit); - expect(graph[0].evidence.verification.targetCommit).toBe('d'.repeat(40)); -}); - -it.each(['.', 'generated\\p\\'])('reconstructs source paths with the original POSIX join rule for project %s', projectRelative => { - const task = lemma('source_path'), proof = referenceProof(task); - const context = compileTaskContext({ ...input([{ ...node(task), status: 'integrated', integratedCheck: proof }]), - problem: { ...problem, projectRelative } }); - const row = compiledGraph(context.message)[0], dictionary = compiledDictionary(context.message); - expect(dictionary.projectRelative).toBe(projectRelative.replaceAll('\\', '/')); - expect(row.source.path).toBe(path.posix.join(dictionary.projectRelative, task.proofPath!)); - for (const id of row.evidence.references.inputs) { - const restoredPath = path.posix.join(dictionary.projectRelative, dictionary.entries[id].file); - expect(restoredPath).toBe(path.posix.join(projectRelative.replaceAll('\\', '/'), proof.references!.inputs[0].file)); - } +it('shows exact proof identities and available Lean references without a decoding step', () => { + const task = lemma('current'), dependency = lemma('needed'), unrelated = lemma('unrelated'); + const current = { ...task, dependsOn: [dependency.id] }; + const proof = referenceProof(dependency, '1'.repeat(40)); + const records = [node(current), { ...node(dependency), status: 'integrated' as const, integratedCheck: proof }, + { ...node(unrelated), status: 'integrated' as const, integratedCheck: referenceProof(unrelated) }]; + const original = structuredClone(records); + const context = compileTaskContext(input(records, assign(current))); + const row = compiledGraph(context.message).find(task => task.id === dependency.id); + expect(row.evidence).toMatchObject({ commit: proof.commit, path: path.posix.join(problem.projectRelative, dependency.proofPath!), + sourceDigest: proof.sourceDigest, taskDigest: proof.taskDigest, + verification: { targetCommit: proof.verification.targetCommit, receipts: proof.verification.results }, + references: { sourceCommit: proof.references!.sourceCommit, environmentDigest: proof.references!.environmentDigest, + contextDigest: proof.references!.contextDigest } }); + expect(contextLine(context.message, 'Lean references for needed:')).toEqual(proof.references); + expect(context.message).not.toContain('Lean references for unrelated:'); + expect(context.message).not.toContain('Complete evidence reference dictionary'); + expect(records).toEqual(original); }); -it('fits a large repeated-reference graph in the unchanged byte budget while preserving every exact task interface', () => { +it('keeps exact interfaces and locators under budget when complete evidence inventories are too large', () => { const tasks = Array.from({ length: 60 }, (_, index) => lemma(`checkpoint${index}`, [], `∀ n : Nat, ${'n = n ∧ '.repeat(80)}True`)); const inputs = Array.from({ length: 60 }, (_, index) => ({ file: 'Submission.lean', - name: `shared_long_declaration_name_${index}`, digest: String(index).padStart(64, '0') })), - declarationRefs = inputs.map(({ file, name }) => ({ file, name })); + name: `shared_long_declaration_name_${index}`, digest: String(index).padStart(64, '0') })); + const declarationRefs = inputs.map(({ file, name }) => ({ file, name })); const records = tasks.map(task => ({ ...node(task), status: 'integrated' as const, integratedCheck: { ...referenceProof(task), references: { ...referenceProof(task).references!, inputs, proof: declarationRefs, statement: declarationRefs }, } })); - const context = compileTaskContext(input(records)), graph = compiledGraph(context.message), - dictionary = compiledDictionary(context.message); + const context = compileTaskContext(input(records)), graph = compiledGraph(context.message); + expect(Buffer.byteLength(canonicalMathJson(records))).toBeGreaterThan(DEFAULT_TASK_CONTEXT_BYTES); expect(context.manifest.usedBytes).toBeLessThanOrEqual(DEFAULT_TASK_CONTEXT_BYTES); - expect(context.manifest.requiredTaskIds).toHaveLength(tasks.length); + expect(context.manifest.requiredTaskIds).toEqual(tasks.map(task => task.id)); expect(graph.map(row => row.type)).toEqual(tasks.map(task => task.type)); - const expanded = graph.map(row => { - const references = row.evidence.references; - const arrays = Object.fromEntries(['inputs', 'proof', 'statement'].map(key => - [key, references[key].map((id: number) => dictionary.entries[id])])); - return { ...row, evidence: { ...row.evidence, references: { ...references, ...arrays, - environmentDigest: dictionary.digests[references.environmentDigest], - contextDigest: dictionary.digests[references.contextDigest] } }, source: { - ...expandedProofSource(row), - inputs: arrays.inputs.map((item: any) => ({ ...item, commit: references.sourceCommit, - path: `${dictionary.projectRelative}/${item.file}` })), - } }; - }); - expect(Buffer.byteLength(canonicalMathJson(expanded))).toBeGreaterThan(DEFAULT_TASK_CONTEXT_BYTES); - expect(dictionary.entries).toHaveLength(inputs.length + declarationRefs.length); -}); - -it('shares exact task reference metadata and proof fields without losing receipt targets or array order', () => { - const tasks = [lemma('first'), lemma('second')], proofs = tasks.map(task => referenceProof(task)); - const references = [{ taskId: tasks[0].id, taskDigest: taskVersion(tasks[0]) }, - { taskId: tasks[1].id, taskDigest: taskVersion(tasks[1]) }]; - for (const proof of proofs) proof.references!.tasks = [references[1], references[0], references[1]]; - const context = compileTaskContext(input(tasks.map((task, index) => ({ ...node(task), status: 'integrated', integratedCheck: proofs[index] })))), - raw = encodedGraph(context.message), dictionary = compiledDictionary(context.message), graph = compiledGraph(context.message); - expect(dictionary.entries.filter(entry => 'taskId' in entry)).toEqual([references[1], references[0]]); - for (const [index, row] of raw.entries()) { - expect(row.evidence.references.tasks).toEqual(raw[0].evidence.references.tasks); - expect(row.evidence.references.tasks[0]).toBe(row.evidence.references.tasks[2]); - expect(row.evidence.taskDigest).toBeNull(); - expect(row.integratedCommit).toBeNull(); - expect(row.checkedSourceDigest).toBeNull(); - expect(row.evidence.verification.receipts[0].targetCommit).toBeNull(); - expect(graph[index].evidence.references.tasks).toEqual(proofs[index].references!.tasks); - expect(graph[index].evidence.taskDigest).toBe(proofs[index].taskDigest); - expect(graph[index].integratedCommit).toBe(proofs[index].commit); - expect(graph[index].checkedSourceDigest).toBe(proofs[index].sourceDigest); - expect(graph[index].evidence.verification.receipts).toEqual(proofs[index].verification.results); + expect(context.message).toContain('matching task ID in worktree-root COOPERATION.json tasks'); + for (const [index, row] of graph.entries()) { + const proof = records[index].integratedCheck; + expect(row.evidence).toMatchObject({ commit: proof.commit, sourceDigest: proof.sourceDigest, + taskDigest: proof.taskDigest, verification: { receipts: proof.verification.results } }); + expect(row.evidence.references.inputs).toBeUndefined(); } }); @@ -990,11 +825,8 @@ it('does not replace distinct or absent failed receipt targets with an enclosing proof.passed = false; proof.verification.results = [{ receiptId: 'distinct', status: 'kernel_rejected', targetCommit: 'e'.repeat(40) }, { receiptId: 'absent', status: 'kernel_rejected' }] as TaskProof['verification']['results']; - const context = compileTaskContext(input([{ ...node(task), proof }])), row = encodedGraph(context.message)[0]; + const context = compileTaskContext(input([{ ...node(task), proof }])), row = compiledGraph(context.message)[0]; expect(row.evidence.verification.receipts).toEqual(proof.verification.results); - expect(compiledGraph(context.message)[0].evidence.verification.receipts).toEqual(proof.verification.results); - expect(row.integratedCommit).toBeUndefined(); - expect(row.checkedSourceDigest).toBeUndefined(); }); const lead = { kind: 'lead' as const, seedCommit: baseCommit }; @@ -1250,7 +1082,7 @@ it('fits a mature Lead graph with many direct checked inputs without raising the for (const helper of helpers) { const row = graph.find(row => row.id === helper.task.id); expect(row.evidence.verification.receipts).toEqual(helper.integratedCheck!.verification.results); - expect(expandedProofSource(row)).toMatchObject({ commit: helper.integratedCheck!.commit, + expect(row.evidence).toMatchObject({ commit: helper.integratedCheck!.commit, sourceDigest: helper.integratedCheck!.sourceDigest }); } expect(context.message).toContain('COMPLETE_OPEN_TASK_DESCRIPTION'); @@ -1407,7 +1239,6 @@ it('uses host-checked actual dependencies without reviving an unused planned inp .toEqual([{ taskId: 'b', taskDigest: taskVersion(lemma('b')) }]); const unused = compiledGraph(context.message).find(row => row.id === 'a'); expect(unused?.evidence).toBeUndefined(); - expect(unused?.source).toBeUndefined(); expect(context.message).not.toContain('STALE_UNUSED_A_SOURCE'); expect(context.message).not.toContain('STALE_UNUSED_A_RECEIPT'); }); diff --git a/tests/contextDispatchBudget.test.ts b/tests/contextDispatchBudget.test.ts index dd174a67..e11dd6d9 100644 --- a/tests/contextDispatchBudget.test.ts +++ b/tests/contextDispatchBudget.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import type { SolverRunState } from '../src/solver/archive'; -import { canonicalMathJson, mathDigest } from '../src/math/mathRuntimeIo'; +import { mathDigest } from '../src/math/mathRuntimeIo'; import { compileTaskContext, DEFAULT_TASK_CONTEXT_BYTES, frozenSourceContext, type TaskContextInput } from '../src/solver/contextCompiler'; import { rejectedDeliveryReceipt, deliveryReceiptFeedback, type DeliveryReceipt } from '../src/solver/deliveryReceipts'; import type { DeliveryRecord } from '../src/solver/deliveries'; @@ -152,8 +152,9 @@ describe('bounded continuation dispatch', () => { for (const message of [context.message, context.continuationMessage!]) { const reference = JSON.parse(message.split('Pending assignment correction receipts (retrieve all before correcting deliveries):\n')[1].split('\n')[0]); expect(reference).toMatchObject({ file: 'COOPERATION.json', field: 'deliveryReceipts', count: receipts.length, - digest: mathDigest(canonicalMathJson(receipts)), scope: { taskId: 'current', status: 'needs-correction' } }); - expect(reference.retrieval).toContain('every'); + status: 'needs-correction' }); + expect(reference.retrieval).toContain('every current needs-correction row'); + expect(reference.digest).toBeUndefined(); } for (const manifest of [context.manifest!, context.continuationManifest!]) { expect(manifest.omitted).toContainEqual(expect.objectContaining({ id: 'assignment-receipts', kind: 'feedback' })); diff --git a/tests/deliveryReceipts.test.ts b/tests/deliveryReceipts.test.ts index 7d7ecfc2..a769247b 100644 --- a/tests/deliveryReceipts.test.ts +++ b/tests/deliveryReceipts.test.ts @@ -44,15 +44,16 @@ describe('delivery receipt correction chains', () => { const second = reject({ kind: 'research', finding: { summary: 'Rejected correction', replacesReceipt: first.id } }, [first]); const independent = reject({ summary: 'Independent rejection' }); const foreign = { ...reject({ summary: 'Foreign rejection' }), workerId: 'other-writer' }; + const stale = { ...reject({ summary: 'Wrong seed rejection' }), seedCommit: 'b'.repeat(40) }; // A restored link outside the dispatch must never be followed by the resolver. first.replacesReceipt = foreign.id; const node = { task, feedback: deliveryReceiptFeedback(second) }; - const receipts = JSON.parse(JSON.stringify([first, second, independent, foreign])) as DeliveryReceipt[]; + const receipts = JSON.parse(JSON.stringify([first, second, independent, foreign, stale])) as DeliveryReceipt[]; const cooperative = Object.create(CooperativeResearch.prototype) as any; Object.assign(cooperative, { archive: { tasks: [node], deliveryReceipts: receipts }, input: { state: { environmentDigest: 'environment' } } }); cooperative.resolveDeliveryReceipts({ id: 'writer' }, action, second.id); - expect(receipts.map(receipt => receipt.status)).toEqual(['recorded', 'recorded', 'needs-correction', 'needs-correction']); + expect(receipts.map(receipt => receipt.status)).toEqual(['recorded', 'recorded', 'needs-correction', 'needs-correction', 'needs-correction']); expect(node.feedback).toBe(deliveryReceiptFeedback(independent)); expect(receipts[0].assignmentKey).toBe(assignmentDeliveryFile(action.assignment)); }); diff --git a/tests/finalCandidateReadiness.test.ts b/tests/finalCandidateReadiness.test.ts index a41de5c0..4884c967 100644 --- a/tests/finalCandidateReadiness.test.ts +++ b/tests/finalCandidateReadiness.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { criticalPathResearchTasks, finalCandidateReviewReady, goalsFirstResearchTasks, +import { criticalPathResearchTasks, goalsFirstResearchTasks, readyResearchTasks, taskCanStart } from '../src/solver/modules/search'; import { isFinalCandidateReview, markTaskAcceptance, parseCooperationPlan, taskVersion, type CooperativeTask, type TaskRecord } from '../src/solver/tasks'; @@ -10,49 +10,27 @@ const node = (id: string, kind: CooperativeTask['kind']): TaskRecord => ({ ...(kind === 'goal' ? { proofPath: 'Submission.lean', theoremName: `Submission.${id}` } : {}) }, status: 'pending', attempts: 0, }); -function accepted(record: TaskRecord, fresh = true) { +function accepted(record: TaskRecord) { record.status = 'integrated'; record.integratedCheck = { passed: true, taskDigest: taskVersion(record.task), conditions: [], commit: 'source', sourceDigest: 'digest', seedCommit: 'seed', changes: [], verification: { schema: 'deepscientist.mathematics.verification-batch/v1', status: 'kernel_verified', targetCommit: 'projection', sessionId: 'fixture', startedAt: 1, checkedAt: 2, durationMs: 1, events: [], results: [] } }; - if (fresh) markTaskAcceptance(record.integratedCheck); + markTaskAcceptance(record.integratedCheck); return record; } -describe('final candidate research dispatch gate', () => { - it.each(['research', 'sketch'] as const)('requires every fresh original goal before a %s candidate review', kind => { - const first = accepted(node('first', 'goal')), second = node('second', 'goal'), review = node('review', kind); - review.task = { ...review.task, reviewScope: 'final-candidate' }; - const tasks = [review, first, second]; +describe('candidate review is reserved for the fixed Reviewer', () => { + it.each(['research', 'sketch', 'legacy'] as const)('never schedules a %s candidate review as ordinary work', kind => { + const goal = accepted(node('goal', 'goal')); + const review = node(kind === 'legacy' ? 'independent_candidate_review' : 'review', kind === 'sketch' ? 'sketch' : 'research'); + review.task = { ...review.task, reviewScope: kind === 'legacy' ? 'feasibility' : 'final-candidate' }; + const tasks = [goal, review]; + expect(isFinalCandidateReview(review.task)).toBe(true); expect(taskCanStart(review.task, tasks)).toBe(false); for (const select of [readyResearchTasks, criticalPathResearchTasks, goalsFirstResearchTasks]) expect(select(tasks)).not.toContain(review); - accepted(second, false); - expect(finalCandidateReviewReady(tasks)).toBe(false); - markTaskAcceptance(second.integratedCheck!); - expect(finalCandidateReviewReady(tasks)).toBe(true); - expect(taskCanStart(review.task, tasks)).toBe(true); - expect(readyResearchTasks(tasks)).toContain(review); - }); - - it('blocks legacy final review even when its ordinary research dependencies are empty or relabeled', () => { - const review = node('independent_candidate_review', 'research'); - review.task = { ...review.task, reviewScope: 'feasibility' }; - expect(isFinalCandidateReview(review.task)).toBe(true); - expect(taskCanStart(review.task, [review])).toBe(false); - expect(taskCanStart(review.task, [review, node('goal', 'goal')])).toBe(false); - }); - - it.each(['conditional', 'revision', 'archived', 'source-mutated'] as const)('does not unlock on %s acceptance', flaw => { - const goal = accepted(node('goal', 'goal')), review = node('review', 'research'); - review.task = { ...review.task, reviewScope: 'final-candidate' }; - if (flaw === 'conditional') goal.integratedCheck = { ...goal.integratedCheck!, conditions: [{ taskId: 'missing', taskDigest: 'old' }] }; - if (flaw === 'revision') goal.task = { ...goal.task, revision: 1 }; - if (flaw === 'archived') goal.integratedCheck = JSON.parse(JSON.stringify(goal.integratedCheck)); - if (flaw === 'source-mutated') (goal.integratedCheck as any).sourceDigest = 'changed-after-acceptance'; - expect(taskCanStart(review.task, [goal, review])).toBe(false); }); it('keeps mathematical feasibility research available before its proof dependencies', () => { diff --git a/tests/fixtures/agentTeamFollowupPeer.cjs b/tests/fixtures/agentTeamFollowupPeer.cjs index e0d90f3f..a89738a3 100644 --- a/tests/fixtures/agentTeamFollowupPeer.cjs +++ b/tests/fixtures/agentTeamFollowupPeer.cjs @@ -48,8 +48,8 @@ function complete(stage, text, status = 'completed') { function checkRole(method, params) { const lead = actor === 'lead'; - const expected = lead ? ['spawn', 'assign', 'amend', 'finish', 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'adopt', 'stop', 'publish', 'cancel', 'budget', 'resume', 'history', 'coordinate', 'retire_route', 'route_summary'] - : ['message', 'poll', 'wait', 'inspect', 'inspect-research', 'submit', 'submit_helpers', 'yield', 'history', 'progress', 'route_summary']; + const expected = lead ? ['spawn', 'assign', 'amend', 'finish', 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'adopt', 'stop', 'publish', 'cancel', 'budget', 'resume', 'history', 'retire_route', 'route_summary'] + : ['message', 'poll', 'wait', 'inspect', 'inspect-research', 'submit', 'yield', 'history', 'progress', 'route_summary']; const identity = lead ? 'You are the Lead of an Agent-organized research team; your agentId is lead.' : `You are a mathematical researcher and Lean proof writer; your agentId is ${JSON.stringify(actor)}, and your coordinator is lead.`; assert(params.developerInstructions.includes(identity), 'current-developer-identity-missing'); diff --git a/tests/fixtures/agentTeamHandoffPeer.cjs b/tests/fixtures/agentTeamHandoffPeer.cjs index f7960c0b..733b63eb 100644 --- a/tests/fixtures/agentTeamHandoffPeer.cjs +++ b/tests/fixtures/agentTeamHandoffPeer.cjs @@ -47,8 +47,8 @@ function complete(stage, text, status = 'completed') { function checkRole(method, params) { const expected = actor === 'lead' - ? ['spawn', 'assign', 'amend', 'finish', 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'adopt', 'stop', 'publish', 'cancel', 'budget', 'resume', 'history', 'coordinate', 'retire_route', 'route_summary'] - : ['message', 'poll', 'wait', 'inspect', 'inspect-research', 'submit', 'submit_helpers', 'yield', 'history', 'progress', 'route_summary']; + ? ['spawn', 'assign', 'amend', 'finish', 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'adopt', 'stop', 'publish', 'cancel', 'budget', 'resume', 'history', 'retire_route', 'route_summary'] + : ['message', 'poll', 'wait', 'inspect', 'inspect-research', 'submit', 'yield', 'history', 'progress', 'route_summary']; assert(params.config['features.multi_agent'] === false && params.config['features.multi_agent_v2'] === false, 'native-unmanaged-delegation-enabled'); if (method === 'thread/start') { diff --git a/tests/fixtures/agentTeamPeer.cjs b/tests/fixtures/agentTeamPeer.cjs index c9db691c..bfb87c67 100644 --- a/tests/fixtures/agentTeamPeer.cjs +++ b/tests/fixtures/agentTeamPeer.cjs @@ -158,8 +158,8 @@ stream.on('line', line => { threadId = params.threadId || threadId; if (call.method === 'thread/start') { const expected = actor === 'lead' - ? ['spawn', 'assign', 'amend', 'finish', 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'adopt', 'stop', 'publish', 'cancel', 'budget', 'resume', 'history', 'coordinate', 'retire_route', 'route_summary'] - : ['message', 'poll', 'wait', 'inspect', 'inspect-research', 'submit', 'submit_helpers', 'yield', 'history', 'progress', 'route_summary']; + ? ['spawn', 'assign', 'amend', 'finish', 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'adopt', 'stop', 'publish', 'cancel', 'budget', 'resume', 'history', 'retire_route', 'route_summary'] + : ['message', 'poll', 'wait', 'inspect', 'inspect-research', 'submit', 'yield', 'history', 'progress', 'route_summary']; const tool = params.dynamicTools.find(tool => tool.name === 'theoremos_team'); if (!tool || JSON.stringify(tool.inputSchema.properties.operation.enum.toSorted()) !== JSON.stringify(expected.toSorted())) throw new Error('role-operation-schema-mismatch'); diff --git a/tests/fixtures/web-cooperative-codex.mjs b/tests/fixtures/web-cooperative-codex.mjs index 2cc2a009..c29d264f 100644 --- a/tests/fixtures/web-cooperative-codex.mjs +++ b/tests/fixtures/web-cooperative-codex.mjs @@ -4,7 +4,7 @@ import path from 'node:path'; export const cooperativeEditId = 'web-cooperative-edit'; export const cooperativeGuidanceMarker = 'WEB_COOPERATIVE_PROVE_FIRST'; -export const cooperativeReviewMarker = 'WEB_COOPERATIVE_RELEASE_REVIEW'; +export const cooperativeSecondProofMarker = 'WEB_COOPERATIVE_PROVE_SECOND'; function workContract(message) { for (const line of message.split('\n')) { @@ -35,11 +35,6 @@ export function createCooperativeFixture({ workspace, source, message, instructi fs.appendFileSync(path.join(workspace, file), JSON.stringify({ kind: 'ready', summary: `Saved ${taskId} for independent host checking.` }) + '\n'); complete(); }; - const finishReview = () => { - notes({ commit: contract.input.seedCommit, verdict: 'accepted', - summary: 'Offline independent reviewer inspected the fixed two-target candidate; only host Lean/S3 checks can accept it.' }); - complete(); - }; if (contract.stage === 'route-planning') { const revised = edited(); const tasks = [ @@ -62,17 +57,16 @@ export function createCooperativeFixture({ workspace, source, message, instructi // Keep Lead active while the Engineer receives human guidance on its own turn. } } else if (contract.stage === 'formal-proof') { - if (contract.input.taskId !== 'goal_1' || edited()) pending = setTimeout(finishProof, 50); - } else if (contract.stage !== 'candidate-review') { + if (contract.input.taskId === 'goal_1' && edited()) pending = setTimeout(finishProof, 50); + } else { throw new Error('web_fixture_unexpected_cooperative_stage'); } return { steer(text) { - if (contract.stage === 'formal-proof' && text.includes(cooperativeGuidanceMarker)) { + if (contract.stage === 'formal-proof' && text.includes( + contract.input.taskId === 'goal_1' ? cooperativeGuidanceMarker : cooperativeSecondProofMarker)) { receivedGuidance = text; clearTimeout(pending); pending = setTimeout(finishProof, 100); - } else if (contract.stage === 'candidate-review' && text.includes(cooperativeReviewMarker)) { - clearTimeout(pending); pending = setTimeout(finishReview, 100); } }, cancel() { clearTimeout(pending); }, diff --git a/tests/frontierPriorityContext.test.ts b/tests/frontierPriorityContext.test.ts index 34d20114..8c5a2439 100644 --- a/tests/frontierPriorityContext.test.ts +++ b/tests/frontierPriorityContext.test.ts @@ -4,7 +4,7 @@ import type { CooperationState } from '../src/solver/cooperation'; import type { SolverRunState } from '../src/solver/archive'; import type { SolverProblem } from '../src/solver/problem'; import { buildResearchContext } from '../src/solver/modules/context'; -import { assignmentDeliveryFile, initialPlanDeliveryFile, taskVersion, type CooperativeAction, type TaskRecord } from '../src/solver/tasks'; +import { assignmentDeliveryFile, taskVersion, type CooperativeAction, type TaskRecord } from '../src/solver/tasks'; import { canonicalMathJson, mathDigest } from '../src/math/mathRuntimeIo'; const seedCommit = 'a'.repeat(40); @@ -50,7 +50,7 @@ const withoutOptionalContext = () => { afterEach(() => vi.restoreAllMocks()); it.each(['lemma', 'goal', 'research', 'sketch'] as const)( - 'retains the complete %s delivery protocol without optional context or repeated protocol text', kind => { + 'keeps the %s delivery entry points available without optional context', kind => { withoutOptionalContext(); const record = node('assigned', kind), action = actionFor(record); if (action.kind !== 'task') throw new Error('fixture_assignment'); @@ -60,27 +60,29 @@ it.each(['lemma', 'goal', 'research', 'sketch'] as const)( expect(context.manifest!.included).toContainEqual(expect.objectContaining({ id: 'assignment-policy', required: true })); expect(context.message).toContain('Current delivery log: ' + assignmentDeliveryFile(action.assignment)); expect(context.instructions).toContain('"kind":"helpers","declarations":'); - expect(context.instructions).toContain('"kind":"research","finding":'); - expect(context.instructions).toContain('publishing does not finish or park your proof task'); - expect(context.instructions).toContain('The host freezes the saved sources and independently checks and integrates them'); - expect(context.instructions).toContain('Do not truncate the delivery log'); - expect((context.instructions + context.message).match(/To share before returning/g)).toHaveLength(1); + expect(context.instructions).toContain('Use research-observe from .scratch/theoremos-help.md'); + expect(context.toolHelp?.text).toContain("--finding '.scratch/finding.json'"); + if (kind === 'lemma' || kind === 'goal') { + expect(context.instructions).toContain('save the assigned declaration and return for host checking'); + } else { + expect(context.instructions).toContain('return with RESEARCH.md to deliver an advisory assignment'); + } + expect(context.instructions).not.toContain('"kind":"research","finding":'); expect(context.message).toContain(`Your role: ${kind === 'goal' ? 'engineer' : kind === 'lemma' ? 'prover' : 'researcher'}`); expect(context.message).toContain('Delivery protocol: see session instructions.'); expect(context.message).toContain(formal); }); -it('retains the complete initial plan publication protocol without optional context or repeated protocol text', () => { +it('keeps initial plan publication available without optional context', () => { withoutOptionalContext(); const action: CooperativeAction = { kind: 'lead', seedCommit, initialPlanNonce: 'publication', planVersion: 'plan-version' }; const context = contextFor({ canonicalCommit: seedCommit, tasks: [] }, action); expect(context.manifest).toMatchObject({ maxOptionalBytes: 0, optionalBytes: 0 }); - expect(context.instructions).toContain(initialPlanDeliveryFile(action)); - expect(context.instructions).toContain('"kind":"plan","baseVersion":"plan-version"'); - expect(context.instructions).toContain('Only the first valid publication in this dispatch is accepted'); - expect(context.instructions).toContain('Do not truncate the log'); - expect((context.instructions + context.message).match(/Once a useful executable plan is ready, publish it promptly/g)).toHaveLength(1); + expect(context.instructions).toContain('Edit only /proof/RESEARCH.md, /proof/.scratch/plan.json.'); + expect(context.instructions).toContain('The host accepts only one publication per dispatch'); + expect(context.toolHelp?.text).toContain('plan-apply --publish --file .scratch/plan.json'); + expect(context.message).toContain(JSON.stringify(action)); expect(context.message).toContain('Your role: lead'); expect(context.message).toContain('Delivery protocol: see session instructions.'); expect(context.message).toContain(formal); diff --git a/tests/fullSkillWorkflow.test.ts b/tests/fullSkillWorkflow.test.ts index ecdb9818..8b4f549d 100644 --- a/tests/fullSkillWorkflow.test.ts +++ b/tests/fullSkillWorkflow.test.ts @@ -1,14 +1,13 @@ import fs from 'node:fs'; import path from 'node:path'; import { afterEach, describe, expect, it } from 'vitest'; -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'; +import { assignmentDeliveryFile, parseCooperationPlan, taskVersion } from '../src/solver/tasks'; import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; const roots: string[] = []; @@ -51,12 +50,12 @@ describe('Skill methods with complete host workflows', () => { expect(context.instructions).not.toContain('comparison arms'); 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)); + expect(context.instructions).toContain('plan-apply --publish'); 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); + expect(leadHelp).toContain('plan-apply --publish --file .scratch/plan.json'); + expect(leadHelp).not.toContain('plan-validate'); const reference = path.join(path.dirname(f.skill.path), 'references/cooperation.md'); expect(context.instructions).toContain(reference); const protocol = fs.readFileSync(reference, 'utf8'); @@ -87,7 +86,7 @@ describe('Skill methods with complete host workflows', () => { { ...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.split(/^## /mu)[1]).toContain(`bun '${tools}' plan-apply --publish --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'); }); @@ -137,8 +136,8 @@ describe('Skill methods with complete host workflows', () => { assignmentDeliveryFile(assignment)]) expect(dispatch.message).toContain(current); expect(dispatch.message).not.toContain('OLD_PROOF_ERROR'); const index = JSON.parse(dispatch.message.split('Pending assignment correction receipts (retrieve all before correcting deliveries):\n')[1]!.split('\n')[0]!); - expect(index).toMatchObject({ count: 2, digest: mathDigest(canonicalMathJson(cooperation.deliveryReceipts)), - scope: { taskId: node.task.id, assignmentKey: assignmentDeliveryFile(assignment) } }); + expect(index).toMatchObject({ count: 2, file: 'COOPERATION.json', field: 'deliveryReceipts', status: 'needs-correction' }); + expect(index.retrieval).toContain('replacesReceipt set to its id'); expect(dispatch.manifest!.included).toContainEqual(expect.objectContaining({ id: 'assignment-receipt-index', required: true })); expect(dispatch.manifest!.omitted).toContainEqual(expect.objectContaining({ id: 'assignment-receipts', reason: 'optional-budget' })); expect(dispatch.manifest!.optionalBytes).toBe(0); diff --git a/tests/helpers/solverAtomicPlanRejection.ts b/tests/helpers/solverAtomicPlanRejection.ts index fea1ee33..f687a0de 100644 --- a/tests/helpers/solverAtomicPlanRejection.ts +++ b/tests/helpers/solverAtomicPlanRejection.ts @@ -31,7 +31,7 @@ describe('CooperativeResearch malformed plans', () => { if (action?.kind !== 'lead') throw new Error('fixture_expected_lead'); expect(research.started(lead, action)).toBe(true); research.activate(lead, action, async () => {}, async () => {}); - expect(research.leadCheckpointInstruction(action)).toContain('theorem-os plan-validate'); + expect(research.leadCheckpointInstruction(action)).toContain('plan-apply'); const file = path.join(lead.worktree, 'RESEARCH.md'); fs.writeFileSync(file, notes); editLean?.(); diff --git a/tests/humanGuidance.test.ts b/tests/humanGuidance.test.ts index 5e972bdd..de59d221 100644 --- a/tests/humanGuidance.test.ts +++ b/tests/humanGuidance.test.ts @@ -1,11 +1,13 @@ import fs from 'node:fs'; import path from 'node:path'; +import { execFileSync } from 'node:child_process'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { queueHumanGuidance, deliverHumanGuidance, readHumanGuidance, recordHumanGuidanceDecisions, withdrawHumanGuidance, humanGuidanceInputSchema, type HumanGuidanceCandidate, type HumanGuidanceInput, type HumanGuidanceDecisionInput } from '../src/solver/humanGuidance'; import { webGuidanceSchema } from '../apps/web/collaborationValidation'; import { mathDigest } from '../src/math/mathRuntimeIo'; import { runInspectionSnapshot } from '../src/solver/inspection'; +import { buildResearchContext } from '../src/solver/modules/context'; import { assignmentDeliveryFile, taskVersion, type CooperativeAction } from '../src/solver/tasks'; import { cooperativeResearch } from './helpers/cooperation'; import { webWorkerFixture } from './helpers/webWorkerBridge'; @@ -106,19 +108,38 @@ describe('independent host guidance input', () => { it('uses the cooperative host checkpoint and preserves role/task ownership', async () => { const f = fixture(), input = guidanceFor(f); await queueHumanGuidance(f.output, input); - const worker = { id: 'engineer', role: 'engineer' as const, worktree: f.worktree, ownedFiles: f.state.problem.ownedFiles }; - const lead = { ...worker, id: 'solver', role: 'lead' as const }; + const workerWorktree = path.join(path.dirname(f.stateFile), 'engineer'); + execFileSync('git', ['-C', f.worktree, 'worktree', 'add', '--detach', '--quiet', workerWorktree, f.currentCommit]); + const worker = { id: 'engineer', role: 'engineer' as const, worktree: workerWorktree, ownedFiles: f.state.problem.ownedFiles }; + const lead = { ...worker, id: 'solver', role: 'lead' as const, worktree: f.worktree }; const node = f.state.cooperation!.tasks[1]; const assignment = { taskId: 'goal', taskDigest: taskVersion(f.goal), workerId: worker.id, seedCommit: f.currentCommit }; node.assignment = assignment; node.status = 'running'; const host = cooperativeResearch({ state: f.state, workers: [lead, worker], retrievalRoot: f.directory }); const notify = vi.fn(async (_message: string) => {}); - host.activate(worker, { kind: 'task', task: node.task, assignment }, async () => {}, notify); + const action: CooperativeAction = { kind: 'task', task: node.task, assignment }; + host.activate(worker, action, async () => {}, notify); await host.pulse(worker.id); expect(notify).toHaveBeenCalledOnce(); expect(readHumanGuidance(f.stateFile, f.state.runId)[0]).toMatchObject({ status: 'delivered', deliveredTo: ['engineer'] }); host.deactivate(worker); expect(node.assignment).toBe(assignment); expect(node.task).toEqual(f.goal); + + const scoped = host.contextState(action, worker); + const problem = { ...f.state.problem, declarations: { 'Submission.lean': [{ name: 'goal', header: 'goal : True' }] } }; + const context = buildResearchContext(problem, { ...f.state, problem, cooperation: scoped }, { root: f.directory, + worktree: workerWorktree, retrievalRoot: f.directory, environment: {}, taskText: 'Prove the original goal.', assignment: action }); + for (const message of [context.message, context.continuationMessage]) { + expect(message).toContain('COOPERATION.json.humanGuidance'); + expect(message).toContain(input.id); + expect(message).toContain('guidanceDecisions'); + expect(message).not.toContain(input.text); + } + host.activate(worker, action, async () => {}, notify); + const readView = (worktree: string) => JSON.parse(fs.readFileSync(path.join(worktree, 'COOPERATION.json'), 'utf8')); + expect(readView(workerWorktree).humanGuidance).toEqual([expect.objectContaining({ id: input.id, text: input.text, taskRef: input.taskRef })]); + expect(readView(f.worktree).humanGuidance).toBeUndefined(); + host.deactivate(worker); }); it('delivers a complete 128 KiB advisory candidate to the actual assigned agent without executing or writing it', async () => { diff --git a/tests/inspection.test.ts b/tests/inspection.test.ts index 46586798..7eafad71 100644 --- a/tests/inspection.test.ts +++ b/tests/inspection.test.ts @@ -641,6 +641,22 @@ describe('human plan edits', () => { await expect(queueRunEdit(f.run, { ...plan, tasks: [{ ...plan.tasks[0], status: 'active' }] })).rejects.toThrow('id_conflict'); }); + it('finds queued edits and appends new ones past malformed complete records', async () => { + const f = fixture(), plan = { ...exportRunPlan(f.state), id: 'first-edit' }; + const log = path.join(path.dirname(f.stateFile), 'edits.jsonl'); + await queueRunEdit(f.run, plan); + const existing = Buffer.concat([Buffer.from('{broken\nnull\n'), fs.readFileSync(log), Buffer.from([0xff, 0x0a])]); + fs.writeFileSync(log, existing); + + expect(await queueRunEdit(f.run, plan)).toMatchObject({ status: 'already_queued' }); + await expect(queueRunEdit(f.run, { ...plan, baseVersion: 'old' })).rejects.toThrow('id_conflict'); + expect(fs.readFileSync(log)).toEqual(existing); + expect(await queueRunEdit(f.run, { ...plan, id: 'second-edit' })).toMatchObject({ status: 'queued' }); + const saved = fs.readFileSync(log); + expect(saved.subarray(0, existing.length)).toEqual(existing); + expect(JSON.parse(saved.subarray(existing.length).toString('utf8')).id).toBe('second-edit'); + }); + it('rejects stale versions, cyclic plans and missing original goals before appending', async () => { const f = fixture(), plan = exportRunPlan(f.state); await expect(queueRunEdit(f.run, { ...plan, baseVersion: 'old' })).rejects.toThrow('version_conflict'); @@ -672,7 +688,13 @@ describe('human plan edits', () => { const other = path.join(f.root, 'other'); fs.writeFileSync(other, 'outside'); fs.symlinkSync(other, log); await expect(queueRunEdit(f.run, exportRunPlan(f.state))).rejects.toThrow(); expect(fs.readFileSync(other, 'utf8')).toBe('outside'); - fs.unlinkSync(log); fs.writeFileSync(log, '{"id":'); - await expect(queueRunEdit(f.run, exportRunPlan(f.state))).rejects.toThrow('incomplete_log'); + fs.unlinkSync(log); + const plan = { ...exportRunPlan(f.state), id: 'already-queued' }; + await queueRunEdit(f.run, plan); + fs.appendFileSync(log, '{"id":'); + const partial = fs.readFileSync(log); + await expect(queueRunEdit(f.run, plan)).rejects.toThrow('incomplete_log'); + await expect(queueRunEdit(f.run, { ...plan, id: 'new-edit' })).rejects.toThrow('incomplete_log'); + expect(fs.readFileSync(log)).toEqual(partial); }); }); diff --git a/tests/leadCheckpointHandoff.test.ts b/tests/leadCheckpointHandoff.test.ts index a901a280..091fdc3c 100644 --- a/tests/leadCheckpointHandoff.test.ts +++ b/tests/leadCheckpointHandoff.test.ts @@ -139,6 +139,8 @@ describe('Lead checkpoint waits for its required decision handoff', () => { f.command(() => f.write(f.revision(false))); await vi.advanceTimersByTimeAsync(0); expect(f.interrupt).not.toHaveBeenCalled(); + expect(f.notify.mock.calls.map(([message]) => message)).toContainEqual( + expect.stringContaining('math_plan_research_decisions_missing')); expect(f.state.cooperation!.researchDecisions).toBeUndefined(); await vi.advanceTimersByTimeAsync(30_000); f.command(() => f.write(f.revision())); diff --git a/tests/libraryPacks.test.ts b/tests/libraryPacks.test.ts index 80cd0307..a25484fe 100644 --- a/tests/libraryPacks.test.ts +++ b/tests/libraryPacks.test.ts @@ -410,17 +410,16 @@ describe('library module guidance in research prompts', () => { assignment: task ? { kind: 'task', task, assignment: { taskId: task.id, taskDigest: taskVersion(task), workerId: 'worker', seedCommit: 'fixed-commit' } } : { kind: 'lead', seedCommit: 'fixed-commit' } }); - it('omits frozen libraries from editable files, proof paths and source bindings and references them once', () => { + it('keeps frozen libraries out of editable files and plan proof paths while retaining import guidance', () => { const lead = build(); expect(lead.instructions).toContain('Leave all Lean source files, imports and environment configuration unchanged.'); - expect(lead.instructions).toMatch(/^Edit only \/proof\/RESEARCH\.md\.$/mu); + expect(lead.instructions).toContain('Edit only /proof/RESEARCH.md, /proof/.scratch/plan.json.'); expect(lead.instructions).toContain('Save RESEARCH.md and delivery logs at these exact worktree-root paths'); expect(lead.instructions).toContain('Choose proofPath from ["Submission.lean"]; goals infer'); const prover = build(lemma); expect(prover.instructions).toContain('Edit only /proof/Submission.lean, /proof/RESEARCH.md,'); expect(prover.instructions).toContain(`${lib} is a frozen host library that Lean rechecked before this run: import the module that holds a declaration`); expect(prover.instructions).toContain('lines whose file starts with Submission/Library/ are library declarations'); - expect(prover.instructions).toContain('Its keys must be exactly ["Submission.lean"]'); expect(prover.message).toContain(JSON.stringify({ commit: 'fixed-commit', path: lib, digest: 'd'.repeat(64), frozenLibrary: true, declarationCount: 1 })); expect(prover.message).not.toContain('frozen-context:'); expect(prover.message).not.toContain('two_mul_two'); diff --git a/tests/nextChecks.test.ts b/tests/nextChecks.test.ts index e8da4514..01becdfc 100644 --- a/tests/nextChecks.test.ts +++ b/tests/nextChecks.test.ts @@ -9,7 +9,7 @@ import { commitSolverSources } from '../src/solver/problem'; import { prepareResearchDelivery } from '../src/solver/researchAdmission'; import { researchCheckpointLocalInputDigest } from '../src/solver/researchCheckpoints'; import { queueResearchObservation } from '../src/solver/researchObservation'; -import { assignmentDeliveryFile, leadPlanDeliveryFile, parseCooperationPlan, taskVersion } from '../src/solver/tasks'; +import { assignmentDeliveryFile, leadPlanDeliveryFile, parseCooperationPlan, taskVersion, type CooperativeAction } from '../src/solver/tasks'; import { cooperativeResearch } from './helpers/cooperation'; import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; @@ -52,12 +52,13 @@ async function fixture(constructionDependencies = ['goal_0']) { }; const record = await publishGap(); const identity = { problemReceiptDigest: example.problem.receiptDigest, environmentDigest: state.environmentDigest }; - const publishOutcome = async () => { + const publishOutcome = async (beforePublish?: (action: Extract) => void) => { const checkAction = await cooperation.next(checker, { maxTurns: Infinity, remainingMs: Infinity }); if (checkAction?.kind !== 'task') throw new Error('missing check assignment'); expect(checkAction.task.id).toBe(record.taskId); expect(cooperation.started(checker, checkAction)).toBe(true); cooperation.activate(checker, checkAction, async () => {}, async () => {}); + beforePublish?.(checkAction); queueResearchObservation({ worktree: checker.worktree, finding: { summary: 'The membership inference is still unknown.', checkOutcome: { checkId: record.id, conclusion: 'inconclusive', summary: 'The available assumptions do not yet provide a membership argument.', evidenceRefs: [] } } }); await cooperation.pulse(checker.id); @@ -176,14 +177,31 @@ describe('scoped next check lifecycle', () => { }); it('requires the shown outcome to receive an explicit decision and keeps it in full and same-thread contexts', async () => { - const f = await fixture(); await f.publishOutcome(); + const f = await fixture(); + const access = { root: f.directory, environment: {}, retrievalRoot: f.directory, taskText: 'Prove the original target.', + maxOptionalContextBytes: 0 }; + const draft = buildResearchContext(f.problem, { ...f.state, cooperation: f.cooperation.contextState(f.action, f.author) }, + { ...access, worktree: f.author.worktree, assignment: f.action }); + for (const message of [draft.message, draft.continuationMessage]) { + expect(message).toContain(f.record.id); + expect(message).not.toContain('checkOutcome:'); + expect(message).not.toContain('guidanceDecisions:'); + } + await f.publishOutcome(action => { + const context = buildResearchContext(f.problem, { ...f.state, cooperation: f.cooperation.contextState(action, f.checker) }, + { ...access, worktree: f.checker.worktree, assignment: action }); + expect(context.message).toContain(f.record.id); + expect(context.message).toContain('checkOutcome:'); + expect(context.message).toContain('with research-observe'); + }); const lead = await f.leadDecision(); - const context = buildResearchContext(f.problem, { ...f.state, cooperation: lead.view }, { root: f.directory, - worktree: f.workspace, environment: {}, retrievalRoot: f.directory, taskText: 'Prove the original target.', - assignment: lead.leadAction, maxOptionalContextBytes: 0 }); + const context = buildResearchContext(f.problem, { ...f.state, cooperation: lead.view }, + { ...access, worktree: f.workspace, assignment: lead.leadAction }); for (const text of [context.message, context.continuationMessage]) { expect(text).toContain(f.record.id); expect(text).toContain(f.record.outcome!.deliveryId); expect(text).toContain('inconclusive'); + expect(text).toContain('nextCheckDecisions'); + expect(text).not.toContain('checkOutcome:'); } await lead.publish(); expect(f.state.cooperation!.planPublicationRejection?.reason).toContain('math_plan_next_check_decision_required'); diff --git a/tests/obligationArchive.test.ts b/tests/obligationArchive.test.ts index 81fb0dd1..0e02661b 100644 --- a/tests/obligationArchive.test.ts +++ b/tests/obligationArchive.test.ts @@ -5,8 +5,7 @@ import { afterEach, describe, expect, it } from 'vitest'; import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; import { buildRunInspection, renderRunInspection } from '../src/solver/inspection'; import { captureObligationSnapshot, diffObligationProgress } from '../src/solver/obligationProgress'; -import { finalCandidateReviewReady } from '../src/solver/modules/search'; -import { taskVersion, type TaskRecord } from '../src/solver/tasks'; +import { hasTaskAcceptance, taskVersion, type TaskRecord } from '../src/solver/tasks'; import type { TaskProof } from '../src/solver/cooperativeProof'; const roots: string[] = []; @@ -41,7 +40,7 @@ describe('persisted mathematical progress', () => { expect(renderRunInspection(report)).toContain('Mathematical changes'); expect(diffObligationProgress(restored.cooperation!.progressSnapshot, captureObligationSnapshot(restored.cooperation!.tasks, { environmentDigest: 'environment' }))).toBeUndefined(); - expect(finalCandidateReviewReady(restored.cooperation!.tasks)).toBe(false); + expect(hasTaskAcceptance(restored.cooperation!.tasks[0].integratedCheck!)).toBe(false); }); it('keeps legacy checkpoints without mathematical progress readable', () => { diff --git a/tests/obligationProgress.test.ts b/tests/obligationProgress.test.ts index 54d45631..4823f1a6 100644 --- a/tests/obligationProgress.test.ts +++ b/tests/obligationProgress.test.ts @@ -1,6 +1,5 @@ import { describe, expect, it } from 'vitest'; import { captureObligationSnapshot, diffObligationProgress } from '../src/solver/obligationProgress'; -import { finalCandidateReviewReady } from '../src/solver/modules/search'; import { hasTaskAcceptance, markTaskAcceptance, taskVersion, type RouteRecord, type TaskRecord } from '../src/solver/tasks'; import type { ProofRoute } from '../src/solver/proofRoutes'; import type { RouteBlocker } from '../src/solver/routeControl'; @@ -35,7 +34,7 @@ describe('obligation snapshots and observed progress', () => { expect(receipt).toMatchObject({ kind: 'baseline', at: 10, afterDigest: state.digest, obligations: { new: [], closed: [], reopened: [], removed: [], changed: [] }, goalFrontiers: [], routes: [] }); expect(hasTaskAcceptance(input.integratedCheck!)).toBe(false); - expect(finalCandidateReviewReady([input, goal])).toBe(false); + expect(hasTaskAcceptance(goal.integratedCheck!)).toBe(false); }); it('ignores dispatches, attempts, assignment metadata, route turns and mere task ordering', () => { @@ -167,7 +166,6 @@ describe('obligation snapshots and observed progress', () => { expect(after.digest).toBe(before.digest); expect(after.obligations[0].closed).toBe(true); expect(diffObligationProgress(JSON.parse(JSON.stringify(before)), after)).toBeUndefined(); expect(hasTaskAcceptance(restored[0].integratedCheck!)).toBe(false); - expect(finalCandidateReviewReady(restored)).toBe(false); }); it('ignores receipts and commits changing during a replay of the same mathematical checkpoint', () => { @@ -264,7 +262,7 @@ describe('proof-route progress', () => { expect(completed.obligations.closed.map(change => change.after.taskId)).toEqual(['goal']); expect(completed.routes[0].after!.connection).toBe('closed-by-original-check'); expect(completed.goalFrontiers[0].after!.frontier).toEqual([]); - expect(completed.acceptance).toBe('not-assessed'); expect(finalCandidateReviewReady(tasks)).toBe(false); + expect(completed.acceptance).toBe('not-assessed'); expect(hasTaskAcceptance(goal.integratedCheck!)).toBe(false); }); it('retains alternative frontiers and does not treat all alternative branches as mandatory', () => { diff --git a/tests/researchObservation.test.ts b/tests/researchObservation.test.ts index 64bb1437..d1a364ad 100644 --- a/tests/researchObservation.test.ts +++ b/tests/researchObservation.test.ts @@ -54,9 +54,9 @@ describe('immediate advisory observation publication', () => { expect(help.usage).toContain('--finding FILE'); const context = buildResearchContext(f.problem, f.state, { root, worktree: f.peer.worktree, environment: {}, taskText: 'Investigate the synthetic construction.', retrievalRoot: f.directory, assignment: f.action }); - expect(context.instructions).toContain('--finding FILE'); - expect(context.instructions).not.toContain('FINDING_JSON'); - expect(context.instructions).toContain('```sh\n' + help.example + '\n```'); + expect(context.instructions).toContain('Use research-observe from .scratch/theoremos-help.md'); + expect(context.toolHelp?.text).toContain('research-observe --worktree'); + const commands = path.join(f.directory, 'commands'); fs.mkdirSync(commands); diff --git a/tests/routeScheduling.test.ts b/tests/routeScheduling.test.ts index 57d28a9a..fb07a061 100644 --- a/tests/routeScheduling.test.ts +++ b/tests/routeScheduling.test.ts @@ -2,9 +2,9 @@ import { describe, expect, it } from 'vitest'; import type { SolverProblem } from '../src/solver/problem'; import { describeProofRoutes, type ProofRoute } from '../src/solver/proofRoutes'; import { recordRouteBlockers, refreshRouteBlockers, type RouteBlocker } from '../src/solver/routeControl'; -import { continuationResearchTasks, criticalPathResearchTasks, finalCandidateReviewReady, plannedTaskDependencyIds, +import { continuationResearchTasks, criticalPathResearchTasks, plannedTaskDependencyIds, readyResearchTasks, researchCanAdvance, routeAllowsTask, selectedTaskRoute, taskCanStart, taskDependenciesReady } from '../src/solver/modules/search'; -import { parseCooperationPlan, taskVersion, type CooperativeTask, type TaskRecord } from '../src/solver/tasks'; +import { freshlyAccepted, parseCooperationPlan, taskVersion, type CooperativeTask, type TaskRecord } from '../src/solver/tasks'; import { integratedProof } from './helpers/taskProof'; const problem = { ownedFiles: ['Submission.lean'], targets: [{ theoremName: 'Submission.goal', proofPath: 'Submission.lean' }], @@ -92,11 +92,11 @@ describe('alternative route scheduling', () => { expect(taskVersion(goal.task)).toBe(version); expect(goal.task.conditional).toBeUndefined(); expect(goal.status).toBe('pending'); - expect(finalCandidateReviewReady([input, goal])).toBe(false); + expect(freshlyAccepted(goal, taskVersion(goal.task))).toBe(false); checked(input); expect(readyResearchTasks([input, goal])).toEqual([goal]); expect(taskDependenciesReady(goal.task, [input, goal])).toBe(true); - expect(finalCandidateReviewReady([input, goal])).toBe(false); + expect(freshlyAccepted(goal, taskVersion(goal.task))).toBe(false); }); it('passes route contracts through the plan parser without rewriting frozen goal dependencies', () => { @@ -261,10 +261,10 @@ describe('alternative route scheduling', () => { const { b, c, closeB, goal, tasks, routes } = fixture(); checked(b); checked(c); checked(closeB, [b, c]); expect(taskCanStart(goal.task, tasks)).toBe(true); - expect(finalCandidateReviewReady(tasks)).toBe(false); + expect(freshlyAccepted(goal, taskVersion(goal.task))).toBe(false); expect(describeProofRoutes(routes, tasks).routes[1].connection).toBe('awaiting-original-check'); checked(goal, [closeB]); - expect(finalCandidateReviewReady(tasks)).toBe(true); + expect(freshlyAccepted(goal, taskVersion(goal.task))).toBe(true); expect(describeProofRoutes(routes, tasks).routes[1].connection).toBe('closed-by-original-check'); }); }); diff --git a/tests/solver.test.ts b/tests/solver.test.ts index d7eee657..fa735d04 100644 --- a/tests/solver.test.ts +++ b/tests/solver.test.ts @@ -1926,6 +1926,10 @@ describe('isolated solver and host acceptance', () => { { id: 'second', kind: 'goal', objective: 'Use the checked first goal', dependsOn: ['first'], proofPath: 'Submission.lean', theoremName: 'Submission.second', revision: 0 }, ]; + const reviewedPlanTasks = (): CooperativeTask[] => [...planTasks(), { + id: 'candidate_audit', kind: 'research', objective: 'Independently inspect the completed candidate.', + dependsOn: [], revision: 0, reviewScope: 'final-candidate', + }]; // Receipt replay and concurrency fixtures prepare helpers under ordinary dependency waiting. const waitingPlanTasks = () => planTasks().map(task => task.kind === 'goal' ? { ...task, conditional: false } : task); const writePlan = (worktree: string, tasks: readonly CooperativeTask[], groups?: readonly RouteGroup[], @@ -2248,17 +2252,10 @@ describe('isolated solver and host acceptance', () => { objective: `Prove ${name} after filling the constant`, theoremName: `Submission.${name}`, proofPath: 'Submission.lean', dependsOn: ['constant'], revision: 0 }))]; host.officialGate.mockResolvedValue({ comparison: { status: officialStatus } }); - let reviews = 0; configureCooperation(async (action, options) => { const file = path.join(options.workspace, 'generated/p/Submission.lean'); if (action.kind === 'lead') writePlan(options.workspace, tasks); - else if (action.kind === 'review') { - reviews++; - expect(fs.readFileSync(file, 'utf8')).not.toContain('sorry'); - expect(fs.readFileSync(file, 'utf8')).toContain('noncomputable def C : Nat := 7'); - expect(host.officialGate).not.toHaveBeenCalled(); - finishAssignment(action, options); - } else if (action.kind === 'task') { + else if (action.kind === 'task') { expect(host.officialGate).not.toHaveBeenCalled(); const source = fs.readFileSync(file, 'utf8'); if (action.task.id === 'constant') { @@ -2276,8 +2273,7 @@ describe('isolated solver and host acceptance', () => { expect(await runSolver([...args, '--workers', '3', '--max-turns', '7'], directory)).toBe(officialStatus === 'official_verified' ? 0 : 2); const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); expect(state.cooperation.tasks.every((node: any) => node.status === 'integrated')).toBe(true); - expect(state.cooperation.review.status).toBe('accepted'); - expect(reviews).toBe(1); + expect(state.cooperation.review).toBeUndefined(); expect(host.officialGate).toHaveBeenCalledOnce(); expect(host.verify.mock.calls.filter(([request]) => request.items.length === problem.targets.length).length).toBeGreaterThanOrEqual(2); expect(JSON.parse(fs.readFileSync(output, 'utf8')).status).toBe(officialStatus === 'official_verified' ? 'evaluated_passed' : 'evaluated_failed'); @@ -2357,7 +2353,7 @@ describe('isolated solver and host acceptance', () => { it('commits saved cooperative proofs on the host and persists worker activity', async () => { configureCooperation(async (action, options, message) => { if (action.kind === 'task') { - expect(options.instructions).toContain('The host freezes the saved sources'); + expect(options.instructions).toContain('save the assigned declaration and return for host checking'); expect(message).not.toContain('commit allowed sources and notes'); expect(options.instructions).not.toContain('Report checker startup errors and return'); expect(options.instructions).toContain('then retry the saved-file check'); @@ -2656,6 +2652,59 @@ describe('isolated solver and host acceptance', () => { expect(host.officialGate).not.toHaveBeenCalled(); }); + it('routes active candidate questions to a single fixed review with the default scheduler', async () => { + const tasks = reviewedPlanTasks(); + tasks.push({ id: 'independent_candidate_review', kind: 'research', objective: 'Did the helper introduce an extra premise?', + dependsOn: ['a'], revision: 0 }, + { id: 'paused_audit', kind: 'research', objective: 'PAUSED_AUDIT_QUESTION', reviewScope: 'final-candidate', + status: 'paused', dependsOn: [], revision: 0 }); + let reviews = 0; + const assigned: string[] = []; + configureCooperation(async (action, options, message) => { + if (action.kind === 'lead') writePlan(options.workspace, tasks); + else if (action.kind === 'task') assigned.push(action.task.id); + else if (action.kind === 'review') { + reviews++; + expect(message).toContain(tasks[4].objective); + expect(message).toContain(tasks[5].objective); + expect(message).not.toContain('"question":"PAUSED_AUDIT_QUESTION"'); + expect(host.officialGate).not.toHaveBeenCalled(); + } + if (action.kind !== 'lead') finishAssignment(action, options); + return 'completed'; + }); + expect(await runSolver([...args, '--workers', '4', '--max-turns', '12'], directory)).toBe(0); + expect(assigned.sort()).toEqual(['a', 'b', 'first', 'second']); + expect(reviews).toBe(1); + expect(cooperationState().review.status).toBe('accepted'); + expect(host.officialGate).toHaveBeenCalledOnce(); + }); + + it('cancels an in-flight candidate review when its only request is paused', async () => { + const tasks = reviewedPlanTasks(), interrupted = deferred(); + let reviewerWorkspace: string | undefined, reviews = 0; + configureCooperation(async (action, options) => { + if (action.kind === 'lead') writePlan(options.workspace, tasks); + else if (action.kind === 'review') { + expect(++reviews).toBe(1); + reviewerWorkspace = options.workspace; + tasks[4] = { ...tasks[4], status: 'paused' }; + fs.appendFileSync(`${output}.runtime/edits.jsonl`, JSON.stringify({ id: 'pause-audit', + baseVersion: cooperationState().planVersion, tasks }) + '\n'); + await interrupted.promise; + } + if (action.kind !== 'lead') finishAssignment(action, options); + return 'completed'; + }); + const create = host.createSession.getMockImplementation()!; + host.createSession.mockImplementation(async (options: MathAgentOptions) => ({ ...await create(options), + interrupt: vi.fn(async () => { if (options.workspace === reviewerWorkspace) interrupted.resolve(); }) })); + expect(await runSolver([...args, '--workers', '2', '--max-turns', '9'], directory)).toBe(0); + expect(cooperationState().edits[0]).toMatchObject({ status: 'applied' }); + expect(cooperationState().review).toBeUndefined(); + expect(host.officialGate).toHaveBeenCalledOnce(); + }, 20_000); + it('resumes a proof review checkpoint without accepting its saved verdict prematurely', async () => { let reviews = 0; configureCooperation(async (action, options) => { @@ -2667,7 +2716,9 @@ describe('isolated solver and host acceptance', () => { expect(cooperationState().deliveries.some((record: any) => record.kind === 'review')).toBe(false); expect(host.officialGate).not.toHaveBeenCalled(); } - finishAssignment(action, options); return 'completed'; + if (action.kind === 'lead') writePlan(options.workspace, reviewedPlanTasks()); + else finishAssignment(action, options); + return 'completed'; }); expect(await runSolver([...args, '--workers', '2', '--max-turns', '7'], directory)).toBe(0); expect(reviews).toBe(2); @@ -2761,7 +2812,7 @@ describe('isolated solver and host acceptance', () => { expect(context.instructions).toContain('leave Lean sources unchanged during planning'); expect(context.instructions).toContain('Return the plan without running Lean diagnostics'); expect(context.instructions).not.toContain('FULL_CLOSED_LEAN_TYPE'); - const exampleText = context.instructions.match(/Use this plan schema for the delivery-log event, or for a math-plan JSON fence in RESEARCH\.md when returning without publication: (\{.*?\})\. Include/u); + const exampleText = context.instructions.match(/Use this plan schema in the draft passed to plan-apply: (\{.*?\})\. Include/u); expect(exampleText).not.toBeNull(); const example = JSON.parse(exampleText![1]); example.tasks[0].theoremName = 'Submission.helper'; @@ -2811,7 +2862,7 @@ describe('isolated solver and host acceptance', () => { it.each(['lead', 'task', 'backtranslate', 'statement-review', 'review'])('does not charge an unstarted cooperative %s assignment', async stoppedKind => { const statementPhase = stoppedKind === 'backtranslate' || stoppedKind === 'statement-review'; - const tasks = statementPhase ? statementTasks() : planTasks(); + const tasks = statementPhase ? statementTasks() : stoppedKind === 'review' ? reviewedPlanTasks() : planTasks(); // Keep independent proof work from stopping all peers before the statement context is ready. if (statementPhase) tasks[1] = { ...tasks[1], dependsOn: ['a'] }; configureCooperation(async (action, options) => { @@ -2834,7 +2885,7 @@ describe('isolated solver and host acceptance', () => { expect(state.turns).toBe(spent + (stoppedKind === 'lead' ? 0 : 1)); expect(Object.values(state.dispatchCounts).reduce((sum: number, value: any) => sum + value, 0)).toBe(state.turns); expect(state.dispatchCounts.planning ?? 0).toBe(stoppedKind === 'lead' ? 0 : 1); - expect(state.cooperation.tasks.every((node: any) => node.attempts === (stoppedKind === 'review' ? 1 : 0))).toBe(true); + expect(state.cooperation.tasks.filter((node: TaskRecord) => node.task.reviewScope !== 'final-candidate').every((node: TaskRecord) => node.attempts === (stoppedKind === 'review' ? 1 : 0))).toBe(true); if (stoppedKind === 'review') expect(state.cooperation.review.status).toBe('pending'); if (stoppedKind === 'backtranslate') expect(state.cooperation.statementReviews[0].status).toBe('pending'); if (stoppedKind === 'statement-review') expect(state.cooperation.statementReviews[0].status).toBe('translated'); @@ -3082,7 +3133,7 @@ describe('isolated solver and host acceptance', () => { }); it.each(['worktree', 'files', 'reviewer'])('keeps host ownership when replacement M5 changes %s', async invalid => { - configureCooperation(); + configureCooperation(undefined, invalid === 'reviewer' ? reviewedPlanTasks : planTasks); const workers = (...inputs: Parameters) => directSolverModules.M5.workers(...inputs).map((worker, index) => index !== 1 ? worker : invalid === 'worktree' ? { ...worker, worktree: workspace } : invalid === 'files' ? { ...worker, ownedFiles: ['Challenge.lean'] } : worker); @@ -3912,9 +3963,7 @@ describe('isolated solver and host acceptance', () => { return 'completed'; }); const parallelArgs = [...args, '--workers', '4', '--max-turns', '5']; - expect(await runSolver(parallelArgs, directory)).toBe(4); - expect(host.officialGate).not.toHaveBeenCalled(); - expect(await runSolver([...parallelArgs, '--max-turns', '6', '--resume'], directory)).toBe(0); + expect(await runSolver(parallelArgs, directory)).toBe(0); const records = cooperationState().deliveries; for (const id of ['a', 'b']) { expect(records.filter((record: any) => record.taskId === id && record.kind === 'progress')).toHaveLength(1); @@ -3957,7 +4006,7 @@ describe('isolated solver and host acceptance', () => { }, 20_000); it('requires a new simplified review response after the reviewed proof version changes', async () => { - const tasks = planTasks(), reviewStopped = deferred(); let reviews = 0, reviewerWorkspace = ''; + const tasks = reviewedPlanTasks(), reviewStopped = deferred(); let reviews = 0, reviewerWorkspace = ''; configureCooperation(async (action, options) => { if (action.kind === 'lead') writePlan(options.workspace, tasks); else if (action.kind === 'review') { @@ -4006,15 +4055,16 @@ describe('isolated solver and host acceptance', () => { } finishAssignment(action, options); return 'completed'; }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '6'], directory, + expect(await runSolver([...args, '--workers', '4', '--max-turns', '5'], directory, { ...directSolverModules, M2: { ...directSolverModules.M2, checkTask } })).toBe(0); expect(started).toBe(2); expect(checking.size).toBe(2); const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); expect(state.cooperation.tasks.map(node => node.status)).toEqual(['integrated', 'integrated', 'integrated', 'integrated']); - expect(state.turns).toBe(6); + expect(state.turns).toBe(5); + expect(state.cooperation.review).toBeUndefined(); expect(state.winningWorker).toBe('solver'); - expect(state.usage).toMatchObject({ inputTokens: 6000, totalTokens: 7200 }); + expect(state.usage).toMatchObject({ inputTokens: 5000, totalTokens: 6000 }); const source = fs.readFileSync(path.join(state.worktree, 'generated/p/Submission.lean'), 'utf8'); expect(source).toContain('lemma a'); expect(source).toContain('lemma b'); expect(source).not.toContain('sorry'); const events = vi.mocked(console.log).mock.calls.map(([event]) => JSON.parse(event)); @@ -4287,8 +4337,12 @@ describe('isolated solver and host acceptance', () => { if (action.kind === 'task' && action.task.id === 'first') { expect(message).toContain('"groupId":"alternative"'); expect(message).toContain('"producer":"researcher-'); - expect(message).toContain('checkedSourceDigest'); - expect(message).toContain('integratedCommit'); + const graph = JSON.parse(message.split('Lead task graph and host feedback:\n')[1].split('\n')[0]); + const projected = JSON.parse(fs.readFileSync(path.join(options.workspace, 'COOPERATION.json'), 'utf8')) + .tasks.find((row: any) => row.task.id === 'b').integratedCheck; + expect(graph.find((row: any) => row.id === 'b').evidence).toMatchObject({ + commit: projected.commit, sourceDigest: projected.sourceDigest, taskDigest: projected.taskDigest, + }); } finishAssignment(action, options); } @@ -4403,6 +4457,7 @@ describe('isolated solver and host acceptance', () => { }); it('invalidates a revised route and cross-route consumers while preserving the other route\'s verified lemma', async () => { + const tasks = () => [...groupedTasks(), reviewedPlanTasks().at(-1)!]; const reviewAcceptances: { accepted: boolean; receiptIds: string[]; assignmentId?: string }[] = []; const modules = { ...directSolverModules, M4: { ...directSolverModules.M4, build: (...inputs: Parameters) => { @@ -4415,20 +4470,20 @@ describe('isolated solver and host acceptance', () => { return directSolverModules.M4.build(...inputs); } } }; configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, groupedTasks(), routeGroups()); + if (action.kind === 'lead') writePlan(options.workspace, tasks(), routeGroups()); else finishAssignment(action, options); return 'completed'; }); const parallelArgs = [...args, '--workers', '4', '--max-turns', '5']; - expect(await runSolver(parallelArgs, directory)).toBe(4); + expect(await runSolver(parallelArgs, directory, modules)).toBe(4); const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.cooperation.tasks.every(node => node.status === 'integrated')).toBe(true); + expect(state.cooperation.tasks.slice(0, 4).every(node => node.status === 'integrated')).toBe(true); const groups = routeGroups(); groups[1] = { ...groups[1], revision: 1 }; - writePlan(state.worktree, groupedTasks(), groups); + writePlan(state.worktree, tasks(), groups); expect(await runSolver([...parallelArgs, '--resume', '--max-turns', '9'], directory, modules)).toBe(0); const resumed = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(resumed.cooperation.tasks.map(node => node.attempts)).toEqual([1, 1, 2, 1]); + expect(resumed.cooperation.tasks.map(node => node.attempts)).toEqual([1, 1, 2, 1, 0]); expect(resumed.cooperation.history.map(node => node.task.id)).toEqual(['b', 'first', 'second']); expect(resumed.cooperation.groups[1]).toMatchObject({ group: { revision: 1 }, turns: 1 }); const bridge = resumed.cooperation.tasks[1]; @@ -4574,7 +4629,8 @@ describe('isolated solver and host acceptance', () => { it('rejects a Reviewer that changes the fixed proof and keeps review separate from Lean acceptance', async () => { configureCooperation(async (action, options) => { - finishAssignment(action, options); + if (action.kind === 'lead') writePlan(options.workspace, reviewedPlanTasks()); + else finishAssignment(action, options); if (action.kind === 'review') { const file = path.join(options.workspace, 'generated/p/Submission.lean'); fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('by exact first', 'by trivial')); @@ -4811,7 +4867,9 @@ describe('isolated solver and host acceptance', () => { expect(await runSolver([...args, '--workers', '4', '--max-turns', '6'], directory)).toBe(0); expect(leadTurns).toBe(1); const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.dispatchCounts).toEqual({ planning: 1, research: 1, proof: 2, review: 1 }); + expect(state.dispatchCounts).toEqual({ planning: 1, research: 1, proof: 2 }); + expect(state.cooperation.review).toBeUndefined(); + expect(host.officialGate).toHaveBeenCalledOnce(); expect(host.verify.mock.calls.some(([request]) => request.items.some(item => item.theoremName === 'route'))).toBe(false); }); @@ -4947,7 +5005,7 @@ describe('isolated solver and host acceptance', () => { expect(finding.integratedCheck).toBeUndefined(); expect(finding.finding).toContain('EXACT_CLOSING_INFERENCE'); const restored = readSolverRunState(`${output}.runtime/state.json`); - expect(restored.dispatchCounts).toEqual({ planning: 1, research: 1, proof: 2, review: 1 }); + expect(restored.dispatchCounts).toEqual({ planning: 1, research: 1, proof: 2 }); expect(restored.cooperation!.tasks.find(item => item.task.id === 'route')!.finding).toBe(finding.finding); const restoredDelivery = restored.cooperation!.deliveries!.find(item => item.taskId === 'route' && item.kind === 'research')!; expect(restoredDelivery.findingDigest).toBe(mathDigest(finding.finding)); @@ -5597,7 +5655,7 @@ describe('isolated solver and host acceptance', () => { }; it.each(['notes-only', 'changed-source'] as const)('keeps integrated evidence after an unused planned dependency is revised (%s completion)', async completion => { - const tasks = planTasks(); tasks[3] = { ...tasks[3], status: 'paused' }; + const tasks = reviewedPlanTasks(); tasks[3] = { ...tasks[3], status: 'paused' }; configureCooperation(async (action, options) => { if (action.kind === 'lead') writePlan(options.workspace, tasks); else if (action.kind === 'task' && action.task.id === 'first') { @@ -5657,7 +5715,7 @@ describe('isolated solver and host acceptance', () => { host.verify.mockClear(); expect(await runSolver([...parallelArgs, '--resume', '--max-turns', '6'], directory)).toBe(0); const resumed = cooperationState(); - expect(resumed.tasks.map((node: any) => node.attempts)).toEqual([1, 1, 1, 1]); + expect(resumed.tasks.map((node: any) => node.attempts)).toEqual([1, 1, 1, 1, 0]); expect(resumed.tasks[0].status).toBe('pending'); expect(resumed.edits[0].recheck.status).toBe('pending'); const refreshedDelivery = resumed.deliveries.find((record: any) => record.id === delivery.id); @@ -5677,7 +5735,7 @@ describe('isolated solver and host acceptance', () => { }, 20_000); it('revalidates checked sources without new model proof turns after descriptive plan revisions', async () => { - const tasks = planTasks(), reviewStopped = deferred(); + const tasks = reviewedPlanTasks(), reviewStopped = deferred(); let reviews = 0, reviewerWorkspace = ''; configureCooperation(async (action, options) => { if (action.kind === 'lead') writePlan(options.workspace, tasks); @@ -5697,7 +5755,7 @@ describe('isolated solver and host acceptance', () => { interrupt: vi.fn(async () => { if (options.workspace === reviewerWorkspace) reviewStopped.resolve(); }) })); expect(await runSolver([...args, '--workers', '2', '--max-turns', '9'], directory)).toBe(0); const state = cooperationState(); - expect(state.tasks.map((node: TaskRecord) => node.attempts)).toEqual([1, 1, 1, 1]); + expect(state.tasks.map((node: TaskRecord) => node.attempts)).toEqual([1, 1, 1, 1, 0]); expect(state.edits[0]).toMatchObject({ status: 'applied', recheck: { status: 'passed' } }); expect(state.tasks[0].integratedCheck.taskDigest).toBe(taskVersion(tasks[0])); expect(state.tasks[2].integratedCheck.references.tasks).toContainEqual({ taskId: 'a', taskDigest: taskVersion(tasks[0]) }); @@ -5706,7 +5764,7 @@ describe('isolated solver and host acceptance', () => { }, 20_000); it.each(['actual', 'missing', 'whole-module'] as const)('invalidates dependent proofs and archives their old deliveries after a live revision (%s references)', async trace => { - const tasks = planTasks(), reviewStopped = deferred(); + const tasks = reviewedPlanTasks(), reviewStopped = deferred(); const reviewAcceptances: { accepted: boolean; receiptIds: string[]; assignmentId?: string }[] = []; const modules = { ...directSolverModules, M4: { ...directSolverModules.M4, build: (...inputs: Parameters) => { @@ -5738,7 +5796,7 @@ describe('isolated solver and host acceptance', () => { expect(await runSolver([...args, '--workers', '2', '--max-turns', '12'], directory, modules)).toBe(0); const state = cooperationState(); expect(state.history.map((node: any) => node.task.id)).toEqual(['a', 'first', 'second']); - expect(state.tasks.map((node: any) => node.attempts)).toEqual([1, 1, 2, 1]); + expect(state.tasks.map((node: any) => node.attempts)).toEqual([1, 1, 2, 1, 0]); for (const id of ['a', 'first', 'second']) { const statuses = state.deliveries.filter((record: any) => record.taskId === id && record.kind === 'proof') .map((record: any) => record.status); @@ -6369,11 +6427,13 @@ describe('isolated solver and host acceptance', () => { configureCooperation(async (action, options) => { if (action.kind === 'review' && ++reviews === 1) { reviewerWorkspace = options.workspace; - const tasks = planTasks(); tasks[0] = { ...tasks[0], revision: 1 }; + const tasks = reviewedPlanTasks(); tasks[0] = { ...tasks[0], revision: 1 }; fs.appendFileSync(`${output}.runtime/edits.jsonl`, JSON.stringify({ id: 'during-review', baseVersion: cooperationState().planVersion, tasks }) + '\n'); await reviewStopped.promise; } - finishAssignment(action, options); return 'completed'; + if (action.kind === 'lead') writePlan(options.workspace, reviewedPlanTasks()); + else finishAssignment(action, options); + return 'completed'; }); const create = host.createSession.getMockImplementation()!; host.createSession.mockImplementation(async (options: MathAgentOptions) => ({ ...await create(options), @@ -6539,13 +6599,13 @@ describe('isolated solver and host acceptance', () => { const file = path.join(directory, 'deliveries.jsonl'); fs.writeFileSync(file, '{"id":"one"}\n{"id":'); const first = readDeliveryLines(file, 0); - expect(first.lines).toEqual(['{"id":"one"}']); + expect(first.entries.map(entry => entry.line)).toEqual(['{"id":"one"}']); fs.appendFileSync(file, '"two"}\n'); const second = readDeliveryLines(file, first.offset); - expect(second.lines).toEqual(['{"id":"two"}']); - expect(readDeliveryLines(file, second.offset).lines).toEqual([]); + expect(second.entries.map(entry => entry.line)).toEqual(['{"id":"two"}']); + expect(readDeliveryLines(file, second.offset).entries).toEqual([]); fs.truncateSync(file, 0); - expect(() => readDeliveryLines(file, second.offset)).toThrow('math_delivery_log_invalid'); + expect(readDeliveryLines(file, second.offset).entries).toMatchObject([{ error: 'math_delivery_log_rewritten', offset: 0 }]); }); it('checks two independent early deliveries concurrently while both producers are still running', async () => { diff --git a/tests/solverContext.test.ts b/tests/solverContext.test.ts index 8d2450f6..5a826b5e 100644 --- a/tests/solverContext.test.ts +++ b/tests/solverContext.test.ts @@ -4,8 +4,8 @@ import type { SolverProblem } from '../src/solver/problem'; import type { SolverRunState } from '../src/solver/archive'; import { mathDigest } from '../src/math/mathRuntimeIo'; import type { DeliveryReceipt } from '../src/solver/deliveryReceipts'; -import { deliveryDetails, parseMathResponse, type DeliveryRecord } from '../src/solver/deliveries'; -import { assignmentDeliveryFile, leadPlanDeliveryFile, taskVersion, type CooperativeAction, type CooperativeTask } from '../src/solver/tasks'; +import type { DeliveryRecord } from '../src/solver/deliveries'; +import { assignmentDeliveryFile, taskVersion, type CooperativeAction, type CooperativeTask } from '../src/solver/tasks'; it('deduplicates repeated findings and progress while preserving exact Lean types and version references', () => { const exactType = '∀ (n : Nat), ' + 'True ∧ '.repeat(2100) + 'True'; @@ -38,13 +38,13 @@ it('deduplicates repeated findings and progress while preserving exact Lean type expect(context.continuationMessage).not.toContain(exactType); expect(context.continuationMessage).not.toContain(finding); expect(context.continuationMessage).toContain(JSON.stringify(action)); - expect(context.continuationMessage).toContain(leadPlanDeliveryFile(action)); + expect(context.continuationMessage).toContain('plan-apply --publish'); expect(context.continuationMessage).toContain(JSON.stringify(context.workContract)); expect(context.continuationMessage).toContain('replaces every previous dispatch nonce and receipt'); expect(context.continuationMessage).toContain('RESEARCH.md'); expect(context.continuationMessage).toContain('COOPERATION.json'); - expect(context.continuationMessage).toContain('host-synced accepted graph'); - expect(context.continuationMessage).toContain('{"baseVersion":"current-plan","upsert":['); + expect(context.instructions).toContain('host-synced accepted graph'); + expect(context.instructions).toContain('{"baseVersion":"current-plan","upsert":['); expect(context.continuationMessage).toContain('proof acceptance'); expect(context.manifest!.usedBytes).toBeLessThanOrEqual(context.manifest!.maxBytes); const graph = context.message.split('Lead task graph and host feedback:\n')[1].split('\n\nRoute groups')[0]; @@ -175,19 +175,15 @@ it.each([false, true])('keeps the Lead on read-only planning and prompt delivery ...(existing ? { planNonce: dispatchNonce } : { initialPlanNonce: dispatchNonce }) } }); expect(context.instructions).toContain('Once a complete plan has useful executable work, save the plan, or a revision of the accepted graph, and return promptly so peers can start it.'); expect(context.instructions).toContain('Delegate unresolved library or mathematical searches as research tasks to eligible Researchers or the Engineer.'); - for (const message of [context.instructions, context.continuationMessage]) { - expect(message).toContain(`"dispatchNonce":${JSON.stringify(dispatchNonce)}`); - expect(message).toContain('Copy the dispatchNonce and baseVersion fields exactly as shown'); - expect(message).toContain('Create this current dispatch log by appending if absent'); - expect(message).toContain('a second copy of the graph in RESEARCH.md or the final response is unnecessary'); - expect(message).toContain('return after publication without polling or waiting for approval'); - expect(message).toContain('ready tasks reserved by ownerId to a busy worker'); - expect(message).toContain('Explicitly reassign an unstarted, unassigned task through the plan'); - expect(message).toContain('Preserve route gates, group scope, independent reviewer eligibility and running assignments'); - expect(message).toContain('A goal/lemma objective may guide the argument, but cannot replace its frozen proof deliverable'); - expect(message).toContain('Create a separate untyped research/sketch task for those checks'); - } - const log = leadPlanDeliveryFile(context.assignment as Extract); + expect(context.instructions).toContain('a second copy of the graph in RESEARCH.md or the final response is unnecessary'); + expect(context.instructions).toContain('return after publication without polling or waiting for approval'); + expect(context.instructions).toContain('ready tasks reserved by ownerId to a busy worker'); + expect(context.instructions).toContain('Explicitly reassign an unstarted, unassigned task through the plan'); + expect(context.instructions).toContain('Preserve route gates, group scope, independent reviewer eligibility and running assignments'); + expect(context.instructions).toContain('A goal/lemma objective may guide the argument, but cannot replace its frozen proof deliverable'); + expect(context.instructions).toContain('Create a separate untyped research/sketch task for those checks'); + expect(context.continuationMessage).toContain('plan-apply --publish'); + expect(context.continuationMessage).not.toContain('ready tasks reserved by ownerId to a busy worker'); expect(context.workContract).toMatchObject({ stage: 'route-planning', sourcePolicy: 'host-checks-any-source-repair' }); expect(context.message).toContain(taskText); expect(context.message).toContain(formal); @@ -195,14 +191,14 @@ it.each([false, true])('keeps the Lead on read-only planning and prompt delivery for (const continuation of [false, true]) { const dispatched = finalizeResearchDispatch(context, { continuation }); expect(dispatched.instructions.split('\n').find(line => line.startsWith('Edit only '))) - .toBe(`Edit only /proof/RESEARCH.md, /proof/${log}.`); + .toBe('Edit only /proof/RESEARCH.md, /proof/.scratch/plan.json.'); expect(dispatched.instructions).toContain('Develop a mathematically plausible route from the exact original statement, definitions and relevant saved findings'); expect(dispatched.instructions).toContain('put a direct original-goal task in the graph; the assigned worker carries out its proof'); expect(dispatched.instructions).toContain('Return the plan without running Lean diagnostics'); expect(dispatched.instructions).toContain('Leave all Lean source files, imports and environment configuration unchanged'); expect(dispatched.instructions).toContain('Keep all existing imports'); expect(dispatched.instructions).toContain('Plan a shared helper before its consumers when needed; assigned workers implement it'); - expect(dispatched.instructions).toContain('only a further substantive change requires another final plan response'); + expect(dispatched.instructions).toContain('For intake on return, omit --publish'); for (const writableAdvice of ['bodies must be filled', 'you may add import Mathlib or any pinned Mathlib.* import', 'Add helpers in owned modules', 'For diagnostics, run', 'check-lean --workspace', 'proof-search --workspace', 'Repair the earliest error', 'restore the offending context', 'For type lookup, add single-name #check']) @@ -216,22 +212,15 @@ it.each([false, true])('keeps the Lead on read-only planning and prompt delivery expect(context.instructions).toContain('Lead planning saves a task graph and returns promptly'); expect(context.instructions).not.toContain('automatically hands writing back to the host'); // Only an accepted graph can be revised; initial planning still writes a complete plan. - for (const message of [context.instructions, context.continuationMessage]) { - expect(message?.includes('Revise the accepted graph instead of retyping it.')).toBe(existing); - expect(message?.includes('it does not need a complete proof decomposition')).toBe(!existing); - if (!existing) { - expect(message).toContain('Keep original goals independent of advisory research in proof dependencies'); - expect(message).toContain('never invent a proposition to fill the graph'); - expect(message).toContain('before further literature searches or proof exploration'); - expect(message).not.toContain('before choosing a task graph'); - } + expect(context.instructions.includes('Revise the accepted graph instead of retyping it.')).toBe(existing); + expect(context.instructions.includes('it does not need a complete proof decomposition')).toBe(!existing); + if (!existing) { + expect(context.instructions).toContain('Keep original goals independent of advisory research in proof dependencies'); + expect(context.instructions).toContain('never invent a proposition to fill the graph'); + expect(context.instructions).toContain('before further literature searches or proof exploration'); } expect(context.continuationMessage?.includes('revise the accepted graph or return it unchanged')).toBe(existing); expect(context.continuationMessage?.includes('No task graph has been accepted')).toBe(!existing); - if (!existing) { - expect(context.continuationMessage).toContain('"baseVersion":"current-plan"'); - expect(context.continuationMessage).toContain('Inline the complete valid graph covering every original target exactly once'); - } }); it.each(['append', 'replace'] as const)('retains custom Lead strategies and installed mathematics tools (%s)', mode => { @@ -323,7 +312,7 @@ it.each(['lemma', 'goal', 'lead', 'research'] as const)( expect(context.instructions).toContain('every original goal proof exactly as it appears in assignment.seedCommit, including existing sorry placeholders'); expect(context.instructions).toContain('A preserved placeholder in another declaration does not block delivery of your completed helper.'); expect(context.instructions).toContain('Proofs you submit for acceptance must not use sorry'); - expect(context.instructions).toContain('confirmed shutdown'); + expect(context.instructions).toContain('save the assigned declaration and return for host checking'); } }); @@ -336,9 +325,8 @@ it.each(['lemma', 'goal'] as const)('keeps Lead planning requests out of a dispa expect(dispatched.instructions).toContain('plan approval belong to the Lead and host'); expect(dispatched.instructions).toContain('before dispatching typed proof work'); expect(dispatched.instructions).toContain('do not start another planning or approval cycle'); - expect(dispatched.instructions).toContain('append JSON to the current delivery log'); + expect(dispatched.instructions).toContain('Use research-observe'); expect(dispatched.message).toContain(`Current delivery log: ${deliveryFile}`); - expect(dispatched.instructions).toContain('Create it by appending if absent'); expect(dispatched.message).toContain(JSON.stringify(context.assignment)); expect(dispatched.workContract).toEqual(context.workContract); expect(dispatched.manifest!.usedBytes).toBeLessThanOrEqual(dispatched.manifest!.maxBytes); @@ -354,16 +342,8 @@ it.each(['lemma', 'goal'] as const)('delivers a completed %s without requiring a const context = gapContext(kind); for (const continuation of [false, true]) { const dispatched = finalizeResearchDispatch(context, { continuation }); - expect(dispatched.instructions).toContain('Once the assigned proof is complete and saved, use the ready delivery protocol above and return'); - expect(dispatched.instructions).toContain('no separate research observation is required'); - expect(dispatched.instructions).not.toContain('Publish a single research observation promptly'); - expect(dispatched.instructions).toContain('only for a substantive intermediate finding or gap'); - expect(dispatched.instructions).toContain('theorem-os research-observe --worktree'); - expect(dispatched.instructions).toContain('--finding FINDING_FILE'); - expect(dispatched.instructions).toContain('Save the finding object shown above in the JSON file FINDING_FILE'); - expect(dispatched.instructions).toContain('When supporting Lean code is saved but the assigned declaration is still unproved'); - expect(dispatched.instructions).toContain('append {"kind":"ready","summary":"saved proof"}, stop editing and return'); - expect(dispatched.instructions).toContain('after turn settlement and confirmed shutdown'); + expect(dispatched.instructions).toContain('for a substantive finding or unresolved gap'); + expect(dispatched.instructions).toContain('save the assigned declaration and return for host checking'); } }); @@ -382,31 +362,23 @@ it.each(['lemma', 'goal'] as const)('preserves the %s proof deliverable when its const objective = 'Read-only audit: run diagnostics once and report the result without editing Lean sources.'; const context = gapContext(kind, undefined, objective); expect(context.assignment).toMatchObject({ kind: 'task', task: { kind, objective, theoremName: 'target', type: 'True' } }); - for (const message of [context.instructions, context.continuationMessage]) { - expect(message).toContain('Audit objectives cannot change this exact proof deliverable'); - expect(message).toContain('Save diagnostics in RESEARCH.md; publish a needsDecision:true research finding to Lead'); - expect(message).toContain('do not resubmit unchanged proofs'); - } + expect(context.instructions).toContain('Audit objectives cannot change this exact proof deliverable'); + expect(context.instructions).toContain('Save diagnostics in RESEARCH.md; publish a needsDecision:true research finding to Lead'); + expect(context.instructions).toContain('do not resubmit unchanged proofs'); + expect(context.continuationMessage).toContain(JSON.stringify(context.workContract)); expect(context.instructions).not.toContain('You are a Mathematical Researcher'); expect(context.instructions).toContain('Prove the assigned Lean declaration with its exact requested type'); }); it('asks researchers to save scoped negative evidence and publish a schema-valid gap decision promptly', () => { const context = gapContext('research'); - expect(context.instructions).toContain('Publish a single research observation promptly with theorem-os research-observe'); + expect(context.instructions).toContain('Use research-observe from .scratch/theoremos-help.md'); expect(context.instructions).not.toContain('no separate research observation is required'); expect(context.instructions).toContain('Save a scoped negative library result or a classification gap in worktree-root RESEARCH.md as soon as it is established'); expect(context.instructions).toContain('pinned library/environment version, searched paths, queries or method, exact result'); expect(context.instructions).toContain('A scoped search failure is not proof of global absence'); expect(context.instructions).toContain('needsDecision:true, conclusion:"inconclusive"'); - const encoded = context.instructions.split('To share an advisory finding or an unresolved proof gap, append ')[1].split('. Inline the full finding;')[0]; - const publication = JSON.parse(encoded); - expect(publication.kind).toBe('research'); - const finding = parseMathResponse(JSON.stringify(publication.finding), 'math-result', { taskId: 'frontier' }, 'summary'); - expect(finding).toMatchObject({ taskId: 'frontier', needsDecision: true, conclusion: 'inconclusive' }); - expect(deliveryDetails(finding)).toMatchObject({ evidenceRefs: [], - remainingObligations: ['precise unresolved mathematical inference'] }); - expect(context.instructions).toContain('publishing does not finish or park your proof task'); + expect(context.instructions).toContain('Ordinary findings share progress'); expect(context.instructions).toContain('Restore Lean sources to the assignment seed before ordinary findings delivery.'); expect(context.instructions).toContain('after the host acknowledges the submission'); expect(context.instructions).toContain('visible kind:"goal" original consumer'); @@ -426,15 +398,8 @@ it.each(['research', 'lemma', 'goal'] as const)('keeps scoped no-rescan and dura expect(context.instructions).toContain('First check the key mathematical premise and structural bridge against the exact definitions'); expect(context.instructions).toContain('A checked conditional wrapper establishes sufficiency under its explicit conditions; keep its unproved conditions on the frontier'); expect(context.manifest!.optionalBytes).toBe(0); - for (const message of [context.instructions, context.continuationMessage]) { - if (kind === 'research') expect(message).not.toContain('add a top-level sources object'); - else { - expect(message).toContain('add a top-level sources object'); - expect(message).toContain('Omit commit when using sources'); - expect(message).toContain('Source changes after that report require a fresh source-bound finding'); - expect(message).toContain('Auxiliary code and a reported gap never accept the assigned proof'); - } - } + if (kind === 'research') expect(context.instructions).not.toContain('Use research-observe --snapshot-sources'); + else expect(context.instructions).toContain('Use research-observe --snapshot-sources when a finding depends on changed saved Lean code.'); }); it('asks the Lead for a real reduction with zero optional context', () => { @@ -475,7 +440,7 @@ it.each(['research', 'lemma', 'goal'] as const)( expect(context.continuationMessage).toContain(JSON.stringify(context.assignment)); expect(context.continuationMessage).toContain(JSON.stringify(context.workContract)); expect(context.continuationMessage).toContain('COOPERATION.json'); - expect(context.continuationMessage).toContain('proof acceptance'); + expect(context.continuationMessage).toContain('Resume the saved argument from RESEARCH.md'); expect(context.message).toContain('Frozen source context and immutable retrieval references:'); expect(context.manifest).toBeDefined(); }); @@ -523,7 +488,7 @@ it('keeps current task feedback and scoped intake receipts inline without repeat expect(first.continuationMessage).not.toContain('old-env-secret'); expect(first.continuationMessage).not.toContain(fullFinding); expect(first.continuationMessage!.length).toBeLessThan(first.message.length / 2); - expect(first.continuationMessage).toContain('matching task digest does not mean its feedback or inbox is unchanged'); + expect(first.continuationMessage).toContain('Read the relevant new records in COOPERATION.json'); state.cooperation!.tasks[0].feedback = 'New diagnostic under the same exact task digest.'; const updated = { ...receipt, id: 'new-receipt', issues: [{ path: 'summary', message: 'Include the new exact counterexample.' }] }; state.cooperation!.deliveryReceipts!.push(updated); diff --git a/tests/solverCooperativeCheckpoints.test.ts b/tests/solverCooperativeCheckpoints.test.ts index a3577894..1062c6c2 100644 --- a/tests/solverCooperativeCheckpoints.test.ts +++ b/tests/solverCooperativeCheckpoints.test.ts @@ -1,4 +1,5 @@ import fs from 'node:fs'; +import { spawnSync } from 'node:child_process'; import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { MathAgentOptions, MathAgentSession } from '../src/runtime/codexSession'; @@ -235,32 +236,35 @@ describe('cooperative advisory scheduling checkpoints', () => { controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); }); - it.each([false, true])('publishes the research reminder example through the current assignment protocol (needs decision: %s)', async needsDecision => { + it.each([false, true])('publishes the research reminder through research-observe (needs decision: %s)', async needsDecision => { const { state, workers, check, controller, run, pulse } = fixture(); const held = heldAdvisoryTurns(1), completion = run(held.open, 1); void completion.catch(() => {}); await held.wait(0, completion); await vi.advanceTimersByTimeAsync(90_000); const message = held.notify.mock.calls[0]![0] as string; - const example = message.match(/Append one complete JSON line to ("(?:\\.|[^"])*"): (\{"kind":"research".*?\}\})\./u); - expect(example).not.toBeNull(); - const log = JSON.parse(example![1]) as string; - expect(log).toBe(path.join(workers[1].worktree, assignmentDeliveryFile(held.actions[0].assignment))); - const value = JSON.parse(example![2]); - expect(value.finding).not.toHaveProperty('needsDecision'); - value.finding.summary = needsDecision - ? 'The saved search resolves the available identities but leaves the uniform norm estimate open; Lead must choose a different estimate.' - : 'The saved algebraic reduction supplies the exact identity needed by the consumer.'; - value.finding.conclusion = needsDecision ? 'inconclusive' : 'supporting'; - value.finding.remainingObligations = needsDecision ? ['Construct the uniform norm estimate.'] : []; - if (needsDecision) value.finding.needsDecision = true; - fs.writeFileSync(path.join(workers[1].worktree, 'RESEARCH.md'), value.finding.summary + '\n'); - fs.appendFileSync(log, JSON.stringify(value) + '\n'); + expect(message).toContain('publish it with research-observe'); + const finding = { + summary: needsDecision + ? 'The saved search resolves the available identities but leaves the uniform norm estimate open; Lead must choose a different estimate.' + : 'The saved algebraic reduction supplies the exact identity needed by the consumer.', + conclusion: needsDecision ? 'inconclusive' : 'supporting', + remainingObligations: needsDecision ? ['Construct the uniform norm estimate.'] : [], + ...(needsDecision ? { needsDecision: true } : {}), + }; + const worktree = workers[1].worktree; + const file = path.join(worktree, '.scratch', 'finding.json'); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(path.join(worktree, 'RESEARCH.md'), finding.summary + '\n'); + fs.writeFileSync(file, JSON.stringify(finding)); + const published = spawnSync('bun', ['bin/math.ts', 'research-observe', '--worktree', worktree, '--finding', file], + { encoding: 'utf8', timeout: 15_000 }); + expect(published.status, published.stdout || published.stderr).toBe(0); const wakes = state.cooperation!.leadWakes!.requested; await pulse(workers[1].id); const delivery = state.cooperation!.deliveries!.find(item => item.taskId === held.actions[0].task.id && item.kind === 'research'); expect(delivery).toMatchObject({ taskDigest: held.actions[0].assignment.taskDigest, - summary: value.finding.summary, status: needsDecision ? 'conditional' : 'advisory' }); - expect(JSON.parse(delivery!.finding!)).toMatchObject(value.finding); + summary: finding.summary, status: needsDecision ? 'conditional' : 'advisory' }); + expect(JSON.parse(delivery!.finding!)).toMatchObject(finding); expect(state.cooperation!.leadWakes!.requested).toBe(wakes + (needsDecision ? 1 : 0)); if (needsDecision) expect(state.cooperation!.leadWakes!.recent!.at(-1)!.reason).toBe('research-finding'); expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); @@ -325,9 +329,7 @@ describe('cooperative advisory scheduling checkpoints', () => { }) + '\n```\n'; fs.writeFileSync(path.join(workers[1].worktree, 'RESEARCH.md'), notes); await vi.advanceTimersByTimeAsync(90_000); - expect(held.notify.mock.calls[0][0]).toContain('Append one complete JSON line to'); - expect(held.notify.mock.calls[0][0]).toContain(assignmentDeliveryFile(held.actions[0].assignment)); - expect(held.notify.mock.calls[0][0]).toContain('"kind":"research","finding":'); + expect(held.notify.mock.calls[0][0]).toContain('publish it with research-observe'); await vi.advanceTimersByTimeAsync(30_000); await stopping.promise; expect(state.cooperation!.deliveries ?? []).toEqual([]); expect(state.cooperation!.researchDrafts?.investigate).toBeUndefined(); @@ -937,14 +939,15 @@ describe('cooperative advisory scheduling checkpoints', () => { await held.wait(0, completion); held.open.mock.calls[0][0].onActivity!({ event: 'reasoning' }); const request = state.workers![0].contextCheckpoint!; - // The Lead's checkpoint request names only its own protocol and defines the digest it must append. + // The Lead's checkpoint request supplies a complete command. const instruction = held.notify.mock.calls.map(([message]) => message).find(message => message.includes(request.requestId!))!; expect(instruction).toContain('a Lead publishes no findings'); - expect(instruction).toContain('as printed by sha256sum RESEARCH.md'); + expect(instruction).toContain('checkpoint --worktree'); expect(instruction).not.toContain('needsDecision'); const log = held.messages[0].receipt!; - fs.appendFileSync(path.join(workers[0].worktree, log), JSON.stringify({ kind: 'checkpoint', requestId: request.requestId, - notesDigest: mathDigest(fs.readFileSync(path.join(workers[0].worktree, 'RESEARCH.md'))) }) + '\n'); + const acknowledged = spawnSync('bun', ['bin/math.ts', 'checkpoint', '--worktree', workers[0].worktree, + '--log', log, '--request-id', request.requestId!], { encoding: 'utf8', timeout: 15_000 }); + expect(acknowledged.status, acknowledged.stdout || acknowledged.stderr).toBe(0); await pulse(workers[0].id); await vi.advanceTimersByTimeAsync(5_000); await held.wait(1, completion); expect(held.threads).toEqual(['continuation-thread-1', 'continuation-thread-2']); @@ -1663,7 +1666,7 @@ describe('cooperative advisory scheduling checkpoints', () => { await vi.advanceTimersByTimeAsync(1); expect(sessions.get('solver')!.notify).toHaveBeenCalledOnce(); expect(sessions.get('solver')!.notify.mock.calls[0]![0]).toMatch(/^If the first plan is still unpublished, publish it now/u); - expect(sessions.get('solver')!.notify.mock.calls[0]![0]).toContain('If the host accepted it while this notice was waiting'); + expect(sessions.get('solver')!.notify.mock.calls[0]![0]).toContain('plan-apply --publish'); expect(sessions.get('solver')!.interrupt).not.toHaveBeenCalled(); await vi.advanceTimersByTimeAsync(20 * 60_000 - 90_000); await proofStarted.promise; diff --git a/tests/solverInitialPlan.test.ts b/tests/solverInitialPlan.test.ts index 8c507a7f..8ce3f9be 100644 --- a/tests/solverInitialPlan.test.ts +++ b/tests/solverInitialPlan.test.ts @@ -76,7 +76,7 @@ describe('explicit initial Lead plan publication', () => { expect(assigned).toMatchObject({ kind: 'task', task: { id: 'goal_1' } }); expect(cooperative.current(action)).toBe(true); expect(action).toEqual(originalAction); - expect(cooperative.initialPlanSnapshot(action)?.tasks.map(task => task.id)).toEqual(['goal_1', 'goal_2']); + expect(cooperative.hasLeadPublication(action)).toBe(true); expect(state.cooperation!.initialPlanPublication).toMatchObject({ nonce: action.initialPlanNonce, baseVersion: originalAction.planVersion, planVersion: state.cooperation!.planVersion }); expect(interrupt).not.toHaveBeenCalled(); @@ -159,7 +159,7 @@ describe('explicit initial Lead plan publication', () => { expect(state.cooperation!.edits?.[0].status).toBe('applied'); expect(cooperative.current(action)).toBe(false); expect(cooperative.started(lead, action)).toBe(false); - expect(cooperative.initialPlanSnapshot(action)).toBeUndefined(); + expect(cooperative.hasLeadPublication(action)).toBe(false); expect(interrupt).toHaveBeenCalledOnce(); }); @@ -198,10 +198,11 @@ describe('explicit initial Lead plan publication', () => { expect(cooperative.current({ ...action })).toBe(false); }); - it.each([false, true])('keeps a published plan after a notes-only final delivery (request failure: %s)', async recovering => { + it.each([false, true])('keeps a published plan when the final notes include illustrative JSON (request failure: %s)', async recovering => { const cooperative = create(), action = await startLead(cooperative); await publish(cooperative, action); - fs.writeFileSync(path.join(lead.worktree, 'RESEARCH.md'), 'The peers can work while the next mathematical route is investigated.\n'); + fs.writeFileSync(path.join(lead.worktree, 'RESEARCH.md'), 'The peers can work while the next mathematical route is investigated.\n\n' + + '```json\n{"example":{"tasks":["check the boundary case"]}}\n```\n'); cooperative.deactivate(lead); const delivered = await cooperative.deliver(lead, action, commitSolverSources(problem, lead.worktree), recovering, 'request-failure'); expect(delivered).toEqual({ checkWhole: false, ...(recovering ? { savedPlan: true } : {}) }); diff --git a/tests/solverInputs.test.ts b/tests/solverInputs.test.ts index bb71d774..fef1f839 100644 --- a/tests/solverInputs.test.ts +++ b/tests/solverInputs.test.ts @@ -29,57 +29,54 @@ describe('solver input boundaries', () => { expect(() => readMathText(file, 64)).toThrow(); }); - it.each([false, true])('tracks log byte offsets across blank lines, CRLF and partial writes (recovery=%s)', recovery => { + it('tracks log byte offsets across blank lines, CRLF and partial writes', () => { const file = path.join(temp(), 'edits.jsonl'); - const read = (offset: number) => readDeliveryLines(file, offset, recovery ? { discardingOversized: false } : undefined); const prefix = '\n' + JSON.stringify({ summary: '\u6570\u5b66' }) + '\r\n'; fs.writeFileSync(file, prefix + '{"partial":'); - const batch = read(0); - expect(batch.lines).toEqual([JSON.stringify({ summary: '\u6570\u5b66' }) + '\r']); - expect(batch.entries?.map(entry => entry.offset)).toEqual([1, Buffer.byteLength(prefix)]); + const batch = readDeliveryLines(file, 0); + expect(batch.entries.map(entry => entry.line)).toEqual(['', JSON.stringify({ summary: '\u6570\u5b66' }) + '\r']); + expect(batch.entries.map(entry => entry.offset)).toEqual([1, Buffer.byteLength(prefix)]); expect(batch.offset).toBe(Buffer.byteLength(prefix)); - expect(Object.hasOwn(batch, 'discardingOversized')).toBe(recovery); fs.appendFileSync(file, 'true}\n'); - const resumed = read(batch.offset); - expect(resumed.lines).toEqual(['{"partial":true}']); - expect(resumed.entries?.[0].offset).toBe(fs.statSync(file).size); + expect(readDeliveryLines(file, batch.offset).entries) + .toEqual([{ line: '{"partial":true}', offset: fs.statSync(file).size, discardingOversized: false }]); }); - it.each([false, true])('rereads an incomplete UTF-8 line crossing the chunk boundary (recovery=%s)', recovery => { + it('rereads an incomplete UTF-8 line crossing the chunk boundary', () => { const file = path.join(temp(), 'edits.jsonl'), prefix = 'x'.repeat(MAX_DELIVERY_LINE_BYTES - 2) + '\n', tail = '\u6570\u5b66\n'; - const read = (offset: number) => readDeliveryLines(file, offset, recovery ? { discardingOversized: false } : undefined); fs.writeFileSync(file, prefix + tail); - const batch = read(0); - expect(batch.lines).toEqual([prefix.slice(0, -1)]); + const batch = readDeliveryLines(file, 0); + expect(batch.entries.map(entry => entry.line)).toEqual([prefix.slice(0, -1)]); expect(batch.offset).toBe(Buffer.byteLength(prefix)); - expect(read(batch.offset)).toMatchObject({ lines: [tail.slice(0, -1)], offset: fs.statSync(file).size }); + expect(readDeliveryLines(file, batch.offset)).toMatchObject({ + entries: [{ line: tail.slice(0, -1) }], offset: fs.statSync(file).size }); }); - it.each([false, true])('accepts a complete line filling the read chunk (recovery=%s)', recovery => { + it('accepts a complete line filling the read chunk', () => { const file = path.join(temp(), 'edits.jsonl'), line = 'x'.repeat(MAX_DELIVERY_LINE_BYTES); fs.writeFileSync(file, line + '\n'); - expect(readDeliveryLines(file, 0, recovery ? { discardingOversized: false } : undefined)) - .toMatchObject({ lines: [line], offset: MAX_DELIVERY_LINE_BYTES + 1, + expect(readDeliveryLines(file, 0)) + .toMatchObject({ offset: MAX_DELIVERY_LINE_BYTES + 1, entries: [{ line, offset: MAX_DELIVERY_LINE_BYTES + 1, discardingOversized: false }] }); }); - it('skips a log rewritten below the cursor once for recovery callers and stays strict otherwise', () => { + it('skips a log rewritten below the cursor and discards its unfinished line', () => { const file = path.join(temp(), 'DELIVERIES.jsonl'), first = '{"summary":"first"}\n', second = '{"summary":"second"}\n'; fs.writeFileSync(file, first + second); - const end = readDeliveryLines(file, 0, { discardingOversized: false }).offset; + const end = readDeliveryLines(file, 0).offset; fs.writeFileSync(file, second); - expect(() => readDeliveryLines(file, end)).toThrow('math_delivery_log_invalid'); - expect(readDeliveryLines(file, end, { discardingOversized: false })).toEqual({ lines: [], offset: second.length, + expect(readDeliveryLines(file, end)).toMatchObject({ offset: second.length, entries: [{ error: 'math_delivery_log_rewritten', offset: second.length, discardingOversized: false }], discardingOversized: false }); fs.writeFileSync(file, second + '{"summ'); - const rewritten = readDeliveryLines(file, end, { discardingOversized: false }); - expect(rewritten).toMatchObject({ lines: [], offset: fs.statSync(file).size, discardingOversized: true, - entries: [{ error: 'math_delivery_log_rewritten', offset: second.length, discardingOversized: true }] }); + const rewritten = readDeliveryLines(file, end); + const rewrittenEnd = fs.statSync(file).size; + expect(rewritten).toMatchObject({ offset: rewrittenEnd, discardingOversized: true, + entries: [{ error: 'math_delivery_log_rewritten', offset: rewrittenEnd, discardingOversized: true }] }); fs.appendFileSync(file, 'ary":"fragment"}\n' + first); - expect(readDeliveryLines(file, rewritten.offset, { discardingOversized: true })) - .toMatchObject({ lines: [first.slice(0, -1)], offset: fs.statSync(file).size, discardingOversized: false }); + expect(readDeliveryLines(file, rewritten.offset, rewritten.discardingOversized)) + .toMatchObject({ entries: [{ line: first.slice(0, -1) }], offset: fs.statSync(file).size, discardingOversized: false }); fs.writeFileSync(file, ''); - expect(readDeliveryLines(file, end, { discardingOversized: true })).toEqual({ lines: [], offset: 0, + expect(readDeliveryLines(file, end, true)).toMatchObject({ offset: 0, entries: [{ error: 'math_delivery_log_rewritten', offset: 0, discardingOversized: false }], discardingOversized: false }); }); @@ -88,7 +85,7 @@ describe('solver input boundaries', () => { fs.writeFileSync(file, 'x'.repeat(MAX_DELIVERY_LINE_BYTES * 2)); const read = vi.spyOn(fs, 'readSync'); try { - expect(readDeliveryLines(file, MAX_DELIVERY_LINE_BYTES * 3, { discardingOversized: false })).toMatchObject({ lines: [], + expect(readDeliveryLines(file, MAX_DELIVERY_LINE_BYTES * 3)).toMatchObject({ offset: MAX_DELIVERY_LINE_BYTES * 2, discardingOversized: true, entries: [{ error: 'math_delivery_log_rewritten' }] }); expect(read.mock.calls.every(call => (call[3] as number) <= MAX_DELIVERY_LINE_BYTES + 1)).toBe(true); } finally { read.mockRestore(); } diff --git a/tests/solverLeadCheckpointSemantics.test.ts b/tests/solverLeadCheckpointSemantics.test.ts index 7d2d98de..40acda1a 100644 --- a/tests/solverLeadCheckpointSemantics.test.ts +++ b/tests/solverLeadCheckpointSemantics.test.ts @@ -124,27 +124,21 @@ describe('Lead scheduling checkpoint control responses', () => { vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); }); - it('corrects a saved incomplete Lead decision in the same dispatch without publishing the draft', async () => { + it('reports a saved incomplete Lead decision at checkpoint handoff without publishing the draft', async () => { const action = await start(), before = structuredClone(state.cooperation!.tasks); await cooperative.pulse(); expect(notify).not.toHaveBeenCalled(); // The inherited accepted graph is still just the dispatch seed. write({ ...graph(), tasks: [...graph().tasks, proposal] }); await cooperative.pulse(); - expect(notify).toHaveBeenCalledOnce(); - const message = notify.mock.calls[0][0]; - expect(message).toContain('math_plan_research_decisions_missing'); - expect(message).toContain('proposal-delivery'); - expect(message).toContain(leadPlanDeliveryFile(action)); - expect(message).toContain('has not accepted the plan or any proof'); + expect(notify).not.toHaveBeenCalled(); + expect(cooperative.leadCheckpointHandoff(action)?.reason).toContain('math_plan_research_decisions_missing'); + expect(cooperative.leadCheckpointInstruction(action)).toContain('proposal-delivery'); expect(state.cooperation!.tasks).toEqual(before); expect(state.cooperation!.researchDecisions).toBeUndefined(); expect(state.cooperation!.planPublication).toBeUndefined(); expect(state.cooperation!.planRejection).toBeUndefined(); - await cooperative.pulse(); await cooperative.pulse(); - expect(notify).toHaveBeenCalledOnce(); write({ ...graph(), tasks: [...graph().tasks, proposal], ...decide('adopt') }); - await cooperative.pulse(); - expect(notify).toHaveBeenCalledOnce(); + expect(cooperative.leadCheckpointHandoff(action)).toBeUndefined(); expect(state.cooperation!.tasks).toEqual(before); await checkpoint(action); expect(state.cooperation!.tasks.find(node => node.task.id === proposal.id)?.status).toBe('pending'); @@ -161,7 +155,6 @@ describe('Lead scheduling checkpoint control responses', () => { fs.writeFileSync(notes(), text); await cooperative.pulse(); } expect(notify).not.toHaveBeenCalled(); - expect(events.some(item => item.event === 'lead_draft_correction_requested')).toBe(false); }); it('ignores an unpublished draft after its dispatch has already published a valid decision', async () => { @@ -194,17 +187,6 @@ describe('Lead scheduling checkpoint control responses', () => { expect(pendingProposals()).toHaveLength(1); }); - it('retries a failed correction notification without losing or accepting the saved draft', async () => { - await start(); - notify.mockRejectedValueOnce(new Error('fixture_request_boundary_unavailable')); - write({ ...graph(), tasks: [...graph().tasks, proposal] }); - await cooperative.pulse(); await Promise.resolve(); - await cooperative.pulse(); - expect(notify).toHaveBeenCalledTimes(2); - expect(state.cooperation!.planPublication).toBeUndefined(); - expect(pendingProposals()).toHaveLength(1); - }); - it.each([false, true])('retains an unanswered research decision in an unchanged control draft (prose-only: %s)', async prose => { const action = await start(), before = structuredClone(state.cooperation!.tasks), base = state.cooperation!.planVersion; const pending = pendingProposals().map(item => item.id); @@ -246,7 +228,7 @@ describe('Lead scheduling checkpoint control responses', () => { expect(reminder).toContain('researchDecisions: ["proposal-delivery"]'); expect(reminder).toContain('task graph stays unchanged'); expect(JSON.parse(reminder.match(/Current response template[^\n]*\n([^\n]+)\n/u)![1])).toMatchObject({ - kind: 'plan', dispatchNonce: action.planNonce, baseVersion: action.planVersion, upsert: [], + baseVersion: action.planVersion, upsert: [], }); expect(reminder).not.toContain('return without a revision'); await checkpoint(action); @@ -383,7 +365,7 @@ describe('Lead scheduling checkpoint control responses', () => { } write({ ...graph(), ...decide('decline') }); await cooperative.pulse(); - expect(notify.mock.calls.at(-1)?.[0]).toContain('math_plan_progress_review_missing'); + expect(cooperative.leadCheckpointHandoff(action)?.reason).toContain('math_plan_progress_review_missing'); expect(state.cooperation!.goalProgress!.pending?.id).toBe(progress.pending.id); expect(state.cooperation!.researchDecisions).toBeUndefined(); }); diff --git a/tests/solverLeadInheritedDraftCorrection.test.ts b/tests/solverLeadInheritedDraftCorrection.test.ts index dcc49649..3494d0cf 100644 --- a/tests/solverLeadInheritedDraftCorrection.test.ts +++ b/tests/solverLeadInheritedDraftCorrection.test.ts @@ -5,7 +5,7 @@ import type { SolverRunState } from '../src/solver/archive'; import type { CooperativeResearch } from '../src/solver/cooperation'; import type { ResearchWorker } from '../src/solver/modules/organization'; import { commitSolverSources, type SolverProblem } from '../src/solver/problem'; -import { leadPlanDeliveryFile, parseCooperationPlan, taskVersion, type CooperativeAction, type CooperativeTask } from '../src/solver/tasks'; +import { parseCooperationPlan, taskVersion, type CooperativeAction, type CooperativeTask } from '../src/solver/tasks'; import { cooperativeResearch } from './helpers/cooperation'; import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; @@ -80,19 +80,17 @@ describe('correction of inherited rejected Lead drafts', () => { vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); }); - it('corrects a previously rejected inherited draft once, while leaving the plan and decisions unpublished', async () => { + it('reports a previously rejected inherited draft at checkpoint handoff without publishing it', async () => { const action = await rejectForRetry(), before = structuredClone(state.cooperation!.tasks); - await cooperative.pulse(); await cooperative.pulse(); - expect(notify).toHaveBeenCalledOnce(); - expect(notify.mock.calls[0][0]).toContain('math_plan_research_decisions_missing'); - expect(notify.mock.calls[0][0]).toContain('unanswered-finding'); - expect(notify.mock.calls[0][0]).toContain(leadPlanDeliveryFile(action)); + await cooperative.pulse(); + expect(notify).not.toHaveBeenCalled(); + expect(cooperative.leadCheckpointHandoff(action)?.reason).toContain('math_plan_research_decisions_missing'); + expect(cooperative.leadCheckpointInstruction(action)).toContain('unanswered-finding'); expect(state.cooperation!.tasks).toEqual(before); expect(state.cooperation!.researchDecisions).toBeUndefined(); expect(state.cooperation!.planPublication).toBeUndefined(); write({ ...graph(), ...decision() }); - await cooperative.pulse(); - expect(notify).toHaveBeenCalledOnce(); + expect(cooperative.leadCheckpointHandoff(action)).toBeUndefined(); expect(state.cooperation!.researchDecisions).toBeUndefined(); expect(state.cooperation!.planPublication).toBeUndefined(); expect(state.cooperation!.error).toContain('math_plan_research_decisions_missing'); @@ -102,19 +100,9 @@ describe('correction of inherited rejected Lead drafts', () => { expect(state.cooperation!.error).toBeUndefined(); }); - it('retries a failed correction notification for the inherited rejected draft', async () => { - await rejectForRetry(); - notify.mockRejectedValueOnce(new Error('fixture_notification_unavailable')); - await cooperative.pulse(); await Promise.resolve(); - await cooperative.pulse(); await cooperative.pulse(); - expect(notify).toHaveBeenCalledTimes(2); - expect(state.cooperation!.researchDecisions).toBeUndefined(); - expect(state.cooperation!.planPublication).toBeUndefined(); - }); - - it('keeps an ordinary accepted baseline quiet when only new research requires a decision', async () => { - await start(); await cooperative.pulse(); await cooperative.pulse(); - expect(notify).not.toHaveBeenCalled(); + it('requests the decision without diagnosing an ordinary accepted baseline as a rejected draft', async () => { + const action = await start(); + expect(cooperative.leadCheckpointHandoff(action)).toEqual({ reason: undefined }); expect(state.cooperation!.planRejection).toBeUndefined(); expect(state.cooperation!.researchDecisions).toBeUndefined(); }); @@ -125,19 +113,18 @@ describe('correction of inherited rejected Lead drafts', () => { await checkpoint(action); expect(state.cooperation!.planRejection?.error).toContain('math_plan_research_decisions_missing'); write(graph()); - await start(); await cooperative.pulse(); await cooperative.pulse(); - expect(notify).not.toHaveBeenCalled(); + const retry = await start(); + expect(cooperative.leadCheckpointHandoff(retry)).toEqual({ reason: undefined }); expect(state.cooperation!.researchDecisions).toBeUndefined(); }); it('does not correct a missing research decision already settled by other accepted evidence', async () => { - await rejectForRetry(); + const action = await rejectForRetry(); const finding = state.cooperation!.deliveries!.find(record => record.id === 'unanswered-finding')!; state.cooperation!.researchDecisions = [{ deliveryId: finding.id, taskDigest: finding.taskDigest, findingDigest: finding.findingDigest, outcome: 'decline', reason: 'An accepted decision already settled this finding.', at: 1, planVersion: state.cooperation!.planVersion! }]; - await cooperative.pulse(); - expect(notify).not.toHaveBeenCalled(); + expect(cooperative.leadCheckpointHandoff(action)?.reason).toBeUndefined(); expect(state.cooperation!.planPublication).toBeUndefined(); }); }); diff --git a/tests/solverPlanApproval.test.ts b/tests/solverPlanApproval.test.ts index 63196c1d..9935bd17 100644 --- a/tests/solverPlanApproval.test.ts +++ b/tests/solverPlanApproval.test.ts @@ -3,6 +3,7 @@ import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; import type { CooperativeResearch } from '../src/solver/cooperation'; +import { MAX_DELIVERY_LINE_BYTES } from '../src/solver/deliveries'; import type { ResearchWorker } from '../src/solver/modules/organization'; import { planApprovalInspection, planApprovalLog } from '../src/solver/planApproval'; import { commitSolverSources, type SolverProblem } from '../src/solver/problem'; @@ -133,13 +134,17 @@ describe('plan approval before dispatch (--plan-approval)', () => { expect(planApprovalInspection(state)).toMatchObject({ required: false, status: 'not-required' }); }); - it('applies an edit before an approval read in the same pulse, so the approval of the older plan conflicts', async () => { + it.each([false, true])('applies queued edits before checking an approval of the old plan (oversized entry: %s)', async oversized => { const cooperative = create(), action = await startLead(cooperative); await publish(cooperative, action); const read = state.cooperation!.planVersion!; - fs.appendFileSync(path.join(directory, 'edits.jsonl'), JSON.stringify({ id: 'owner-edit', baseVersion: read, ...plan('_edited') }) + '\n'); + const edits = path.join(directory, 'edits.jsonl'); + if (oversized) fs.writeFileSync(edits, 'x'.repeat(MAX_DELIVERY_LINE_BYTES + 1) + '\n'); + fs.appendFileSync(edits, JSON.stringify({ id: 'owner-edit', baseVersion: read, ...plan('_edited') }) + '\n'); await approve(cooperative, 'owner', read); - expect(state.cooperation!.edits?.[0]).toMatchObject({ id: 'owner-edit', status: 'applied' }); + expect(state.cooperation!.edits?.at(-1)).toMatchObject({ id: 'owner-edit', status: 'applied' }); + expect(named('edit_rejected').map(event => event?.reason)).toEqual(oversized ? ['math_delivery_line_too_large'] : []); + expect(state.cooperation!.cursors?.edits).toBe(fs.statSync(edits).size); expect(state.cooperation!.planVersion).not.toBe(read); expect(state.cooperation!.planApproval!.rejections).toEqual([expect.objectContaining({ id: 'owner', reason: 'math_plan_approval_version_conflict', planVersion: read })]); @@ -149,6 +154,30 @@ describe('plan approval before dispatch (--plan-approval)', () => { await approve(cooperative, 'owner-again'); expect(await waiting).toMatchObject({ kind: 'task', task: { id: 'goal_1_edited' } }); }); + + it('continues reading approvals after a shortened log across restart', async () => { + const cooperative = create(), action = await startLead(cooperative); + await publish(cooperative, action); + const log = planApprovalLog(path.join(directory, 'state.json')); + const version = state.cooperation!.planVersion!; + await approve(cooperative, 'stale', 'obsolete-version'); + const oldOffset = state.cooperation!.cursors!.planApprovals; + fs.writeFileSync(log, '{"id":"ignored","planVersion":"'); + expect(fs.statSync(log).size).toBeLessThan(oldOffset); + await cooperative.pulse(); + expect(named('plan_approval_rejected').map(event => event?.reason)) + .toEqual(['math_plan_approval_version_conflict', 'math_delivery_log_rewritten']); + expect(planApprovalInspection(state).status).toBe('pending'); + + const stateFile = path.join(directory, 'state.json'); + writeSolverRunState(stateFile, state); + state = readSolverRunState(stateFile); + const resumed = create(); + fs.appendFileSync(log, version + '"}\n'); + await approve(resumed, 'owner', version); + expect(named('plan_approved')).toEqual([{ id: 'owner', planVersion: version }]); + expect(named('plan_approval_rejected')).toHaveLength(2); + }); it('gives the Lead one revision turn per owner note while the plan waits', async () => { const cooperative = create(), action = await startLead(cooperative); await publish(cooperative, action); diff --git a/tests/solverPlanPatch.test.ts b/tests/solverPlanPatch.test.ts index 8592d304..1d0a877f 100644 --- a/tests/solverPlanPatch.test.ts +++ b/tests/solverPlanPatch.test.ts @@ -65,7 +65,9 @@ describe('Lead plan revisions in a cooperative run', () => { await publish(action, { upsert: [helper('patched_bridge')] }); expect(ids()).toEqual([...goals, 'patched_bridge']); expect(events.filter(event => event.event === 'plan_published')).toHaveLength(1); - fs.writeFileSync(notes(), 'A notes-only final response.\n'); + const argument = 'A notes-only final response.\n\n' + 'An intermediate estimate with details.\n'.repeat(250) + + '\n```json\n{"example":{"tasks":["compare two cases"]}}\n```\n\nThe remaining inference is at the boundary.\n'; + fs.writeFileSync(notes(), argument); await finish(action); expect(state.cooperation!.planPublication?.finalized).toBe(true); expect(state.cooperation!.planEdited).toBe(true); @@ -73,7 +75,7 @@ describe('Lead plan revisions in a cooperative run', () => { const text = fs.readFileSync(notes(), 'utf8'); expect(readMathResponse(workers[0].worktree, 'math-plan').tasks.map((task: { id: string }) => task.id)).toEqual(ids()); expect(text.split('\n').filter(line => line.startsWith(' {"id":"'))).toHaveLength(ids().length + 1); - expect(text).toContain('A notes-only final response.'); + expect(text).toContain(argument); }); it('accepts a live revision nested under tasks as the same top-level revision', async () => { diff --git a/tests/solverPlanPublication.test.ts b/tests/solverPlanPublication.test.ts index c08ccbf1..71c67638 100644 --- a/tests/solverPlanPublication.test.ts +++ b/tests/solverPlanPublication.test.ts @@ -5,8 +5,10 @@ import { readSolverRunState, writeSolverRunState, type SolverRunState } from '.. import type { CooperativeResearch } from '../src/solver/cooperation'; import { requestLeadWake } from '../src/solver/leadWakes'; import type { ResearchWorker } from '../src/solver/modules/organization'; +import { publishCooperationPlanFile } from '../src/solver/planTool'; import { commitSolverSources, type SolverProblem } from '../src/solver/problem'; import { leadPlanDeliveryFile, parseCooperationPlan, type CooperativeAction } from '../src/solver/tasks'; +import { deferred } from './helpers/async'; import { cooperativeResearch } from './helpers/cooperation'; import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; import { integratedProof } from './helpers/taskProof'; @@ -19,10 +21,10 @@ describe('live replacement plan publication', () => { let events: { event: string; details?: Record }[], pending: Promise[]; const graph = () => ({ tasks: state.cooperation!.tasks.map(node => node.task), groups: state.cooperation!.groups!.map(route => route.group) }); - const create = () => { + const create = (exclusiveCheck: (check: () => Promise) => Promise = async check => check()) => { const controller = new AbortController(); const result = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, - emit: (event, details) => events.push({ event, details }) }); + exclusiveCheck, emit: (event, details) => events.push({ event, details }) }); instances.push({ cooperative: result, controller }); return result; }; @@ -101,6 +103,16 @@ describe('live replacement plan publication', () => { expect(events.filter(event => event.event === 'plan_published')).toHaveLength(1); }); + it('closes the publish command after a publication that leaves the plan version unchanged', async () => { + const action = await start(), workspace = workers[0].worktree; + await publish(action); + expect(state.cooperation!.planPublication?.planVersion).toBe(action.planVersion); + const acceptedLog = fs.readFileSync(file(action)); + expect(publishCooperationPlanFile({ workspace, text: JSON.stringify(withHelper('second_bridge')) })) + .toMatchObject({ ok: false, error: 'math_plan_publication_unavailable' }); + expect(fs.readFileSync(file(action))).toEqual(acceptedLog); + }); + it('requires both the dispatch nonce and current base version before accepting a replacement', async () => { const action = await start(), value = JSON.parse(line(action, withHelper('bridge'))); await publish(action, JSON.stringify({ ...value, dispatchNonce: 'different-dispatch' })); @@ -124,6 +136,28 @@ describe('live replacement plan publication', () => { expect(state.cooperation!.tasks.some(node => node.task.id === 'stale_bridge')).toBe(false); }); + it('rejects a publication still waiting for exclusive access when the run stops', async () => { + const waiting = deferred(), release = deferred(); + let pause = false; + cooperative = create(async check => { + if (pause) { waiting.resolve(); await release.promise; } + return check(); + }); + const action = await start(), before = graph(); + pause = true; + const polling = publish(action, line(action, withHelper('late_bridge'))); + await Promise.race([waiting.promise, polling]); + const stopped = cooperative.stop(); + release.resolve(); + await Promise.all([polling, stopped]); + + expect(graph()).toEqual(before); + expect(state.cooperation!.planPublication).toBeUndefined(); + expect(state.cooperation!.planPublicationRejection).toBeUndefined(); + expect(events).toContainEqual(expect.objectContaining({ event: 'plan_publication_rejected', + details: expect.objectContaining({ reason: 'math_plan_publication_superseded' }) })); + }); + it.each([false, true])('keeps a live graph when inherited plan notes remain in a notes-only final (append prose: %s)', async append => { fs.writeFileSync(path.join(workers[0].worktree, 'RESEARCH.md'), '```math-plan\n' + JSON.stringify(graph()) + '\n```'); const action = await start(); diff --git a/tests/solverPlanPublicationFeedback.test.ts b/tests/solverPlanPublicationFeedback.test.ts index 105ce979..8ad2ae57 100644 --- a/tests/solverPlanPublicationFeedback.test.ts +++ b/tests/solverPlanPublicationFeedback.test.ts @@ -1,4 +1,5 @@ import fs from 'node:fs'; +import { spawnSync } from 'node:child_process'; import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { mathDigest } from '../src/math/mathRuntimeIo'; @@ -62,13 +63,16 @@ describe('live Lead publication correction feedback', () => { fs.appendFileSync(path.join(workers[0].worktree, log(action)), (typeof value === 'string' ? value : JSON.stringify(value)) + '\n'); await cooperative.pulse(); }; - const expectCorrection = (message: string, action: Lead, reason: string) => { - for (const detail of [reason, log(action), action.planVersion!, nonce(action)]) expect(message).toContain(detail); - expect(message).toContain('"kind":"plan"'); - const target = JSON.parse(message.split('current publication target: ')[1].split('. Preserve the log')[0]); - expect(target).toEqual({ file: log(action), kind: 'plan', dispatchNonce: nonce(action), baseVersion: action.planVersion }); - expect(message).toMatch(/append/iu); - expect(message).toMatch(/complete/iu); + const expectCorrection = (message: string, _action: Lead, reason: string) => { + expect(message).toContain(reason); + expect(message).toContain('plan-apply --publish'); + }; + const submitDraft = async (action: Lead, draft: object) => { + const result = spawnSync('bun', ['bin/math.ts', 'plan-apply', '--publish', '--workspace', workers[0].worktree], + { input: JSON.stringify(draft), encoding: 'utf8', timeout: 15_000 }); + expect(result.status, result.stdout || result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ status: 'queued', file: log(action) }); + await cooperative.pulse(); }; const context = (action: Lead) => directSolverModules.M4.build(problem, { ...state, cooperation: cooperative.contextState(action, workers[0]) }, @@ -85,8 +89,8 @@ describe('live Lead publication correction feedback', () => { const checkpoint = (requestId: string, correct = false) => ({ kind: 'checkpoint', requestId, notesDigest: correct ? mathDigest(fs.readFileSync(path.join(workers[0].worktree, 'RESEARCH.md'))) : '0'.repeat(64) }); const expectCheckpointCorrection = (message: string, action: Lead, requestId: string, reason: string) => { - for (const detail of [requestId, reason, log(action), 'notesDigest', '"kind":"checkpoint"']) expect(message).toContain(detail); - expect(message).toMatch(/append/iu); + for (const detail of [requestId, reason, log(action), '--request-id', '--log']) expect(message).toContain(detail); + expect(message).toContain('rerun checkpoint'); expect(message).not.toContain('dispatchNonce'); expect(message).not.toContain('"kind":"plan"'); }; @@ -154,7 +158,7 @@ describe('live Lead publication correction feedback', () => { }); it.each(['initial', 'replacement'] as const)( - 'supplies the missing event envelope for a bare %s graph or patch', async kind => { + 'binds a bare %s graph or patch to the active dispatch', async kind => { prepare(kind); const action = await start(), before = structuredClone(state.cooperation); const graph = kind === 'initial' ? { tasks: completePlan.tasks, groups: completePlan.groups } @@ -167,13 +171,9 @@ describe('live Lead publication correction feedback', () => { expect(state.cooperation!.tasks).toEqual(before!.tasks); expect(state.cooperation!.planPublication).toBeUndefined(); const message = notify.mock.calls[0][0]; - const target = JSON.parse(message.match(/current publication target: (\{[^\n]+?\})\. /u)![1]); - const { file, ...envelope } = target; - expect(file).toBe(log(action)); - expect(envelope.kind).toBe('plan'); - expect(envelope.dispatchNonce).toBe(nonce(action)); - expect(message).toContain('top level of the same event'); - await publish(action, { ...envelope, ...graph }); + expect(message).toContain('plan-apply --publish'); + const { baseVersion: _base, ...draft } = graph as typeof graph & { baseVersion?: string }; + await submitDraft(action, draft); expect(rejected()).toHaveLength(1); expect(state.cooperation!.planPublicationRejection).toBeUndefined(); expect(state.cooperation!.planPublication).toMatchObject({ nonce: nonce(action) }); @@ -199,12 +199,12 @@ describe('live Lead publication correction feedback', () => { const message = notify.mock.calls[0][0]; expect(message).toContain('Current response template'); const template = JSON.parse(message.split('the template itself is not a valid submission):\n')[1].split('\n')[0]); - expect(template).toMatchObject({ kind: 'plan', dispatchNonce: nonce(action), baseVersion: action.planVersion, upsert: [], + expect(template).toMatchObject({ baseVersion: action.planVersion, upsert: [], researchDecisions: [{ deliveryId: 'current-research-finding' }] }); expect(template).not.toHaveProperty('file'); expect(state.cooperation!.researchDecisions).toBeUndefined(); expect(state.cooperation!.planPublication).toBeUndefined(); - await publish(action, { ...template, upsert: [helper], researchDecisions: [{ deliveryId: 'current-research-finding', + await submitDraft(action, { ...template, upsert: [helper], researchDecisions: [{ deliveryId: 'current-research-finding', outcome: 'adopt', taskIds: [helper.id], reason: 'This exact helper closes the consumer obligation.' }] }); expect(notify).toHaveBeenCalledOnce(); expect(rejected()).toHaveLength(1); @@ -404,7 +404,7 @@ describe('live Lead publication correction feedback', () => { for (const id of ['plan-publication-rejection', 'context-checkpoint-rejection']) expect(compiled.manifest!.included).toContainEqual(expect.objectContaining({ id, required: true })); for (const message of [compiled.message, compiled.continuationMessage!]) { - for (const detail of [requestId, rejection!.reason, log(action), 'notesDigest', '"kind":"checkpoint"', planRejection!.reason]) + for (const detail of [requestId, rejection!.reason, log(action), '--request-id', '--log', planRejection!.reason]) expect(message).toContain(detail); } await publish(action, checkpoint(requestId, true)); diff --git a/tests/solverStagnationRecovery.test.ts b/tests/solverStagnationRecovery.test.ts index 9c14aedc..8d6aacc9 100644 --- a/tests/solverStagnationRecovery.test.ts +++ b/tests/solverStagnationRecovery.test.ts @@ -135,7 +135,7 @@ describe('durable checkpoint before context rotation', () => { expect(events).toContainEqual({ event: 'context_rotation_deferred', details: { workerId: 'researcher', threadId: 'checkpoint-thread-1', reason: 'checkpoint-not-published', lastInputTokens: 100_000 } }); expect(held.messages[1]).toMatch(/RESEARCH\.md/u); - expect(held.messages[1]).toMatch(/needsDecision/u); + expect(held.messages[1]).toMatch(/research-observe/u); expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); expect(state.cooperation!.tasks.find(node => node.task.id === 'investigate')?.proof).toBeUndefined(); held.finish.resolve('checkpoint'); await expect(completion).resolves.toBeUndefined(); @@ -184,7 +184,7 @@ describe('durable checkpoint before context rotation', () => { expect(held.executedThreads).toEqual(['checkpoint-thread-1', 'checkpoint-thread-1']); expect(events.filter(item => item.event === 'context_restarted')).toEqual([]); expect(held.messages[1]).toMatch(/RESEARCH\.md/u); - expect(held.messages[1]).toMatch(/needsDecision/u); + expect(held.messages[1]).toMatch(/research-observe/u); expect(state.workers![1].previousThreadIds ?? []).toEqual([]); expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); held.finish.resolve('checkpoint'); await expect(completion).resolves.toBeUndefined(); @@ -254,7 +254,7 @@ describe('durable checkpoint before context rotation', () => { expect(open.mock.calls.at(-1)![0].threadId).toBe('deduplicated-thread'); expect(events.filter(item => item.event === 'context_checkpoint_requested')).toHaveLength(1); expect(events.filter(item => item.event === 'context_restarted')).toEqual([]); - expect(messages.slice(1).every(message => /RESEARCH\.md/u.test(message) && /needsDecision/u.test(message))).toBe(true); + expect(messages.slice(1).every(message => /RESEARCH\.md/u.test(message) && /research-observe/u.test(message))).toBe(true); expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); done[2].resolve('checkpoint'); await expect(completion).resolves.toBeUndefined(); }); @@ -309,7 +309,7 @@ describe('durable checkpoint before context rotation', () => { }]); expect(notify).toHaveBeenCalledOnce(); expect(notify.mock.calls[0][0]).toMatch(/RESEARCH\.md/u); - expect(notify.mock.calls[0][0]).toMatch(/needsDecision/u); + expect(notify.mock.calls[0][0]).toMatch(/research-observe/u); inputTokens = 105_000; activity!({ event: 'reasoning' }); await Promise.resolve(); expect(notify).toHaveBeenCalledOnce(); expect(interrupt).not.toHaveBeenCalled(); diff --git a/tests/solverStaleFailure.test.ts b/tests/solverStaleFailure.test.ts index 873eea67..5601a492 100644 --- a/tests/solverStaleFailure.test.ts +++ b/tests/solverStaleFailure.test.ts @@ -148,20 +148,27 @@ describe('failed turns superseded while their session closes', () => { deadline: Infinity, maxTurns: 1, maxTurnMs: Infinity, maxTotalTokens: 0, save: () => {}, emit: (event, details) => events.push({ event, details }), }); - const currentReviewFailure = kind === 'review' && change === 'pause'; - if (currentReviewFailure) await expect(result).rejects.toThrow('math_original_declaration_changed'); - else await expect(result).resolves.toBeUndefined(); + const reviewRemainsCurrent = kind === 'review' && change === 'pause'; + await expect(result).resolves.toBeUndefined(); expect(edited).toBe(true); expect(state.cooperation!.tasks.every(node => node.status === 'pending' && !node.feedback)).toBe(true); const failures = state.cooperation!.deliveries?.filter(delivery => delivery.kind === 'failure') ?? []; - if (currentReviewFailure) { - expect(failures).toHaveLength(1); + const sourceRejections = events.filter(event => event.event === 'source_rejected'); + if (reviewRemainsCurrent) { + // Pausing only changes scheduling. Reject the review's invalid edit and leave the run resumable. + expect(state.cooperation!.tasks.find(node => node.task.id === target.id)?.task.status).toBe('paused'); + const reason = expect.stringContaining('math_original_declaration_changed'); + expect(failures).toMatchObject([{ status: 'failed', summary: reason }]); expect(state.cooperation!.review).toMatchObject({ status: 'changes_requested', - summary: expect.stringContaining('math_original_declaration_changed') }); - } else expect(failures).toEqual([]); - expect(events.some(event => event.event === 'assignment_superseded')).toBe(!currentReviewFailure); - if (kind === 'review' && !currentReviewFailure) expect(state.cooperation!.deliveries).toContainEqual( + commit: problem.baseCommit, sourceDigest: baseDigest(), summary: reason }); + expect(sourceRejections).toMatchObject([{ details: { reason } }]); + } else { + expect(failures).toEqual([]); + expect(sourceRejections).toEqual([]); + } + expect(events.some(event => event.event === 'assignment_superseded')).toBe(!reviewRemainsCurrent); + if (kind === 'review' && !reviewRemainsCurrent) expect(state.cooperation!.deliveries).toContainEqual( expect.objectContaining({ kind: 'review', status: 'superseded', commit: problem.baseCommit })); expect(retry).not.toHaveBeenCalled(); expect(close).toHaveBeenCalledOnce(); diff --git a/tests/solverWorkerCheckpointFeedback.test.ts b/tests/solverWorkerCheckpointFeedback.test.ts index 791bce8c..9990acfc 100644 --- a/tests/solverWorkerCheckpointFeedback.test.ts +++ b/tests/solverWorkerCheckpointFeedback.test.ts @@ -55,9 +55,9 @@ describe('task worker checkpoint correction feedback', () => { { root: directory, worktree: worker.worktree, retrievalRoot: directory, environment: {}, taskText: 'Resolve the exact assigned mathematical question.', assignment: action, maxOptionalContextBytes: 0 }); const expectCorrection = (message: string, worker: ResearchWorker, action: Task, notification = true) => { - for (const detail of [research(worker).contextCheckpoint!.requestId!, log(action), 'notesDigest', '"kind":"checkpoint"']) + for (const detail of [research(worker).contextCheckpoint!.requestId!, log(action), '--request-id', '--log']) expect(message).toContain(detail); - expect(message).toMatch(/append/iu); + expect(message).toContain('rerun checkpoint'); if (notification) { expect(message).not.toContain('replacesReceipt'); expect(message).not.toContain('dispatchNonce'); @@ -256,7 +256,7 @@ describe('task worker checkpoint correction feedback', () => { expect(currentNotice).toHaveBeenCalledOnce(); expectCorrection(currentNotice.mock.calls[0][0], worker, currentAction); for (const message of [context(worker, currentAction).message, context(worker, currentAction).continuationMessage!]) - expect(message).toContain('Append one complete corrected JSON line to ' + log(currentAction)); + expect(message).toContain('--log ' + log(currentAction)); await publish(worker, currentAction, checkpoint(worker, true)); expect(checkpointRequest.rejection).toBeUndefined(); expect(checkpointRequest.publishedNotesDigest).toBe(checkpoint(worker, true).notesDigest); diff --git a/tests/theoryModules.test.ts b/tests/theoryModules.test.ts index a100574c..482c7c48 100644 --- a/tests/theoryModules.test.ts +++ b/tests/theoryModules.test.ts @@ -126,7 +126,7 @@ describe('theory module guidance in research prompts', () => { it('collapses theory modules, offers them as proof paths and asks for definition sanity lemmas', () => { const owned = ['Submission.lean', ...modules, ...certificateSlotFiles(2)].toSorted(); const lead = build(fixture(owned)); - expect(lead).toContain('Edit only /proof/RESEARCH.md.'); + expect(lead).toContain('Edit only /proof/RESEARCH.md, /proof/.scratch/plan.json.'); expect(lead).toContain('Leave all Lean source files, imports and environment configuration unchanged.'); const worker = build(fixture(owned), lemma); expect(worker).toContain('Edit only /proof/Submission.lean, the 3 theory modules /proof/Submission/Theory/T01.lean … ' + @@ -137,7 +137,6 @@ describe('theory module guidance in research prompts', () => { expect(worker).toContain('Submission/Theory/T01.lean … Submission/Theory/T03.lean are owned theory-library modules'); expect(worker).toContain('a theorem named Foo.bar there is Submission.Theory.Foo.bar'); expect(lead).toContain('Pair each definition with a typed sanity lemma'); - expect(worker).toContain(`Its keys must be exactly ${JSON.stringify(owned)}`); const plain = build(fixture(['Submission.lean'])); expect(plain).toContain('Choose proofPath from ["Submission.lean"]; goals infer'); diff --git a/tests/webModuleIdentity.test.ts b/tests/webModuleIdentity.test.ts index 18843d68..e4d179f5 100644 --- a/tests/webModuleIdentity.test.ts +++ b/tests/webModuleIdentity.test.ts @@ -16,12 +16,12 @@ describe('one frozen identity for executable research modules and the optional w it('pins the method digests for both executable modules and shared identity functions', () => { // These digests include the module versions for final review and research handoffs. const original: [ResearchModulePlan['scheduler'], ResearchModulePlan['context'], string][] = [ - ['plan', 'full', '21fc6be379970092aff994a851cb58205449b5ba9e4dda358184463b0c16a2c6'], - ['plan', 'essential', '478c4f19065692fd55d226b2e2368bc85f669f5580ffd4008cffa101293d0843'], - ['critical-path', 'full', 'bdc715b53f5fffa4d606170f9020fd232f5e6eeb7c42943260908b2985d3c075'], - ['critical-path', 'essential', 'b7eb54e73acd05a12441b9cfafde14e68cb5008e89cfaf95f7db077e1918dc6e'], - ['continuation', 'full', '31df4a061f0659a4e786c1e0665253576c61a2d428e2464bb0474b3e55e613fc'], - ['continuation', 'essential', '01e21dbb7fe4e08273a119086eb99fa67240e9719bd4a63f42e03e8e4dd371dd'], + ['plan', 'full', '3a13f06557273451d404a55d577b91950370f4fc4382094903cbe39aa8de8c9a'], + ['plan', 'essential', 'dd421930f1956a64fc43b82b8c93caec63167a9d2ca520ddd3c053284d104715'], + ['critical-path', 'full', '52efdc4399312deadc2bf540aa4e06ce83f76cdfc0a1cbc611513cc385c04814'], + ['critical-path', 'essential', '8dd6d1453840acf9f77ca2e4bd800f2e9abc7fb272cd846c063bf51ec2e4fcff'], + ['continuation', 'full', 'd8b7b8e2720ac897bb6a266345bce9b6db16e2ad7d1b7ceff607fc6033aa7e00'], + ['continuation', 'essential', '2b3f0dfb1abad52360d1b167f1fb598a96f1be29c7faf741f65caab2cfd052cb'], ]; for (const [scheduler, context, digest] of original) { const plan = { scheduler, context, custom: [] }; @@ -29,10 +29,10 @@ describe('one frozen identity for executable research modules and the optional w expect(solverIdentityMethodDigest(configuredResearchModuleIdentity(plan).identity, 'cooperative')).toBe(digest); } const advised: ['cooperative' | 'independent', number, string][] = [ - ['cooperative', 1, 'ab420dc942068047a7985e8e1fb42e2e5b56f854c7172e6ad57ba84ff1869d96'], - ['cooperative', 4, 'c98d52416c3252a1aee24ce65ca28cafb63e077862fd3212caafe226918cc36a'], - ['independent', 1, '83d8708d1b164f45dee5ebc83c847867cc46637427bb058df60508333676fb25'], - ['independent', 4, '83d8708d1b164f45dee5ebc83c847867cc46637427bb058df60508333676fb25'], + ['cooperative', 1, '743afc2c24dab56ee088ff6d0c4ecac49bf3c28feb3cc2e75539711167282d0b'], + ['cooperative', 4, '3c0a4d4d40f2b9596c72d1f7b976e866c23b86dfffb6a5a967d7d53bb03b2f62'], + ['independent', 1, '3398b370d5cc7a05566eca9f9ba39deaba425d658845688b32c9d21f0d9229df'], + ['independent', 4, '3398b370d5cc7a05566eca9f9ba39deaba425d658845688b32c9d21f0d9229df'], ]; for (const [coordination, workers, digest] of advised) { const plan: ResearchModulePlan = { scheduler: 'continuation', context: 'essential', custom }; diff --git a/tests/webWorkerBridge.test.ts b/tests/webWorkerBridge.test.ts index 16ae8389..b3ef26dd 100644 --- a/tests/webWorkerBridge.test.ts +++ b/tests/webWorkerBridge.test.ts @@ -409,7 +409,7 @@ describe('isolated Web worker bridge', () => { await expect(handleWebWorkerCommand({ type: 'edit', proposal: { ...proposal, id: 'stale', baseVersion: 'stale' } }, options)).rejects.toThrow('version_conflict'); }); - it.each(['edit-preview', 'edit'] as const)('rejects an unowned proofPath in %s with its proposal id and repair details before opening the queue', async type => { + it.each(['edit-preview', 'edit'] as const)('rejects an unowned proofPath in %s with its proposal id and repair details without appending', async type => { const f = fixture(), before = fs.readFileSync(f.stateFile); const proposal = { ...exportRunPlan(f.state), id: 'invalid-proof-path' }; proposal.tasks = proposal.tasks.map(task => task.id === 'goal' ? { ...task, proofPath: 'generated/problem/Submission.lean' } : task); @@ -421,16 +421,27 @@ describe('isolated Web worker bridge', () => { expect(result.reason).toContain('Use an owned proofPath'); expect(fs.readFileSync(f.stateFile)).toEqual(before); expect(fs.existsSync(path.join(path.dirname(f.stateFile), 'edits.jsonl'))).toBe(false); - expect(fs.existsSync(path.join(path.dirname(f.stateFile), 'edits.lock'))).toBe(false); }); - it('keeps malformed edit queue persistence distinct from a rejected proposal', async () => { + it('rejects an unavailable preferred owner during both preview and submission', async () => { + const f = fixture(), before = fs.readFileSync(f.stateFile), options = { activeRunFile: f.activeRunFile }; + const proposal = { ...exportRunPlan(f.state), id: 'missing-preferred-owner' }; + proposal.tasks = proposal.tasks.map(task => task.id === 'goal' ? { ...task, preferredOwnerId: 'missing-worker' } : task); + const rejected = { id: proposal.id, status: 'rejected', baseVersion: proposal.baseVersion, reason: 'math_plan_task_owner_unavailable' }; + expect(await handleWebWorkerCommand({ type: 'edit-preview', proposal }, options)).toEqual(rejected); + expect(await handleWebWorkerCommand({ type: 'edit', proposal }, options)).toEqual(rejected); + expect(fs.readFileSync(f.stateFile)).toEqual(before); + expect(fs.existsSync(path.join(path.dirname(f.stateFile), 'edits.jsonl'))).toBe(false); + }); + + it('keeps an incomplete edit queue distinct from a rejected proposal', async () => { const f = fixture(), before = fs.readFileSync(f.stateFile); const proposal = { ...exportRunPlan(f.state), id: 'valid-proposal' }; - const log = path.join(path.dirname(f.stateFile), 'edits.jsonl'), damaged = '{invalid-json}\n'; - fs.writeFileSync(log, damaged); - await expect(handleWebWorkerCommand({ type: 'edit', proposal }, { activeRunFile: f.activeRunFile })).rejects.toThrow(SyntaxError); - expect(fs.readFileSync(log, 'utf8')).toBe(damaged); + const log = path.join(path.dirname(f.stateFile), 'edits.jsonl'), partial = '{"id":'; + fs.writeFileSync(log, partial); + await expect(handleWebWorkerCommand({ type: 'edit', proposal }, { activeRunFile: f.activeRunFile })) + .rejects.toThrow('math_edit_incomplete_log'); + expect(fs.readFileSync(log, 'utf8')).toBe(partial); expect(fs.readFileSync(f.stateFile)).toEqual(before); }); @@ -568,6 +579,32 @@ describe('isolated Web worker bridge', () => { expect(fs.readFileSync(log, 'utf8').split('\n').filter(Boolean)).toHaveLength(1); }); + it('queues approvals past malformed records and counts only valid requests toward the limit', async () => { + const f = fixture(), options = { activeRunFile: f.activeRunFile }; + const planVersion = 'plan-v1'; + const approval = (id: string) => ({ type: 'plan-approval', approval: { id, planVersion } }); + const log = path.join(path.dirname(f.stateFile), 'plan-approvals.jsonl'); + f.state.planApproval = true; f.save(); + const damaged = '{broken\n'.repeat(64) + 'null\n' + + JSON.stringify({ ...approval('owner').approval, unexpected: true }) + '\n'; + fs.writeFileSync(log, damaged); + + expect(await handleWebWorkerCommand(approval('owner'), options)).toMatchObject({ status: 'queued' }); + expect(await handleWebWorkerCommand(approval('owner'), options)).toMatchObject({ status: 'already_queued' }); + expect(fs.readFileSync(log, 'utf8')).toBe(damaged + JSON.stringify(approval('owner').approval) + '\n'); + + fs.appendFileSync(log, Array.from({ length: 63 }, (_, index) => JSON.stringify(approval(`previous-${index}`).approval) + '\n').join('')); + expect(await handleWebWorkerCommand(approval('over-limit'), options)).toMatchObject({ status: 'rejected', + reason: 'math_plan_approval_limit' }); + expect(await handleWebWorkerCommand(approval('previous-62'), options)).toMatchObject({ status: 'already_queued' }); + + fs.appendFileSync(log, '{"id":'); + const partial = fs.readFileSync(log); + await expect(handleWebWorkerCommand(approval('owner'), options)).rejects.toThrow('math_plan_approval_incomplete_log'); + await expect(handleWebWorkerCommand(approval('new'), options)).rejects.toThrow('math_plan_approval_incomplete_log'); + expect(fs.readFileSync(log)).toEqual(partial); + }); + it('reports unavailable sources as partial and retains recorded checks without accepting them', async () => { const f = fixture(), messages: WorkerMessage[] = []; f.state.problem = { ...f.state.problem, ownedFiles: ['Submission.lean', '../private.lean'] }; f.save(); diff --git a/tests/workerDeliveryRecovery.test.ts b/tests/workerDeliveryRecovery.test.ts index 019cfe1a..07598a14 100644 --- a/tests/workerDeliveryRecovery.test.ts +++ b/tests/workerDeliveryRecovery.test.ts @@ -3,9 +3,10 @@ import os from 'node:os'; import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { CooperativeResearch } from '../src/solver/cooperation'; -import { MAX_DELIVERY_LINE_BYTES, readDeliveryLines, type DeliveryRecord } from '../src/solver/deliveries'; +import { MAX_DELIVERY_LINE_BYTES, type DeliveryRecord } from '../src/solver/deliveries'; import { git } from '../src/solver/problem'; import { assignmentDeliveryFile, taskVersion, type CooperativeAction, type CooperativeTask } from '../src/solver/tasks'; +import { deferred } from './helpers/async'; describe('worker delivery log recovery', () => { let directory: string, commit: string, cooperative: any, controller: AbortController; @@ -165,6 +166,33 @@ describe('worker delivery log recovery', () => { expect(records.map(record => record.summary)).toEqual(['Keep this progress while retrying the reminder.']); }); + it('lets a replacement session receive a correction while the previous notice is still pending', async () => { + fs.appendFileSync(path.join(directory, log()), '{broken\n'); + const previous = deferred(), current = deferred(); + const oldNotify = vi.fn(() => previous.promise), newNotify = vi.fn(() => current.promise); + cooperative.active = new Map([['peer', { action, notify: oldNotify }]]); + try { + await poll(); + expect(oldNotify).toHaveBeenCalledOnce(); + cooperative.active.set('peer', { action, notify: newNotify }); + await poll(); await poll(); + expect(newNotify).toHaveBeenCalledOnce(); + const receipt = cooperative.archive.deliveryReceipts[0]; + expect(newNotify.mock.calls[0]).toEqual([expect.stringContaining(receipt.id)]); + + const oldNotice = [...cooperative.notifications][0]; + previous.reject(new Error('previous session closed')); + await oldNotice; + await poll(); + expect(newNotify).toHaveBeenCalledOnce(); + expect(cooperative.archive.deliveryReceipts).toHaveLength(1); + expect(events.filter(event => event.event === 'delivery_rejected')).toHaveLength(1); + } finally { + previous.resolve(); current.resolve(); + await Promise.allSettled([...cooperative.notifications]); + } + }); + it('rejects a commit outside the frozen problem history once without blocking following progress', async () => { const tree = git(directory, ['rev-parse', `${commit}^{tree}`]); const unrelated = git(directory, ['-c', 'user.name=Fixture', '-c', 'user.email=fixture@localhost', @@ -239,8 +267,4 @@ describe('worker delivery log recovery', () => { expect(cursors[`${key()}/discardingOversized`]).toBe(0); }); - it('keeps the existing strict line reader behavior for callers without recovery state', () => { - const file = path.join(directory, log()); fs.writeFileSync(file, 'x'.repeat(MAX_DELIVERY_LINE_BYTES + 1)); - expect(() => readDeliveryLines(file, 0)).toThrow('math_delivery_line_too_large'); - }); }); diff --git a/tests/workerRecovery.test.ts b/tests/workerRecovery.test.ts index b8da6a0a..645a67f6 100644 --- a/tests/workerRecovery.test.ts +++ b/tests/workerRecovery.test.ts @@ -70,14 +70,16 @@ describe('bounded role session recovery', () => { return { advance: (milliseconds: number) => { now += milliseconds; }, current: () => now }; }; const claim = { id: 'claim', kind: 'goal', objective: 'Prove the original claim', theoremName: 'Submission.claim' }; + const finalAudit = { id: 'candidate_audit', kind: 'research', objective: 'Audit the fixed candidate', reviewScope: 'final-candidate' }; const research = (options: MathAgentOptions, value: object) => fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), JSON.stringify(value)); /** Runs two cooperative workers, recording the assignment each worktree receives. */ const cooperate = (assignments: Map) => runSolver([...args, '--workers', '2'], directory, - { ...directSolverModules, M1: { ...directSolverModules.M1, execute: async (...input) => { - assignments.set(input[3].worktree, input[1].assignment!); - return directSolverModules.M1.execute(...input); - } } }); + { ...directSolverModules, + M1: { ...directSolverModules.M1, execute: async (...input) => { + assignments.set(input[3].worktree, input[1].assignment!); + return directSolverModules.M1.execute(...input); + } } }); beforeEach(() => { vi.clearAllMocks(); @@ -236,8 +238,7 @@ describe('bounded role session recovery', () => { expect(options.threadId).toBe(failedThread); expect(fs.readFileSync(proof(options), 'utf8')).toBe(original); fs.writeFileSync(proof(options), completed); - } else if (action.kind === 'review') research(options, { commit: action.seedCommit, verdict: 'accepted' }); - else throw new Error(`unexpected recovery action: ${action.kind}`); + } else throw new Error(`unexpected recovery action: ${action.kind}`); return 'completed'; }, 'upstream request failed: completed turn had no assistant output or tool operation'); return { ...current, get lastFailureDiagnostic() { return diagnostic; } }; @@ -256,7 +257,7 @@ describe('bounded role session recovery', () => { worker.lastFailure?.reason === 'math_model_request_failed' && worker.lastFailure.diagnostic?.reason === 'upstream_request_failed')).toBe(true); expect(state().cooperation.tasks[0].status).toBe('integrated'); - expect(state().cooperation.review.status).toBe('accepted'); + expect(state().cooperation.review).toBeUndefined(); expect(host.official).toHaveBeenCalledOnce(); }); @@ -531,7 +532,6 @@ describe('bounded role session recovery', () => { const action = assignments.get(options.workspace)!; if (action.kind === 'lead') research(options, { tasks: [{ ...claim, ownerId: 'engineer' }] }); else if (action.kind === 'task') fs.writeFileSync(proof(options), completed); - else if (action.kind === 'review') research(options, { commit: action.seedCommit, verdict: 'accepted' }); else throw new Error(`unexpected recovery action: ${action.kind}`); return 'completed'; }); @@ -542,7 +542,7 @@ describe('bounded role session recovery', () => { }); expect(state().workers.every((worker: { error?: string }) => !worker.error)).toBe(true); expect(state().cooperation.tasks[0].status).toBe('integrated'); - expect(state().cooperation.review.status).toBe('accepted'); + expect(state().cooperation.review).toBeUndefined(); expect(events().filter(event => event.event === 'worker_failed')).toHaveLength(0); expect(events().filter(event => event.event === 'worker_cooling_down')).toEqual([ expect.objectContaining({ workerId, cycle: 1, delayMs: 60_000 }), @@ -601,7 +601,7 @@ describe('bounded role session recovery', () => { let proofTurns = 0; host.open.mockImplementation(async (options: MathAgentOptions) => session(options, async () => { const action = assignments.get(options.workspace)!; - if (action.kind === 'lead') research(options, { tasks: [claim] }); + if (action.kind === 'lead') research(options, { tasks: [claim, finalAudit] }); else if (action.kind === 'task') { proofTurns++; fs.writeFileSync(proof(options), completed); options.onUsage({ totalTokens: 11 }); return 'failed'; @@ -630,24 +630,23 @@ describe('bounded role session recovery', () => { fs.writeFileSync(proof(options), proofTurns <= 3 ? draft : draft.replace('by sorry', 'by exact checkpoint_3')); options.onUsage({ totalTokens: 11 }); return proofTurns <= 3 ? 'checkpoint' : 'completed'; - } else if (action.kind === 'review') research(options, { commit: action.seedCommit, verdict: 'accepted' }); - else throw new Error(`unexpected checkpoint action: ${action.kind}`); + } else throw new Error(`unexpected checkpoint action: ${action.kind}`); options.onUsage({ totalTokens: 8 }); return 'completed'; })); expect(await cooperate(assignments)).toBe(0); expect(proofTurns).toBe(4); expect(events().filter(event => event.event === 'turn_checkpoint')).toHaveLength(3); expect(state().cooperation.tasks[0].status).toBe('integrated'); - expect(state().cooperation.review.status).toBe('accepted'); + expect(state().cooperation.review).toBeUndefined(); expect(host.delay).not.toHaveBeenCalled(); expect(host.official).toHaveBeenCalledOnce(); }); - it('checks and integrates a saved proof once after a tool failure, then keeps the peer available for independent review', async () => { + it('checks and integrates a saved proof once after a tool failure, then keeps the peer available for an explicit review', async () => { const assignments = new Map(); let proofTurns = 0; host.open.mockImplementation(async (options: MathAgentOptions) => session(options, async () => { const action = assignments.get(options.workspace)!; - if (action.kind === 'lead') research(options, { tasks: [claim] }); + if (action.kind === 'lead') research(options, { tasks: [claim, finalAudit] }); else if (action.kind === 'task') { proofTurns++; fs.writeFileSync(proof(options), completed); options.onUsage({ totalTokens: 11 });