From b6ad8d62164f0e753f62f063b90b8dccd60ad2a8 Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <3100378030@qq.com> Date: Fri, 27 Nov 2026 01:37:35 +0800 Subject: [PATCH] Fix Codex compaction and long session recovery --- docs/codex-skill-runtime.md | 38 ++++++++++---------- docs/harness-portability.md | 2 +- docs/usage.md | 20 +++++------ scripts/codex-backend/README.md | 13 +++++-- src/runtime/codexSession.ts | 24 ++++++------- tests/codexSession.test.ts | 12 +++++++ tests/nativeDelegation.test.ts | 61 +++++++++++++++++++++++++++------ 7 files changed, 114 insertions(+), 56 deletions(-) diff --git a/docs/codex-skill-runtime.md b/docs/codex-skill-runtime.md index 51ec0b74..bcede457 100644 --- a/docs/codex-skill-runtime.md +++ b/docs/codex-skill-runtime.md @@ -16,6 +16,8 @@ New `--research-mode skill` runs default to one independent researcher. Explicit The normal `--resume` command inherits the saved research mode, skill loading, workers and coordination. It continues the saved native thread when the frozen contract permits. Mode, skill content, loading mode, provider, environment and other frozen identities cannot be changed in place. New runs save `researchSkillWorkflow: full` and an execution plan. Historical Skill checkpoints without that marker keep their original single-only workflow; resume does not silently upgrade their strategy. A different strategy starts a new run and thread from saved artifacts. +For Codex sessions metered by upstream request receipts, the host sends `excludeTurns: true` on resume. Codex restores the thread internally and returns metadata without sending the full transcript over stdio. Direct providers whose budget gate uses native thread totals still request turn history so Codex can replay saved usage. + The default `--skill-loading native` checks Codex discovery and sends native skill input on ordinary host turns. `--skill-loading file` explicitly directs Codex to read the same pinned file. Native child communication carries the host's frozen context and explicit pinned-file reading instructions; its execution plan records file loading because Codex's typed input cannot combine an inter-agent communication with a skill input. Discovery and an accepted request do not prove that a provider followed the skill; that requires separate execution evidence. ## Codex adapter boundary @@ -28,17 +30,17 @@ File handoffs use native `fs/watch` on the existing parent directory before the New Codex report workflows prefer native `outputSchema` and the final response bound to the completed turn. The host closes the session, validates the response and saves the frozen output file. `outputDelivery` freezes this choice; older requests without the field retain their file protocol and instruction hashes. Replay, other harnesses, the DeepSeek/Westlake Chat bridge and early proof handoffs retain file delivery. The audit reads the session's final-response record instead of collecting a second copy of agent messages. -The legacy non-Skill research path uses native `thread/compact/start` between settled turns before rotating a thread for context capacity. Its maintenance requests are accounted for separately from proof turns; failed compaction retains the existing fresh-thread recovery. Skill research keeps Codex's own automatic compaction behavior. Ordinary peer-status notices in the legacy cooperative path also use advisory native history; assignment changes and other effective instructions keep their steering contract. +The legacy non-Skill research path uses native `thread/compact/start` between settled turns before rotating a thread for context capacity. The adapter waits for the `contextCompaction` item and the successful terminal event for that turn before it resumes research. Its maintenance requests are accounted for separately from proof turns; failed compaction retains the existing fresh-thread recovery. Skill research keeps Codex's own automatic compaction behavior. Ordinary peer-status notices in the legacy cooperative path also use advisory native history; assignment changes and other effective instructions keep their steering contract. -Historical teams use `thread/inject_items` for ordinary advisory updates and `turn/steer` for effective amendments with the existing paid-request settlement fence. Native teams deliver through Codex's mailbox and attributed input. Queue-only delivery never starts an idle turn; acceptance transfers queue ownership and is not a read receipt. An amendment uses exact-turn steering so a late notification cannot start another writer. Uncertain delivery after worker loss stays explicitly uncertain. +Teams using host tools use `thread/inject_items` for ordinary advisory updates and `turn/steer` for effective amendments with the existing paid-request settlement fence. Native teams deliver through Codex's mailbox and attributed input. Queue-only delivery never starts an idle turn; acceptance transfers queue ownership and is not a read receipt. An amendment uses exact-turn steering so a late notification cannot start another writer. Uncertain delivery after worker loss stays explicitly uncertain. -New team runs use the separately built [Codex AgentControl backend](../scripts/codex-backend/README.md). Official `spawn_agent`, `send_message`, `followup_task`, `list_agents`, `wait_agent` and `interrupt_agent` handlers stay installed. The adapter connects them over stdio to TheoremOS's isolated writer lifecycle. The host prepares a separate process and worktree before the first child model request; trusted bootstrap preserves native tree identity, captured instructions, parent lineage and native fork history. Workspace relocation revokes the parent's writable worktree and permits the destination isolated workspace while retaining other restrictions. Per-worker provider settings stay local to the worker process. +Native team runs use the separately built [Codex AgentControl backend](../scripts/codex-backend/README.md). Official `spawn_agent`, `send_message`, `followup_task`, `list_agents`, `wait_agent` and `interrupt_agent` handlers stay installed. The adapter connects them over stdio to TheoremOS's isolated writer lifecycle. The host prepares a separate process and worktree before the first child model request; trusted bootstrap preserves native tree identity, captured instructions, parent lineage and native fork history. Workspace relocation revokes the parent's writable worktree and permits the destination isolated workspace while retaining other restrictions. Per-worker provider settings stay local to the worker process. Codex's generic root/subagent role messages are deliberately suppressed: their defaults assume a shared working directory and allow recursive child teams. TheoremOS supplies the actual flat-team identities, isolated workspace permissions and native usage guidance through the pinned context instead. This does not remove native tool descriptions. Deferred mailbox preemption preserves delivery at the next model boundary after the current response and tools settle; it does not require a host coordination acknowledgment. -Native team sessions also set Codex's existing `features.multi_agent_v2.multi_agent_mode_hint_text`. Lead receives explicit authorization to proactively delegate useful complementary work; members receive a flat-team policy that permits messages and forbids further dispatch or peer interruption. This replaces the default explicit-request-only mode message emitted at `high` effort, which otherwise follows the host's team authorization. The override is recorded with the runtime configuration and reapplied on new and resumed writer sessions. Single-agent and historical host-tool sessions keep their existing native mode settings. This adds no dispatch gate, required team size or model-choice override. +Native team sessions also set Codex's existing `features.multi_agent_v2.multi_agent_mode_hint_text`. Lead receives explicit authorization to proactively delegate useful complementary work; members receive a flat-team policy that permits messages and forbids further dispatch or peer interruption. This replaces the default explicit-request-only mode message emitted at `high` effort, which otherwise follows the host's team authorization. The override is recorded with the runtime configuration and reapplied on new and resumed writer sessions. Single-agent and host-tool sessions keep their existing native mode settings. This adds no dispatch gate, required team size or model-choice override. -Build the pinned backend before starting a new team run. New runs freeze `agentTeam.transport: native-agent-control`, plus the backend executable's real path and digest. `THEOREMOS_CODEX_BACKEND_EXECUTABLE` can select an explicitly built binary; the default is `out/codex-backend/codex`. Startup checks the backend capability endpoint and rejects a stock or incompatible executable. Saved runs without that transport field keep their original host-tool contract. Building does not switch or restart running solves, and no global Codex profile or binary is replaced. Native completion remains separate from stopped-writer source freezing, Lean verification and Lead adoption. +Build the pinned backend to start a native team. It defaults to `out/codex-backend/codex`. Set `THEOREMOS_CODEX_BACKEND_EXECUTABLE` to select another build. The run pins the executable's real path and digest. New teams using the direct Westlake Chat profile start with host tools. Other new teams start with native collaboration and can switch to `theoremos_team` host tools on eligible app-server startup failures before the Lead starts research. Resume uses the recorded transport. Checkpoints that predate the transport field use host tools. Building does not switch or restart running solves, and no global Codex profile or binary is replaced. The host confirms writer shutdown before freezing sources, checking them in Lean and making them available for Lead adoption. See the [backend startup and fallback rules](../scripts/codex-backend/README.md). The backend's real-binary [loopback fixture](../scripts/test-codex-backend.ts) covers isolated native spawn, attributed messages, idle queues, cold resume with first-request FIFO mail, full-history fork, loaded-agent listing, mailbox wakeup, changes to a running member's expertise and idle/active interruption. It verifies writer shutdown, checked delivery, adoption and final proof references. Provider responses are fixed local data. Installing the CLI backend does not upgrade an existing Web worker image. @@ -71,11 +73,11 @@ Lead and member contexts report remaining run milliseconds, the stage checkpoint Team identity is stable: Lead owns the original problem and may also write proofs; each child is a mathematical researcher and Lean proof writer. The pinned Skill's [specialist profiles](../skills/theoremos-research/references/domain-experts.md) supply specialized knowledge: concepts and structures, relevant theories with their conditions, important distinctions and connections to neighboring subjects. Each member chooses its reasoning and proof approach for the assigned question. The catalog contains 100 domain profiles and 24 work or supporting-expertise profiles; these can be combined and are separate from the runtime's agent capacity. Lead provides the question and members read the relevant knowledge sections. The [work profiles](../skills/theoremos-research/references/team-roles.md), including Researcher, Lean Prover, Lean Engineer and Reviewer, describe responsibilities that can accompany a specialization. Lead selects, combines or changes expertise and responsibilities in native spawn and followup messages; no separate `role` or `domain` parameter or host authority is added. Independent review requires a non-producing member and fixed evidence; a role change alone does not make the producing thread independent. This is a Skill collaboration requirement, not an additional host review gate. The host refreshes developer identity and source permissions, while the pinned Skill supplies domain knowledge and collaboration guidance. Each child dispatch starts with a bounded current-assignment section containing its task ID, objective, source and delivery baselines, own prior feedback, peer work and addressed inbox. The inbox cursor advances only after turn-start acknowledgment. See the [source research and prompt design](../research/agent-team-prompts.md). -Start a specialized native `spawn_agent` or `followup_task` message with `Profiles:` followed by comma-separated domain and work-profile IDs or slugs selected for the actual gap. A work profile alone is valid; no domain is selected by default. The child receives the selected profile text and the locations of local reading notes; it can read those notes on demand. When Lead changes the expertise of a running member, the same attributed followup delivers the new profile context to the current turn. The host records the change after the native backend accepts the input; acceptance does not establish that the model used the material. The record includes the pinned Skill digest, requested and loaded IDs, and unresolved names. Historical host-tool runs use the same opening line in `spawn.message` or `assign.message`. Source permissions, agent capacity and proof acceptance do not change. +Start a specialized native `spawn_agent` or `followup_task` message with `Profiles:` followed by comma-separated domain and work-profile IDs or slugs selected for the actual gap. A work profile alone is valid; no domain is selected by default. The child receives the selected profile text and the locations of local reading notes; it can read those notes on demand. When Lead changes the expertise of a running member, the same attributed followup delivers the new profile context to the current turn. The host records the change after the native backend accepts the input; acceptance does not establish that the model used the material. The record includes the pinned Skill digest, requested and loaded IDs, and unresolved names. Teams using host tools use the same opening line in `spawn.message` or `assign.message`. Source permissions, agent capacity and proof acceptance do not change. The Lead charter assigns concrete gaps with a consumer and first usable result, with one owner per active obligation including Lead. While a member owns a gap, Lead advances its consumer or other work; different methods for proving the same target still overlap. Whole-target delegation has one owner while others provide targeted support, integration or review. Alternative routes start with the smallest finding that resolves a specific uncertainty. Members receive the original problem as background to their current assignment and send useful intermediate findings before the complete proof. These are Skill and native role instructions, without a host scheduler or delegation gate. -Native followup retains the member's workspace, thread and draft while the adapter records the latest accepted task instructions and retains earlier instructions in history. It preserves the current profile selection when the message has no new `Profiles:` header, and switches knowledge when an explicit header is supplied. Native submit omits `objectiveRevision`; the host binds the member's current task. Profile records retain exact loaded passage identities; a member can explain a passage's application in its messages or saved research notes. Supplied context, reported knowledge use and checked proof evidence remain distinct. Historical host-tools retain `amend` and optional structured `progress` records, including their objective revisions, work kinds and source-anchor reports, for compatibility. +Native followup retains the member's workspace, thread and draft while the adapter records the latest accepted task instructions and retains earlier instructions in history. It preserves the current profile selection when the message has no new `Profiles:` header, and switches knowledge when an explicit header is supplied. Native submit omits `objectiveRevision`; the host binds the member's current task. Profile records retain exact loaded passage identities; a member can explain a passage's application in its messages or saved research notes. Supplied context, reported knowledge use and checked proof evidence remain distinct. Host tools provide `amend` and optional structured `progress` records, including their objective revisions, work kinds and source-anchor reports. Members use independent Git object stores; each writer's namespace hides the peer-workspace parent and rebinds only its own workspace. Checked fixed commits and evidence are archived outside writer visibility and imported by exact version for explicit adoption. `inspect` records exposure to a peer delivery, and completed adoption records reuse. These records persist across tasks and accompany later deliveries with the source producer, task and commit. They record explicit source transfers, not complete reasoning independence or independent authorship of reused declarations. @@ -89,35 +91,35 @@ The native transport leaves identity, dispatch, instructions, messaging, waiting 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. -Historical `coordinate` and `publish` remain optional note and summary operations. Saved coordination decisions, observations and presentations remain readable historical records; they do not gate tools, create collaboration stages or schedule turn handoffs. +The host-tool operations `coordinate` and `publish` provide optional notes and summaries. Saved coordination decisions, observations and presentations remain readable historical records; they do not gate tools, create collaboration stages or schedule turn handoffs. -The historical `message(agentId, message, relatedTaskId?, researchRevision?)` durably saves its event before returning. Native notification is queued asynchronously, so a receiver waiting on its own tool call cannot block all team mutations. The reply distinguishes saved inbox delivery from notification availability; neither confirms reading. Child message events automatically carry the sender's current `sourceTaskId` and `dispatchResearchRevision`, the summary version injected at that sender's dispatch. An explicitly referenced `researchRevision` can be newer; the dispatch revision never asserts that later updates have been read. Native transport uses attributed Codex messages and queue-only mailbox updates instead; accepted mail does not establish that it was read. +The host tool `message(agentId, message, relatedTaskId?, researchRevision?)` durably saves its event before returning. Native notification is queued asynchronously, so a receiver waiting on its own tool call cannot block all team mutations. The reply distinguishes saved inbox delivery from notification availability; neither confirms reading. Child message events automatically carry the sender's current `sourceTaskId` and `dispatchResearchRevision`, the summary version injected at that sender's dispatch. An explicitly referenced `researchRevision` can be newer; the dispatch revision never asserts that later updates have been read. Native transport uses attributed Codex messages and queue-only mailbox updates instead; accepted mail does not establish that it was read. -Lead/worker dispatch contexts and historical poll/wait share a bounded [overview projection](../src/solver/agentTeamViews.ts): selected members, each member's current/next/recent tasks, recent research/proof references and current integration status. Long objectives, summaries and errors have previews and truncation markers; omission counts and retrieval instructions identify what is not shown. `activity` distinguishes preparing, running, stopping, checking, integrating, paused and idle without claiming mathematical progress. `history(agentId?, offset?, limit?)` returns complete task text and any saved legacy summary, with source/evidence IDs; declaration arrays remain available through checked delivery inspection. The default page limit is 4, maximum 8, with a 256 KiB soft byte limit ending at whole-task boundaries and `nextOffset` pointing to the first unreturned task. A single large task is still returned. Global history uses host-assigned task sequences, stable as new tasks are appended; a task's `historyOffset` indexes its member's history. +Lead/worker dispatch contexts and host-tool poll/wait share a bounded [overview projection](../src/solver/agentTeamViews.ts): selected members, each member's current/next/recent tasks, recent research/proof references and current integration status. Long objectives, summaries and errors have previews and truncation markers; omission counts and retrieval instructions identify what is not shown. `activity` distinguishes preparing, running, stopping, checking, integrating, paused and idle without claiming mathematical progress. `history(agentId?, offset?, limit?)` returns complete task text and any saved legacy summary, with source/evidence IDs; declaration arrays remain available through checked delivery inspection. The default page limit is 4, maximum 8, with a 256 KiB soft byte limit ending at whole-task boundaries and `nextOffset` pointing to the first unreturned task. A single large task is still returned. Global history uses host-assigned task sequences, stable as new tasks are appended; a task's `historyOffset` indexes its member's history. -Context inboxes contain at most eight event previews. A truncated message and later previews are not acknowledged: `through` remains the last completely shown prefix, and `previewThrough` is explicitly not a receive cursor. Historical poll/wait return at most eight complete events and can stop earlier at a byte limit; their cursor advances only past returned events. Native messages use Codex's attributed mailbox delivery. Long-lived task history, reference indexes and inbox previews remain bounded, with complete content retrievable. +Context inboxes contain at most eight event previews. A truncated message and later previews are not acknowledged: `through` remains the last completely shown prefix, and `previewThrough` is explicitly not a receive cursor. The host tools `poll` and `wait` return at most eight complete events and can stop earlier at a byte limit; their cursor advances only past returned events. Native messages use Codex's attributed mailbox delivery. Long-lived task history, reference indexes and inbox previews remain bounded, with complete content retrievable. -Historical host-tools retain `publish(summary)`, which updates `researchState` with a new revision and publication time and sends members a `research-updated` event. The saved summary is advisory and may describe routes, assumptions, findings and gaps; it is neither a host task graph nor checked mathematical evidence. Native teams use ordinary native messages for these updates and save reproducible notes in RESEARCH.md. +Host tools provide `publish(summary)`, which updates `researchState` with a new revision and publication time and sends members a `research-updated` event. The saved summary is advisory and may describe routes, assumptions, findings and gaps; it is neither a host task graph nor checked mathematical evidence. Native teams use ordinary native messages for these updates and save reproducible notes in RESEARCH.md. After an executed child task's writer stops, its result records the stable `sourceCommit` and `researchArtifactId`. The artifact contains the task's summary and status, plus the root RESEARCH.md when present; missing notes return `notes:null`. The `researchArtifacts` index exposes artifact ID, producer, task and commit without host storage paths. Any member can use `inspect-research(artifactId, offset?, limit?)` to read paginated saved notes at that fixed commit, using Unicode code point offsets and `nextOffset`. This preserves inspectable counterexamples, literature mappings, calculations and failed routes even when no Lean declaration was submitted. An artifact remains advisory and separate from a checked proof delivery. Historical checkpoints can omit these new fields; the context then has no invented summary or artifact. -Historical host-tools retain `cancel(agentId, taskId, reason?, replacement?)` for withdrawing a task or queuing a replacement, and `stop(agentId)` for retiring a member. A cancellation request and queued replacement do not assert writer shutdown. Native teams use `interrupt_agent` to stop a turn and `followup_task` for further instructions, preserving identity and saved work; a subsequent writer still waits for confirmed shutdown. +Host tools provide `cancel(agentId, taskId, reason?, replacement?)` for withdrawing a task or queuing a replacement, and `stop(agentId)` for retiring a member. A cancellation request and queued replacement do not assert writer shutdown. Native teams use `interrupt_agent` to stop a turn and `followup_task` for further instructions, preserving identity and saved work; a subsequent writer still waits for confirmed shutdown. -For a temporary dependency or Lead decision, a child saves its draft and notes, calls `yield(reason)` and returns. The host confirms writer shutdown before making the task paused. Lead can adopt needed results and use native `followup_task`, or historical `resume(agentId, taskId)`, to continue the task, worktree and native thread. This preserves the original delivery baseline and cumulative task consumption. A normal return still completes the investigation; a submitted proof is checked through the submission path rather than yielding it. +For a temporary dependency or Lead decision, a child saves its draft and notes, calls `yield(reason)` and returns. The host confirms writer shutdown before making the task paused. Lead can adopt needed results and use native `followup_task`, or the host tool `resume(agentId, taskId)`, to continue the task, worktree and native thread. This preserves the original delivery baseline and cumulative task consumption. A normal return still completes the investigation; a submitted proof is checked through the submission path rather than yielding it. Runs have no token, turn or solving-time budget by default. Without a finite host token or turn allowance, Lead cannot invent local task caps or an integration reserve: the tool omits those capabilities and the host rejects budget requests before creating or queuing a task. Usage accounting continues independently of limits. Older saved task caps and reserves are preserved as history and are not enforced while the host has no finite token or turn allowance. Removing a global token limit on resume requires explicit `--max-total-tokens 0`, because omission retains the old run's value. -Native team tools expose no task-budget or reserve controls. Historical host-tools retain 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. +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. -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. Historical host-tool teams retain `message` with `agentId`, their original receipts and deduplication. +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. For native teams, `result.teamContributions` and `inspect` distinguish checked declarations and their adoption from use in each original proof. The report ties a delivered source version to its transfer into Lead's worktree and to final Lean evidence. Where the evidence permits, it distinguishes a delivered target proof, a direct reference, an indirect reference, and a declaration absent from the proof's references. An older receipt may establish a reference without its depth; missing or ambiguous evidence stays unknown. Member messages are separate advisory records, not proof of adoption or mathematical use. For long declarations, `inspect` returns a preview for each source change. Pass the same `deliveryId`, its `changeIndex` and `offset: nextOffset` to read the next page at the fixed commit without adopting it. Native spawn evidence distinguishes a fresh thread, a thread with parent history and an unknown history. A parent's inspection before a full-history fork is recorded as possible exposure through the parent. It is neither a direct read by the child nor proof that the source reached the model after context compaction. -Lead and children share the original run's time, turn and token allowances, with cumulative usage saved in host state. Team writers use Linux bubblewrap isolation with separate PID namespaces; host-controlled process identities allow recovery to confirm previous writers stopped before sources are reused. Native runs use the official collaboration handlers with host-backed isolation; historical host-tool teams keep built-in spawn/fork disabled. Native threads, messages, tasks, delivery identities and adoption progress persist on resume. A previously running assignment becomes interrupted and requires an explicit Lead assignment to continue; pending proof checking and adoption use their saved source identities. An unconfirmed writer stop blocks further use of that workspace. +Lead and children share the original run's time, turn and token allowances, with cumulative usage saved in host state. Team writers use Linux bubblewrap isolation with separate PID namespaces; host-controlled process identities allow recovery to confirm previous writers stopped before sources are reused. Native runs use the official collaboration handlers with host-backed isolation; host-tool teams keep built-in spawn/fork disabled. Native threads, messages, tasks, delivery identities and adoption progress persist on resume. A previously running assignment becomes interrupted and requires an explicit Lead assignment to continue; pending proof checking and adoption use their saved source identities. An unconfirmed writer stop blocks further use of that workspace. Deferred or rejected source drafts keep their original delivery baseline across assignments, so a corrected helper remains transferable. A stopped child can adopt checked peer work while retaining its own unpublished draft. The host merges against fixed commits, preserves the child's draft and baseline, tracks adopted peer declarations and freshly checks the subsequent combined delivery; the child still names all its own unpublished declarations. Each submit remains limited to 32 declarations; larger host-composed sets are checked in batches, with full-set source-delta and duplicate validation. Conflicts and unconfirmed writer shutdown remain explicit failures. Successful deliveries advance the baseline. Lead adoption completion durably records the next source freeze. If the host exits before whole-proof checking, resume verifies a complete adopted original candidate before admitting another model turn, including when the turn allowance is exhausted. @@ -210,7 +212,7 @@ In this separate read-only investigation mode, stock Codex V1 and V2 spawn inher ## Web workflow -Web proof requests can select AgentResearchTeam or host-managed cooperative workers. Use `webAgentTeamPreset(N)` to set the team fields for a Web request, or `math run --agent-team N` on the CLI. Capacity is 2–8 including Lead. Web starts one host Lead and requires a Codex provider and a worker image labeled `org.theoremos.native-agent-control=v1` after its backend passes the image capability check. If native transport startup fails before the Lead starts research, the same team can restart with `theoremos_team` host tools and records the transport change for resume. Existing cooperative requests retain their plan and approval workflow. Browser requests select neither host binaries nor CLI profiles. +Web proof requests can select AgentResearchTeam or host-managed cooperative workers. Use `webAgentTeamPreset(N)` to set the team fields for a Web request, or `math run --agent-team N` on the CLI. Capacity is 2–8 including Lead. Web starts one host Lead and requires a Codex provider and a worker image labeled `org.theoremos.native-agent-control=v1` after its backend passes the image capability check. The same team can retry eligible native startup failures before the Lead starts research using `theoremos_team` host tools. The saved transport is used on resume. Existing cooperative requests retain their plan and approval workflow. Browser requests select neither host binaries nor CLI profiles. The skill view displays the actual researcher and independent declaration source, full type, premises, checked commit, environment and receipt references. Recorded evidence requires a fresh consumer check; it never turns an unfinished original goal into an accepted result. Large declaration collections have an explicit byte allowance and report omitted records. Plan, cooperative guidance and approval actions require actual cooperative execution; single researchers keep their declaration workflow. Capture and archive remain supported. All context builders use the host-projected agent tool bundle, including when Docker hides application source. diff --git a/docs/harness-portability.md b/docs/harness-portability.md index d8da966b..06cf1ee1 100644 --- a/docs/harness-portability.md +++ b/docs/harness-portability.md @@ -13,7 +13,7 @@ CLI research, trusted Web provider configuration, automatic-library proof backen Codex Skill single research can additionally select `--skill-delegation read-only --skill-max-agents 2..4`. A native dynamic tool dispatches independent named read-only threads through the host, with one shared request gate and accounting ledger. This is host-mediated native threading; Codex's built-in V1/V2 spawn remains disabled because both inherit the primary writer's permission. Each investigator is archived before returning advisory findings. Parent shutdown confirms that the owned process group stopped before source freeze. Native permission profiles and dynamic tools require the app-server experimental capability, verified against Codex 0.169.0. Unsupported protocols or permission bindings fail explicitly and stop the owned tree. -Codex also supports `--research-mode skill --skill-delegation team --skill-max-agents 3`, with a total of 2–8 agents including Lead. It uses one host Lead (`workers=1`, `coordination=independent`) and the `theoremos_team` dynamic tool. Lead decides decomposition and adoption; children retain native threads, write Lean in isolated worktrees and communicate or deliver asynchronously. The host checks exact deliveries after writer shutdown and rechecks them during integration. See the [team launch and delivery protocol](codex-skill-runtime.md#agent-organized-proof-writing-team). This bridge is Codex-only; host-cooperative workflows remain available across all four harnesses. Checked team artifacts do not grant whole-problem acceptance. +Codex also supports `--research-mode skill --skill-delegation team --skill-max-agents 3`, with a total of 2–8 agents including Lead. It uses one host Lead (`workers=1`, `coordination=independent`). Native teams use Codex collaboration tools for dispatch and messaging and `theoremos_team` for proof handoffs. Teams using host tools also coordinate through `theoremos_team`. Lead decides decomposition and adoption; children retain native threads, write Lean in isolated worktrees and communicate or deliver asynchronously. The host checks exact deliveries after writer shutdown and rechecks them during integration. See the [team launch and delivery protocol](codex-skill-runtime.md#agent-organized-proof-writing-team). This bridge is Codex-only; host-cooperative workflows remain available across all four harnesses. Checked team artifacts do not grant whole-problem acceptance. ## Launch diff --git a/docs/usage.md b/docs/usage.md index 2ac1b933..3230b138 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -42,7 +42,7 @@ bun run build 构建生成 `out/main/math-solver.js`、`search-lean.js`、`check-lean.js` 和 `proof-search.js`,并输出 JSON。记录其中的 **`buildManifestRef`**,运行时需要传入这个文件的绝对路径。源码与 bundle 均校验哈希,修改运行时代码后需重新构建。 -CLI 默认使用 `~/.config/deepscientist/math-sol-codex` 中的 Codex profile(本地 Sub2API 网关的 `deepseek-flash` / `max`,网关 `http://127.0.0.1:8080/v1`)。本机 profile 的认证命令按需读取已有部署的 Westlake 号池密钥,无需复制密钥或手动 export。也可通过 `CODEX_HOME` 指向其他已有 profile。 +CLI 默认使用 `~/.config/deepscientist/math-sol-codex` 中的 Codex profile,通过本地 Sub2API 网关 `http://127.0.0.1:8080/v1` 调用模型。`run` 的默认模型为 `deepseek-flash`,新运行的默认推理强度为 `high`。本机 profile 的认证命令按需读取已有部署的 Westlake 号池密钥,无需复制密钥或手动 export。也可通过 `CODEX_HOME` 指向其他已有 profile。 `compare --provider sub2api` 和 `sample-putnam` 创建的独立 profile 使用环境变量 `SUB2API_WESTLAKE_API_KEY`;启动这些实验前需要在调用环境中设置它。密钥不会写入实验 profile 或数学工具环境文件。 @@ -101,7 +101,7 @@ bun run math run \ --output "$MATH_RUN_ROOT/result.json" ``` -默认启用四个 Agent,解题预算为 30 分钟、合计 200 次模型调度。运行向标准输出发送 JSON 进度事件,并将结果写入 `result.json`。 +默认启用四个 Agent。CLI 默认不限制解题时间、模型调度次数和 token 用量。需要限制时,可设置 `--max-run-seconds`、`--max-turns` 或 `--max-total-tokens`。Web worker 会传入该次运行的预算。运行向标准输出发送 JSON 进度事件,并将结果写入 `result.json`。 首次配置环境时,可在上述命令末尾加 `--startup-only`,只检查准备条件,不调用模型。预检会创建运行状态;之后使用相同参数加 `--resume` 开始求解。 @@ -346,21 +346,21 @@ Lead 的普通规划和初始规划执行 90 秒后收到保存提醒,120 秒 | 参数 | 默认值 | 作用 | | --- | --- | --- | | `--model` | `deepseek-flash` | 所选 provider 提供的模型 ID | -| `--effort` | `max` | 推理强度(Sub2API DeepSeek 支持 low/high/max) | +| `--effort` | `high` | 推理强度(Sub2API DeepSeek 支持 low/high/max) | | `--workers` | `4` | Agent 总数,支持 1–8;四人以上增加专门的辅助引理 Prover | | `--method` | `direct` | 仅支持 `direct`,保留以兼容已有命令 | | `--coordination` | `cooperative` | 协作,或 `independent` 独立并行尝试 | | `--continuation-manifest` | 无 | 新建时绑定显式历史附件;恢复时沿用同一只读快照 | | `--scheduler` | `plan` | 按计划顺序调度;`critical-path` 按依赖链排序;`continuation` 优先承接已证成果的主路径任务 | -| `--prepare-timeout-seconds` | `1800` | 环境准备与依赖预编译预算 | -| `--max-run-seconds` | `1800` | 准备完成后的共享解题时间预算 | -| `--max-turns` | `200` | 所有 Agent 合计模型调度次数 | +| `--prepare-timeout-seconds` | `0` | 环境准备与依赖预编译预算 | +| `--max-run-seconds` | `0` | 准备完成后的共享解题时间预算 | +| `--max-turns` | `0` | 所有 Agent 合计模型调度次数 | | `--max-total-tokens` | `0` | 全部角色累计的 provider 报告 token 阈值;`0` 不限。达到后停止新模型请求,在途请求仍可完成并产生超额 | -| `--max-turn-seconds` | `180` | 单轮时间限制;停止写入后检查已保存源码 | -| `--proof-timeout-seconds` | `1800` | 单次宿主证明检查预算;超时保存可恢复检查点 | -| `--evaluator-timeout-seconds` | `1800` | 集成后 Lean 复核与最终评测共享的独立时间预算 | +| `--max-turn-seconds` | `0` | 单轮时间限制;停止写入后检查已保存源码 | +| `--proof-timeout-seconds` | `0` | 单次宿主证明检查预算;超时保存可恢复检查点 | +| `--evaluator-timeout-seconds` | `0` | 集成后 Lean 复核与最终评测共享的独立时间预算 | -`--prepare-timeout-seconds`、`--max-run-seconds`、`--max-turns`、`--max-turn-seconds`、`--proof-timeout-seconds` 与 `--evaluator-timeout-seconds` 可设为 `0` 关闭对应限制。证明检查预算独立于总解题时间;关闭总解题时间限制不会关闭证明检查期限。同一源码、任务和环境的检查超时后保留候选,恢复时逐次延长检查时间,最多 24 小时。 +`--prepare-timeout-seconds`、`--max-run-seconds`、`--max-turns`、`--max-turn-seconds`、`--proof-timeout-seconds` 与 `--evaluator-timeout-seconds` 在 CLI 中均默认为 `0`,表示不限。可以分别设置解题、证明检查和最终评测的时限。显式设置证明检查时限后,同一源码、任务和环境的检查超时会保留候选,恢复时逐次延长检查时间,最多 24 小时。 `--max-total-tokens` 包含规划、研究、证明和审阅角色,按跨线程累计消费计算;恢复时继续使用历史用量,省略参数时保留已存额度。它依据 provider 的事后通知阻止新请求,不能保证并发在途消费不超过阈值。报告保留超额与用量完整性;有限额度下缺失已执行请求的用量会停止继续派发。旧运行未记录逐轮用量完整性,不能直接当作严格 token 对照。默认不限 token,不为已有长跑增加停止条件。原生 provider 的用量按完整 turn 记账:turn 被 `--max-turn-seconds` 截断时该轮用量记为不完整,有限额度会以 usage-unavailable 停止;需要有限 token 额度时应同时放宽 `--max-turn-seconds`(或设为 0)。 diff --git a/scripts/codex-backend/README.md b/scripts/codex-backend/README.md index 87652c44..e195bba6 100644 --- a/scripts/codex-backend/README.md +++ b/scripts/codex-backend/README.md @@ -51,9 +51,16 @@ All Cargo targets, logs and binaries stay under `--output`. On success, not restarted. Source edits beyond the checked-in patches are preserved and rejected, so freeze the adapter patch before running a final build. -New team runs pin this executable and freeze the native transport in their run -record. Saved runs without that transport keep their historical host-tool team. -An incompatible binary fails the capability handshake before a model turn. +New native team runs pin the executable's real path and digest and record +`agentTeam.transport: native-agent-control`. On certain compatibility or transport +errors during initial app-server startup, the solver can retry with +`theoremos_team` host tools. The failed writer must have stopped, and the Lead +must have no open session, saved thread, started turn or model request, or team +member. The solver emits `team_transport_fallback` and saves `host-tools` for +resume. Authentication failures and cancellation follow the normal error path. +A missing binary can fail earlier during configuration. New teams using the +direct Westlake Chat profile start with host tools. Checkpoints that predate the +transport field also use host tools. After the ordinary headless runtime build, exercise the real binary with fixed loopback Responses and independent process/workspace isolation: diff --git a/src/runtime/codexSession.ts b/src/runtime/codexSession.ts index 0b721d39..d4d8676f 100644 --- a/src/runtime/codexSession.ts +++ b/src/runtime/codexSession.ts @@ -530,7 +530,7 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise let turnHasOutput = false; const earlyOutputTurns = new Set(); let completion: { resolve: (turn: Json) => void; reject: (error: Error) => void } | undefined; - let compacting: { resolve: (turn?: Json) => void; reject: (error: Error) => void; + let compacting: { resolve: (turn: Json) => void; reject: (error: Error) => void; turnId?: string; installed?: boolean } | undefined; const earlyCompletions = new Map(); const completedMessages = new Map(); @@ -740,12 +740,10 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise const { id } = object(params.turn); if (typeof id === 'string') compacting.turnId ??= id; } - if (compacting && (method === 'thread/compacted' || method === 'item/completed' && object(params.item).type === 'contextCompaction')) { - if (!nativeControl) compacting.resolve(); - else if (method === 'item/completed' && params.turnId === compacting.turnId) compacting.installed = true; - } if (method === 'item/started' || method === 'item/completed') { const item = object(params.item); + if (compacting?.turnId && method === 'item/completed' && params.turnId === compacting.turnId + && item.type === 'contextCompaction') compacting.installed = true; if (isTurnOutputItem(item)) recordTurnOutput(params.turnId); observePublicItem(method, params, item); if (method === 'item/completed' && completion && typeof params.turnId === 'string' && @@ -796,12 +794,10 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise const turn = object(params.turn); if (typeof turn.id !== 'string' || typeof turn.status !== 'string' || !['completed', 'interrupted', 'failed'].includes(turn.status)) return; - if (compacting && (!compacting.turnId || turn.id === compacting.turnId)) { + if (compacting && turn.id === compacting.turnId) { if (turn.status !== 'completed') compacting.reject(new Error('math_codex_compaction_' + turn.status)); - else if (nativeControl) { - if (compacting.installed) compacting.resolve(turn); - else compacting.reject(new Error('math_codex_compaction_missing_summary')); - } + else if (compacting.installed) compacting.resolve(turn); + else compacting.reject(new Error('math_codex_compaction_missing_summary')); } if (turn.id === activeTurn && completion) completion.resolve(turn); else if (completion && !activeTurn) { @@ -872,8 +868,8 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise ...(tools ? { dynamicTools: tools.definitions } : {}), } } : undefined; // Codex restores history internally. Echoing it can exceed the stdio frame limit. - // Keep the historical usage notification for direct providers with an active budget gate. - const metadataOnlyResume = nativeControl && (usesRequestReceipts || !options.requestGate); + // Retain historical usage replay for sessions that depend on native thread totals. + const metadataOnlyResume = usesRequestReceipts || (nativeControl && !options.requestGate); const threadSettings = { ...settings, ...(options.threadId ? { threadId: options.threadId, ...(metadataOnlyResume ? { excludeTurns: true } : {}) } : {}), @@ -940,7 +936,7 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise options.signal?.throwIfAborted(); if (closing || transportFailure) throw transportFailure ?? new Error('math_codex_transport_closed:closing'); if (completion || activeTurn || compacting) throw new Error('math_codex_turn_already_running'); - const done = new Promise((resolve, reject) => { compacting = { resolve, reject }; }); + const done = new Promise((resolve, reject) => { compacting = { resolve, reject }; }); turnSettled = false; turnStopping = false; turnCheckpointReached = false; requestTurn++; const cancel = scheduleMathTimeout(() => { compacting?.reject(new Error('math_codex_compaction_timeout')); @@ -950,7 +946,7 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise options.signal?.addEventListener('abort', stop, { once: true }); try { const [, turn] = await Promise.all([rpc.request('thread/compact/start', { threadId }), done]); - if (turn && nativeControl) await nativeControl.waitTurnSettled(String(turn.id), turn.status); + if (nativeControl) await nativeControl.waitTurnSettled(String(turn.id), turn.status); } catch (error) { await closeSession(); options.signal?.throwIfAborted(); throw error; } finally { diff --git a/tests/codexSession.test.ts b/tests/codexSession.test.ts index 67705ffb..e28a1ae9 100644 --- a/tests/codexSession.test.ts +++ b/tests/codexSession.test.ts @@ -58,6 +58,11 @@ readline.createInterface({ input: process.stdin }).on('line', line => { modelProvider: fixtureInstruction === 'wrong-provider' ? 'wrong-provider' : settings.config.model_provider, ...(fixtureInstruction === 'ignore-permissions' ? {} : { activePermissionProfile: { id: settings.config.default_permissions } }), approvalPolicy: settings.approvalPolicy, reasoningEffort: settings.config.model_reasoning_effort }); + if (call.method === 'thread/resume' && fixtureInstruction === 'restore-usage' && !settings.excludeTurns) { + send({ method: 'thread/tokenUsage/updated', params: { threadId: settings.threadId, turnId: 'saved-turn', tokenUsage: { + total: { totalTokens: 123 }, last: { inputTokens: 31 }, + } } }); + } } if (call.method === 'mcpServerStatus/list') result({ data: Object.keys(settings.config.mcp_servers) .filter(name => settings.config.mcp_servers[name].enabled).map(name => ({ name, @@ -761,6 +766,13 @@ readline.createInterface({ input: process.stdin }).on('line', line => { expect(await done).toBe('interrupted'); }); + it('receives historical usage when resuming with native thread accounting', async () => { + session = await createCodexMathSession({ ...options, threadId: 'retained-thread', instructions: 'restore-usage', + requestGate: () => ({ allowed: true, settle: () => {} }) }); + expect(session.usageSource).toBe('native-thread-totals'); + await vi.waitFor(() => expect(options.onUsage).toHaveBeenCalledWith({ totalTokens: 123 }, { turnId: 'saved-turn' })); + }); + it('requires turn settlement before confirming writer shutdown and retains the resumable thread', async () => { session = await createCodexMathSession({ ...options, threadId: 'freeze-thread' }); let started = false; diff --git a/tests/nativeDelegation.test.ts b/tests/nativeDelegation.test.ts index 99880b28..fc717136 100644 --- a/tests/nativeDelegation.test.ts +++ b/tests/nativeDelegation.test.ts @@ -14,7 +14,7 @@ vi.mock('../src/runtime/formalizationRelay', () => ({ startFormalizationRelay: a }); } })); const peer = String.raw` -const fs=require('node:fs'),readline=require('node:readline'); +const fs=require('node:fs'),path=require('node:path'),readline=require('node:readline'); const send=value=>process.stdout.write(JSON.stringify(value)+'\n'); let child=0,parentTurn,callback=100; const finish=(status='completed')=>{ @@ -33,7 +33,11 @@ readline.createInterface({input:process.stdin}).on('line',line=>{ } if(c.id===101)return finish(); } - if(c.method==='thread/start'||c.method==='thread/resume')return reply({thread:{id:p.permissions==='math-investigator'?'child-'+(++child):'parent'},model:'fixture-model',reasoningEffort:'high',modelProvider:'sub2api',approvalPolicy:'never',activePermissionProfile:{id:p.permissions==='math-investigator'?(process.env.MODE==='wrong-permission'?'math-worker':'math-investigator'):'math-worker'}}); + if(c.method==='thread/start'||c.method==='thread/resume'){ + const turns=c.method==='thread/resume'&&process.env.MODE==='long-resume'&&!p.excludeTurns + ? [{id:'saved-turn',items:[{type:'agentMessage',text:'x'.repeat(8*1024*1024)}]}] : []; + return reply({thread:{id:p.permissions==='math-investigator'?'child-'+(++child):'parent',turns},model:'fixture-model',reasoningEffort:'high',modelProvider:'sub2api',approvalPolicy:'never',activePermissionProfile:{id:p.permissions==='math-investigator'?(process.env.MODE==='wrong-permission'?'math-worker':'math-investigator'):'math-worker'}}); + } if(c.method==='thread/archive')return process.env.MODE==='archive-error'?send({id:c.id,error:{code:-32603}}):reply({}); if(c.method==='turn/interrupt'){reply({});return finish('interrupted');} if(c.method==='turn/start'){ @@ -55,7 +59,21 @@ readline.createInterface({input:process.stdin}).on('line',line=>{ } if(c.method==='thread/compact/start'){ reply({}); - return setTimeout(()=>send({method:'item/completed',params:{threadId:'parent',turnId:'compact-turn',item:{type:'contextCompaction',id:'compacted'}}}),40); + const turnId = 'compact-turn'; + const notify = (method, params) => send({ method, params: { threadId: 'parent', ...params } }); + const release = path.join(path.dirname(process.env.TRACE), 'compact-release'); + const timer = setInterval(() => { + if (!fs.existsSync(release)) return; + clearInterval(timer); + notify('turn/completed', { turn: { id: turnId, status: fs.readFileSync(release, 'utf8') } }); + }, 5); + notify('turn/started', { turn: { id: turnId, status: 'inProgress' } }); + notify('turn/completed', { turn: { id: 'older-turn', status: 'failed' } }); + notify('thread/compacted', {}); + notify('item/completed', { + turnId: process.env.MODE === 'wrong-summary' ? 'older-turn' : turnId, + item: { type: 'contextCompaction', id: 'compacted' }, + }); } });`; @@ -140,6 +158,13 @@ describe('native delegation availability and compaction', () => { expect(trace().filter(c=>c.method==='thread/start'&&c.params.permissions==='math-investigator')).toHaveLength(2); }); + it('resumes a regular metered thread whose history exceeds the stdio frame limit', async () => { + session = await createCodexMathSession({ ...options(), threadId: 'parent', + environment: { ...options().environment, MODE: 'long-resume' } }); + expect(session.usageSource).toBe('upstream-requests'); + expect(await session.run('Continue the saved research.', 'next', root, () => {})).toBe('completed'); + }); + it('preserves a configured checkpoint result while stopping active child threads',async()=>{ session=await createCodexMathSession({...delegated('waiting'),turnTimeoutMs:75}); expect(await session.run('delegate','one',root,()=>{})).toBe('checkpoint'); @@ -152,13 +177,29 @@ describe('native delegation availability and compaction', () => { expect(fs.existsSync(path.join(root,'trace'))).toBe(false); }); - it('waits for native compaction completion, excludes overlapping turns and continues the same thread',async()=>{ - session=await createCodexMathSession({...options(),environment:{...options().environment,MODE:'compact'}}); - expect(await session.run('Initial research.','one',root,()=>{})).toBe('completed'); - let completed=false;const compact=session.compact!().then(()=>{completed=true;}); - await expect(session.run('Overlapping.','overlap',root,()=>{})).rejects.toThrow('math_codex_turn_already_running'); - expect(completed).toBe(false);await compact;expect(completed).toBe(true); - expect(await session.run('Continue from preserved sources.','two',root,()=>{})).toBe('completed'); + it.each([ + ['matching-summary','completed',undefined], + ['matching-summary','failed','math_codex_compaction_failed'], + ['wrong-summary','completed','math_codex_compaction_missing_summary'], + ])('settles ordinary compaction using the matching terminal turn (%s, %s)', async (mode, status, error) => { + const onItem = vi.fn(); + session = await createCodexMathSession({ ...options(), onItem, environment: { ...options().environment, MODE: mode } }); + expect(await session.run('Initial research.', 'one', root, () => {})).toBe('completed'); + const compact = session.compact!(); + void compact.catch(() => {}); + try { + await vi.waitFor(() => expect(onItem).toHaveBeenCalledWith('completed', + expect.objectContaining({ type: 'contextCompaction' }), expect.anything())); + await expect(session.run('Overlapping.', 'overlap', root, () => {})).rejects.toThrow('math_codex_turn_already_running'); + } finally { + fs.writeFileSync(path.join(root, 'compact-release'), status); + } + if (error) await expect(compact).rejects.toThrow(error); + else { + await compact; + expect(session.threadId).toBe('parent'); + expect(await session.run('Continue from preserved sources.', 'two', root, () => {})).toBe('completed'); + } }); });