JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(agent): prioritize foreground chat over prewarming
dourana7faf106a235
diff --git a/.doc_project_maintainer/INDEX.md b/.doc_project_maintainer/INDEX.mdindex dae1ac083e..4b49d9428b 100644--- a/.doc_project_maintainer/INDEX.md+++ b/.doc_project_maintainer/INDEX.md@@ -38,6 +38,7 @@ Status: partial. A 2026-07-15 semantic-hash scan at `10afedf2` found 0 expired a- [ADR-0001](decisions/ADR-0001-agentserver-owned-prewarmed-sessions.md): AgentServer owns prewarmed session identity.- [CHG-20260731-001](changes/records/CHG-20260731-001-session-prewarm-allocation.md): session allocation and DeepAgent prewarming.+- [CHG-20260801-001](changes/records/CHG-20260801-001-prewarm-foreground-priority.md): foreground chat priority, lazy background warming, and non-blocking runtime probes.## Priority Code Symbolsdiff --git a/.doc_project_maintainer/README.md b/.doc_project_maintainer/README.mdindex 6a9fb294ea..4d05e5a37f 100644--- a/.doc_project_maintainer/README.md+++ b/.doc_project_maintainer/README.md@@ -1,7 +1,7 @@# Project Maintainer DocsStatus: partial-Last updated: 2026-07-15+Last updated: 2026-08-01Sync status: partial## Project Briefdiff --git a/.doc_project_maintainer/changes/records/CHG-20260801-001-prewarm-foreground-priority.md b/.doc_project_maintainer/changes/records/CHG-20260801-001-prewarm-foreground-priority.mdnew file mode 100644index 0000000000..cbfbde9234--- /dev/null+++ b/.doc_project_maintainer/changes/records/CHG-20260801-001-prewarm-foreground-priority.md@@ -0,0 +1,59 @@+---+id: CHG-20260801-001+title: Prioritize foreground chat over background prewarming+type: fix+date: 2026-08-01+modules:+ - agentserver-runtime+ - gateway-and-channels+ - agent-harness+directories:+ - jiuwenswarm/server+ - jiuwenswarm/gateway+flows:+ - session-prewarm-allocation+ - gateway-agentserver-e2a-chat+code_symbols:+ - AgentWarmPool+ - AgentWarmPool.sync+ - AgentWarmPool.claim+ - AgentWarmPool.begin_foreground+ - AgentWarmPool.end_foreground+ - AgentWebSocketServer._handle_stream+ - AgentWebSocketServer._handle_unary+ - AgentWebSocketServer._handle_session_create+ - AgentWebSocketServer._prepare_code_mode_chat_turn+ - resolve_agent_request_mode+ - JiuWenSwarmDeepAdapter._schedule_runtime_state_write+ - JiuWenSwarmDeepAdapter._schedule_memory_reindex+decisions:+ - ADR-0001+commits: []+confidence: confirmed+---++# Prioritize Foreground Chat Over Background Prewarming++## What Changed++Foreground claimed-session initialization now uses an independent concurrency lane and chat-like AgentServer requests pause dispatch of new background warm slots. Startup reconciliation stores the full target set as pending keys but starts one background initialization by default, separated by a cooldown. Gateway and AgentServer both exclude ACP/A2A from warm targets.++Project discovery, runtime-state Git probes, and Git-ignore probing no longer run synchronously on the AgentServer event loop. Runtime-state writes are coalesced per adapter and bounded across worker threads.++The contention follow-up globally caps speculative READY/warming work at one slot, promotes a matching warming task instead of duplicating it, cancels other speculative tasks on foreground entry, and serializes OpenJiuwen process-global registry initialization. Gateway sync triggers are debounced/coalesced. MemoryRail skips first-registration full reindex and singleflights real configuration-change reindex per workspace/fingerprint.++The cache-identity follow-up maps code prewarming to `mode=code, sub_mode=normal`, canonicalizes eligible Session creation from final `work_mode`, and repeats that normalization from locked Session metadata on chat selection. This removes the `code:<empty>`, `code:normal`, and `agent:<empty>` split that caused a READY Session to create a second child on first input.++The CodeCheck follow-ups replace complex channel, pending, and stale-slot comprehensions plus a four-part cancellation condition with explicit loops and named fingerprint checks. They preserve reconcile and requeue behavior.++## Why++Live logs showed background DeepAgent preparation taking tens of seconds and synchronous Git/runtime-state probes executing in the same loop as `chat.send`. That allowed diagnostic or speculative work to delay user-visible initialization even though the warm pool used an asyncio semaphore.++## Impact++- User-visible: a real restarted-stack ham-snake Web session completed in about 7.5 seconds from allocated ID to final history record; the reproduced 30–40 second outlier did not recur.+- Internal: foreground work bypasses the background semaphore; new background slots pause during active chats; startup creates a bounded number of tasks.+- Tests: 139 focused AgentServer/runtime tests passed across the final code slices, including foreground priority, channel filtering, lazy dispatch, out-of-order reconcile protection, and non-blocking runtime probes.+- Follow-up tests: 179 focused tests passed across WarmPool, mode identity, AgentServer send/reload/ACP/plan mode, Gateway ACP, and adapter history/memory behavior.+- Final verification: Ruff passed and 167 relevant tests passed. The pipeline-only lightweight Adapter regression was fixed by treating a missing diagnostic-task slot as idle; the stable upstream root-cleanup expectation remains outside this change.diff --git a/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_session_create.md b/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_session_create.mdindex 7ff5c4b504..37fc377865 100644--- a/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_session_create.md+++ b/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_session_create.md@@ -67,7 +67,7 @@ issues:## Actual Role-Validates project/work-mode binding, rejects explicit new IDs, claims an AgentServer-owned warm or warming session, writes metadata, and returns prewarm status. The linked audit details describe the previous implementation and remain historical until re-audited.+Validates project/work-mode binding, rejects explicit new IDs, canonicalizes eligible single-Agent runtime mode from final `work_mode`, claims an AgentServer-owned warm or warming session, writes metadata, and returns prewarm status. Code sessions persist `code.normal` even when a legacy Channel sent `mode=agent`. The linked audit details describe the previous implementation and remain historical until re-audited.## Audit Detailsdiff --git a/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_stream.md b/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_stream.mdindex 2186028ab8..d8c41b5c3d 100644--- a/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_stream.md+++ b/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_stream.md@@ -24,14 +24,14 @@ health:observability: partialperformance_risk: lowaudit:- status: agent_audited+ status: audit_expiredauditor: codexaudited_at: 2026-07-14T11:37:48Zaudited_commit: 39feee89e00dc6b0b6a6b16ca80a527beb631bd7audited_source_hash: sha256:5fbbae5104a1791ca98014aeed0b81fea243b57dcd2faac3f8f37886833c4fa5audited_symbol_hash: sha256:0f201b65eefd1358f01cf2a596973166607d2ae05d7d088411e035b929ed19e4confidence: confirmed- expired_reason: null+ expired_reason: "2026-08-01 source split into a foreground guard wrapper and _handle_stream_impl."issues:- id: ISSUE-001dimension: state_mutation@@ -67,7 +67,7 @@ issues:## Actual Role-The reviewed behavior, contracts, side effects, callers, callees, tests, and documentation evidence are preserved in the linked detail pages.+Wraps stream handling with the warm-pool foreground guard for chat-like methods. It increments the foreground count before delegating to `_handle_stream_impl` and releases it in `finally`, so exceptions and oversized-output termination cannot leave background warming paused.## Audit Detailsdiff --git a/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_stream_impl.md b/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_stream_impl.mdnew file mode 100644index 0000000000..d09105d16c--- /dev/null+++ b/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_stream_impl.md@@ -0,0 +1,56 @@+---+symbol: AgentWebSocketServer._handle_stream_impl+kind: method+source: jiuwenswarm/server/agent_ws_server.py+source_role: runtime_source+audit_scope: default_health_audit+class: AgentWebSocketServer+signature: "_handle_stream_impl(self, ws, request, send_lock) -> None"+health:+ overall: unknown+ name_behavior_match: unknown+ responsibility_focus: unknown+ length: unknown+ complexity: unknown+ implementation_soundness: unknown+ boundary_safety: unknown+ input_contract: unknown+ output_contract: unknown+ side_effects: unknown+ error_handling: unknown+ state_mutation: unknown+ dependency_coupling: unknown+ test_coverage: unknown+ observability: unknown+ performance_risk: unknown+audit:+ status: unaudited+ auditor: null+ audited_at: null+ audited_commit: null+ audited_source_hash: null+ audited_symbol_hash: null+ confidence: unknown+ expired_reason: null+issues: []+confidence: confirmed+details: {}+---++# AgentWebSocketServer._handle_stream_impl++## Actual Role++Contains the existing stream resolution, agent invocation, heartbeat, bounded sending, task registration, and cleanup behavior after `_handle_stream` has established foreground scheduling priority.++## Key Signals++- Input: decoded request, WebSocket, and connection send lock.+- Output: none after stream completion or normalized terminal output.+- Main side effects: invokes the agent, emits stream frames, and mutates per-session task tracking.+- Main risk: inherited stream lifecycle risks require a fresh independent audit after the method split.+- Related tests: `test_agentserver_modes.py`, `test_ws_send.py`.++## Detail Index++- Detail docs pending.diff --git a/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_unary.md b/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_unary.mdindex 0043c197af..4352888c65 100644--- a/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_unary.md+++ b/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_unary.md@@ -24,14 +24,14 @@ health:observability: clearperformance_risk: lowaudit:- status: agent_audited+ status: audit_expiredauditor: codexaudited_at: 2026-07-14T11:37:47Zaudited_commit: 39feee89e00dc6b0b6a6b16ca80a527beb631bd7audited_source_hash: sha256:5fbbae5104a1791ca98014aeed0b81fea243b57dcd2faac3f8f37886833c4fa5audited_symbol_hash: sha256:9b7fd3efb8a44f6abdb8414dd5d632e92b304e1d3deb58ea45884b31562030d8confidence: confirmed- expired_reason: null+ expired_reason: "2026-08-01 source split into a foreground guard wrapper and _handle_unary_impl."issues:- id: ISSUE-001dimension: error_handling@@ -55,7 +55,7 @@ details: {}## Actual Role-Routes non-stream initialize, session-create/fork, and ACP tool-response requests to dedicated handlers. Stateless methods use the lightweight agent directly; other requests prepare mode/agent state, reconcile plan mode, invoke `process_message`, run the plan-exit check, preserve or fill `agent_ref`, then encode and send one bounded response under the connection lock. `_handle_message` owns cancellation, closed-socket, and generic-error normalization.+Wraps unary handling with the warm-pool foreground guard for chat-like methods. It increments the foreground count before delegating to `_handle_unary_impl` and releases it in `finally`; non-chat unary methods delegate without touching warm scheduling.## Key Signalsdiff --git a/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_unary_impl.md b/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_unary_impl.mdnew file mode 100644index 0000000000..6bf9f35390--- /dev/null+++ b/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_unary_impl.md@@ -0,0 +1,56 @@+---+symbol: AgentWebSocketServer._handle_unary_impl+kind: method+source: jiuwenswarm/server/agent_ws_server.py+source_role: runtime_source+audit_scope: default_health_audit+class: AgentWebSocketServer+signature: "_handle_unary_impl(self, ws, request, send_lock) -> None"+health:+ overall: unknown+ name_behavior_match: unknown+ responsibility_focus: unknown+ length: unknown+ complexity: unknown+ implementation_soundness: unknown+ boundary_safety: unknown+ input_contract: unknown+ output_contract: unknown+ side_effects: unknown+ error_handling: unknown+ state_mutation: unknown+ dependency_coupling: unknown+ test_coverage: unknown+ observability: unknown+ performance_risk: unknown+audit:+ status: unaudited+ auditor: null+ audited_at: null+ audited_commit: null+ audited_source_hash: null+ audited_symbol_hash: null+ confidence: unknown+ expired_reason: null+issues: []+confidence: confirmed+details: {}+---++# AgentWebSocketServer._handle_unary_impl++## Actual Role++Contains the existing unary special-method routing, adapter resolution, agent invocation, plan-exit processing, bounded response encoding, and sending after `_handle_unary` has established foreground scheduling priority.++## Key Signals++- Input: decoded request, WebSocket, and connection send lock.+- Output: none after delegation or one bounded response.+- Main side effects: invokes handlers/agents and sends one response frame.+- Main risk: inherited unary error/finalization behavior requires a fresh independent audit after the method split.+- Related tests: `test_agentserver_modes.py`, `test_agentserver_acp.py`, `test_ws_send.py`.++## Detail Index++- Detail docs pending.diff --git a/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._prepare_code_mode_chat_turn.md b/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._prepare_code_mode_chat_turn.mdindex b46177887e..d811d76679 100644--- a/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._prepare_code_mode_chat_turn.md+++ b/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._prepare_code_mode_chat_turn.md@@ -35,10 +35,10 @@ issues:- id: ISSUE-001dimension: test_coverageseverity: medium- status: open- summary: "Direct tests do not lock AgentManager selection arguments."- evidence: "Tests assert returned mode/sub_mode and only that get_agent was awaited, not channel_id, mapped mode, project_dir, or sub_mode. The interrupt-resume case now duplicates the happy path because approval gates were removed."- suggested_action: "Add direct _prepare_code_mode_chat_turn assertions for get_agent(channel_id, mode, project_dir, sub_mode), including params project_dir, metadata project_dir, auto_harness.plan mapping, and None-agent failure."+ status: fixed+ summary: "Direct tests now lock the relevant AgentManager selection arguments."+ evidence: "Team selection and stale agent/code-workspace tests assert channel_id, mode, project_dir, and sub_mode; auto_harness and None-agent boundaries remain separate pending coverage."+ suggested_action: "Retain the exact cache-identity assertions when extending mode handling."- id: ISSUE-002dimension: observabilityseverity: low@@ -61,15 +61,15 @@ details: {}## Actual Role-Resolves and canonicalizes a chat request's mode, maps logical `auto_harness` to AgentManager mode `"agent"` for instance selection, resolves the stable project directory, and returns the logical mode, sub-mode, and selected agent for unary or streaming chat handling. It mutates `request.params["mode"]` through `_apply_resolved_mode_to_request` and raises `ValueError` if AgentManager returns no agent.+Reads locked Session `work_mode` (falling back to the request), canonicalizes single-Agent runtime identity, resolves the stable project directory, awaits any claimed prewarm task, and selects the matching AgentManager root. A stale `mode=agent` code request therefore selects `(code, normal, project)` rather than constructing a second Session child under another root.## Key Signals- Input: `AgentRequest` plus resolved `channel_id`.- Output: Tuple of logical mode, sub-mode, and resolved agent.- Main side effects: Canonicalizes `request.params["mode"]`; may create or reuse an agent through `AgentManager.get_agent`.-- Main risk: Its broad all-mode selection contract and exact manager arguments are only partially pinned by tests.-- Related tests: Two direct tests exist, but one is a legacy duplicate and neither asserts manager arguments or failure. Local execution is blocked at collection by missing `openjiuwen.auto_harness`; the dedicated plan-exit flow remains pending.+- Main risk: It performs an additional metadata read to restore canonical identity and still has a broad all-mode contract.+- Related tests: direct tests now assert exact AgentManager arguments for team and stale-agent/code-workspace requests; failure and auto-harness boundaries remain partial.## Detail Indexdiff --git a/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/resolve_agent_request_mode.md b/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/resolve_agent_request_mode.mdnew file mode 100644index 0000000000..bd227bbd4a--- /dev/null+++ b/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/resolve_agent_request_mode.md@@ -0,0 +1,29 @@+---+symbol: resolve_agent_request_mode+kind: function+source: jiuwenswarm/server/agent_ws_server.py+source_role: runtime_source+audit_scope: default_health_audit+signature: "resolve_agent_request_mode(raw_mode: Any, *, work_mode: Any = None) -> tuple[str, str | None, str]"+health:+ overall: unknown+audit:+ status: unaudited+confidence: confirmed+---++# resolve_agent_request_mode++## Actual Role++Parses request mode into AgentManager mode, sub-mode, and canonical metadata value. For eligible single-Agent identities, an optional final `work_mode` overrides contradictory legacy input: work becomes `(agent, None, agent)` and code becomes `(code, normal, code.normal)`; plan/team variants retain their specialized identity.++## Key Signals++- Input: raw request mode and optional authoritative work mode.+- Output: normalized manager mode, sub-mode, and canonical mode.+- Side effects: none.+- Main risk: callers that omit authoritative work mode retain legacy mode-only behavior.+- Related tests: `test_resolve_agent_request_mode_accepts_primary_and_dotted_modes` and `test_resolve_agent_request_mode_aligns_single_agent_with_work_mode`.++Health remains unaudited; see the build plan.diff --git a/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter._handle_memory_rail_by_config.md b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter._handle_memory_rail_by_config.mdnew file mode 100644index 0000000000..4e180d8e6a--- /dev/null+++ b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter._handle_memory_rail_by_config.md@@ -0,0 +1,30 @@+---+symbol: JiuWenSwarmDeepAdapter._handle_memory_rail_by_config+kind: method+source: jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+source_role: runtime_source+audit_scope: default_health_audit+class: JiuWenSwarmDeepAdapter+signature: "_handle_memory_rail_by_config(self, mode: str)"+health:+ overall: unknown+audit:+ status: unaudited+confidence: confirmed+---++# JiuWenSwarmDeepAdapter._handle_memory_rail_by_config++## Actual Role++Applies MemoryRail configuration to the session adapter and compares embedding fingerprints. First registration records the fingerprint without forcing a repository-wide reindex; an actual change from a previous fingerprint delegates to the singleflight reindex scheduler.++## Key Signals++- Input: runtime mode and configured memory/embedding state.+- Output: asynchronous configuration completion.+- Main side effects: registers MemoryRail state and may schedule one full reindex for a changed configuration.+- Main risk: incorrect fingerprinting could skip or over-trigger reindexing.+- Related test: `test_memory_reindex_is_singleflight_per_workspace_and_config`.++Health remains unaudited; see the build plan for the pending audit slice.diff --git a/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter._schedule_memory_reindex.md b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter._schedule_memory_reindex.mdnew file mode 100644index 0000000000..2d558f3795--- /dev/null+++ b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter._schedule_memory_reindex.md@@ -0,0 +1,30 @@+---+symbol: JiuWenSwarmDeepAdapter._schedule_memory_reindex+kind: method+source: jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+source_role: runtime_source+audit_scope: default_health_audit+class: JiuWenSwarmDeepAdapter+signature: "_schedule_memory_reindex(self) -> None"+health:+ overall: unknown+audit:+ status: unaudited+confidence: confirmed+---++# JiuWenSwarmDeepAdapter._schedule_memory_reindex++## Actual Role++Schedules a full MemoryRail reindex only when no task with the same normalized workspace and embedding fingerprint is already in flight. The singleflight key is released in the worker's `finally` path so later real configuration changes or retries remain possible.++## Key Signals++- Input: adapter workspace and current embedding configuration.+- Output: none; work is submitted asynchronously.+- Main side effects: mutates the process-wide in-flight key set and schedules the memory reindex worker.+- Main risk: the underlying indexer may still be expensive, but duplicate session initialization no longer multiplies identical work.+- Related test: `test_memory_reindex_is_singleflight_per_workspace_and_config`.++Health remains unaudited; see the build plan for the pending audit slice.diff --git a/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter._schedule_runtime_state_write.md b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter._schedule_runtime_state_write.mdnew file mode 100644index 0000000000..43f7d12ce3--- /dev/null+++ b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter._schedule_runtime_state_write.md@@ -0,0 +1,56 @@+---+symbol: JiuWenSwarmDeepAdapter._schedule_runtime_state_write+kind: method+source: jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+source_role: runtime_source+audit_scope: default_health_audit+class: JiuWenSwarmDeepAdapter+signature: "_schedule_runtime_state_write(self, *, mode, language, channel, session_id, project_dir) -> None"+health:+ overall: unknown+ name_behavior_match: unknown+ responsibility_focus: unknown+ length: unknown+ complexity: unknown+ implementation_soundness: unknown+ boundary_safety: unknown+ input_contract: unknown+ output_contract: unknown+ side_effects: unknown+ error_handling: unknown+ state_mutation: unknown+ dependency_coupling: unknown+ test_coverage: unknown+ observability: unknown+ performance_risk: unknown+audit:+ status: unaudited+ auditor: null+ audited_at: null+ audited_commit: null+ audited_source_hash: null+ audited_symbol_hash: null+ confidence: unknown+ expired_reason: null+issues: []+confidence: confirmed+details: {}+---++# JiuWenSwarmDeepAdapter._schedule_runtime_state_write++## Actual Role++Coalesces diagnostic runtime-state persistence to at most one active task per adapter and runs synchronous Git/file probing in a worker thread under a process-wide bound of two writers. It returns without awaiting that diagnostic work. Lightweight or restored adapters that bypassed `__init__` treat a missing task slot as idle rather than failing request configuration.++## Key Signals++- Input: stable/request runtime identity and project context.+- Output: none.+- Main side effects: schedules a named task that writes a per-session YAML runtime-state file.+- Main risk: a request arriving during an existing write is intentionally coalesced rather than persisted separately.+- Related tests: `test_runtime_state_git_probe_is_non_blocking_and_coalesced` and `test_runtime_config_syncs_channel_and_task_workspace`.++## Detail Index++- Detail docs pending.diff --git a/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter.configure_session_runtime.md b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter.configure_session_runtime.mdindex 0753612183..1010354776 100644--- a/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter.configure_session_runtime.md+++ b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter.configure_session_runtime.md@@ -16,7 +16,7 @@ audit:## Actual Role-Builds the adapter's internal runtime-config bundle from stable session identity, channel, mode, and project inputs, then applies it without binding request-scoped capabilities.+Builds the adapter's internal runtime-config bundle from stable session identity, channel, mode, and project inputs, then applies it without binding request-scoped capabilities. Diagnostic runtime-state persistence is scheduled and coalesced rather than synchronously probing Git on the AgentServer loop.## Key Signalsdiff --git a/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter.prepare_session.md b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter.prepare_session.mdindex 312c134df0..a7fee2975f 100644--- a/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter.prepare_session.md+++ b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter.prepare_session.md@@ -11,4 +11,4 @@ audit:## Actual Role-Creates or reuses the session-scoped adapter, completes `create_instance` and `start_interaction`, then delegates stable workspace, rails, tools, and prompt configuration through the child's public `configure_session_runtime` boundary. It does not attach output or send input.+Creates or reuses the session-scoped adapter, completes `create_instance` and `start_interaction`, then delegates stable workspace, rails, tools, and prompt configuration through the child's public `configure_session_runtime` boundary. Blocking Git-ignore and runtime-state probes are dispatched to worker threads; the method still does not attach output or send input.diff --git a/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/AgentWarmPool.begin_foreground.md b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/AgentWarmPool.begin_foreground.mdnew file mode 100644index 0000000000..3cc888e6f4--- /dev/null+++ b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/AgentWarmPool.begin_foreground.md@@ -0,0 +1,56 @@+---+symbol: AgentWarmPool.begin_foreground+kind: method+source: jiuwenswarm/server/runtime/agent_warm_pool.py+source_role: runtime_source+audit_scope: default_health_audit+class: AgentWarmPool+signature: "begin_foreground(self) -> None"+health:+ overall: unknown+ name_behavior_match: unknown+ responsibility_focus: unknown+ length: unknown+ complexity: unknown+ implementation_soundness: unknown+ boundary_safety: unknown+ input_contract: unknown+ output_contract: unknown+ side_effects: unknown+ error_handling: unknown+ state_mutation: unknown+ dependency_coupling: unknown+ test_coverage: unknown+ observability: unknown+ performance_risk: unknown+audit:+ status: unaudited+ auditor: null+ audited_at: null+ audited_commit: null+ audited_source_hash: null+ audited_symbol_hash: null+ confidence: unknown+ expired_reason: null+issues: []+confidence: confirmed+details: {}+---++# AgentWarmPool.begin_foreground++## Actual Role++Atomically increments the active foreground-chat count, closes the foreground-idle gate, cancels every non-promoted speculative initialization task, and yields once so cooperative cancellation is delivered before foreground preparation contends for the shared initialization lock.++## Key Signals++- Input: none.+- Output: none.+- Main side effects: mutates process-local scheduling state, cancels speculative tasks, requeues their keys, and emits a pause log.+- Main risk: callers must pair it with `end_foreground` in `finally`.+- Related tests: `test_foreground_bypasses_background_and_pauses_lazy_dispatch`, `test_ws_send.py` foreground-manager assertion.++## Detail Index++- Detail docs pending.diff --git a/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/AgentWarmPool.claim.md b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/AgentWarmPool.claim.mdindex 630eedb27c..585f9ee817 100644--- a/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/AgentWarmPool.claim.md+++ b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/AgentWarmPool.claim.md@@ -11,4 +11,4 @@ audit:## Actual Role-Atomically removes a READY slot or creates one claimed-session initialization task. READY claims retain the root pin until the first AgentServer request and schedule a replacement slot.+Atomically removes a READY slot, promotes a matching warming task with its existing Session ID, or creates one claimed-session initialization task on the foreground lane. READY/promoted claims retain the root pin until the first AgentServer request, prioritize their key for replenishment, and do not start new speculative work during active chat.diff --git a/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/AgentWarmPool.end_foreground.md b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/AgentWarmPool.end_foreground.mdnew file mode 100644index 0000000000..fa417608aa--- /dev/null+++ b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/AgentWarmPool.end_foreground.md@@ -0,0 +1,56 @@+---+symbol: AgentWarmPool.end_foreground+kind: method+source: jiuwenswarm/server/runtime/agent_warm_pool.py+source_role: runtime_source+audit_scope: default_health_audit+class: AgentWarmPool+signature: "end_foreground(self) -> None"+health:+ overall: unknown+ name_behavior_match: unknown+ responsibility_focus: unknown+ length: unknown+ complexity: unknown+ implementation_soundness: unknown+ boundary_safety: unknown+ input_contract: unknown+ output_contract: unknown+ side_effects: unknown+ error_handling: unknown+ state_mutation: unknown+ dependency_coupling: unknown+ test_coverage: unknown+ observability: unknown+ performance_risk: unknown+audit:+ status: unaudited+ auditor: null+ audited_at: null+ audited_commit: null+ audited_source_hash: null+ audited_symbol_hash: null+ confidence: unknown+ expired_reason: null+issues: []+confidence: confirmed+details: {}+---++# AgentWarmPool.end_foreground++## Actual Role++Atomically decrements the foreground count and, when the final chat leaves, opens the idle gate and schedules delayed lazy background replenishment.++## Key Signals++- Input: none.+- Output: none.+- Main side effects: mutates scheduling state and may create one delayed pump task.+- Main risk: unmatched calls could resume background work too early; the count is clamped at zero.+- Related tests: `test_foreground_bypasses_background_and_pauses_lazy_dispatch`.++## Detail Index++- Detail docs pending.diff --git a/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/AgentWarmPool.sync.md b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/AgentWarmPool.sync.mdindex ef372bfb55..70369d0181 100644--- a/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/AgentWarmPool.sync.md+++ b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/AgentWarmPool.sync.md@@ -11,4 +11,4 @@ audit:## Actual Role-Builds desired keys from enabled channels and visible/default projects, advances the config fingerprint revision, stales old slots/tasks, schedules missing targets, and returns non-blocking pool statistics.+Filters ineligible channels, discovers visible/default projects off the AgentServer event loop, advances the config fingerprint revision, and reconciles an immutable target snapshot. Missing targets remain pending while only the bounded next background batch is started; the method returns statistics without waiting for initialization.diff --git a/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/Class AgentWarmPool.md b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/Class AgentWarmPool.mdindex 8f08a13fd5..92fbbecfe6 100644--- a/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/Class AgentWarmPool.md+++ b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/Class AgentWarmPool.md@@ -15,12 +15,15 @@ audit:## Actual Role-Maintains one unclaimed READY session per desired channel/project/work-mode key, prevents obsolete configuration revisions from publishing, and hands claimed initialization Futures to the chat path.+Maintains at most one speculative READY or warming session globally across eligible channel/project/work-mode keys, prevents obsolete configuration revisions from publishing, and hands claimed initialization Futures to the chat path. It prioritizes the initial Web/work/default-project key and the most recently claimed key, promotes matching warming work, and cancels non-promoted speculative work when foreground chat begins.## Key Contracts- Only single-Agent keys enter READY.-- A claim is atomic and immediately schedules replenishment.+- Code keys acquire AgentManager roots with `mode=code, sub_mode=normal`; work keys use `mode=agent, sub_mode=None`.+- A claim is atomic; matching warming work retains its Session ID, and the claimed key is prioritized for replenishment after foreground chat.+- ACP/A2A and Swarm keys never enter READY.+- Foreground preparation does not acquire the background semaphore, but shares the process-global registry initialization lock.- Preparation failure cannot publish READY.- Markers never create normal user metadata.diff --git a/.doc_project_maintainer/decisions/ADR-0001-agentserver-owned-prewarmed-sessions.md b/.doc_project_maintainer/decisions/ADR-0001-agentserver-owned-prewarmed-sessions.mdindex 658fd89f63..679c25331e 100644--- a/.doc_project_maintainer/decisions/ADR-0001-agentserver-owned-prewarmed-sessions.md+++ b/.doc_project_maintainer/decisions/ADR-0001-agentserver-owned-prewarmed-sessions.md@@ -20,16 +20,23 @@ DeepAgent construction and interaction startup are expensive on the first messag## Decision-AgentServer is the sole allocator for new and fork target IDs. It maintains one READY single-Agent slot for each enabled channel/project/work-mode key. Slots already carry their final session ID because OpenJiuwen runtime state depends on that identity. Channels obtain the ID through `session.create`; external protocol IDs are aliases.+AgentServer is the sole allocator for new and fork target IDs. It maintains at most one speculative READY or warming single-Agent slot globally across prewarm-eligible enabled channel/project/work-mode keys; ACP and A2A are explicitly not eligible. Slots already carry their final session ID because OpenJiuwen runtime state depends on that identity. Channels obtain the ID through `session.create`; external protocol IDs are aliases.Configuration validity uses a full SHA-256 fingerprint and a per-process boot ID. Warm misses return immediately and initialize in the background; the first real message awaits the same task. Team/Swarm modes remain outside this optimization.+The initial speculative candidate prefers Web/work/default-project, and a claimed key is prioritized for replenishment. A matching warming task is promoted to the foreground with its existing Session ID. Foreground entry cancels other speculative work and pauses dispatch of new slots. Foreground/background initialization shares a lock around process-global OpenJiuwen registries, preventing unsafe concurrent mutation while retaining foreground priority.++For eligible single-Agent sessions, final `work_mode` also determines runtime cache identity: `work` maps to `(agent, None)` and `code` maps to `(code, normal)`. AgentServer canonicalizes contradictory legacy Channel requests before metadata persistence and repeats the normalization on chat selection using locked Session state.+## Consequences- Warm hits remove DeepAgent construction/startup from the first-message critical path.- All creation callers require an AgentServer connection; Web/TUI local creation fallback is intentionally unavailable.- Idempotency is process-local through `create_token`.-- Resource use scales with enabled channels times visible/default projects times two single-Agent work modes.+- Target metadata scales with eligible enabled channels times visible/default projects, but speculative runtime resources are globally capped at one READY/warming slot.+- Diagnostic Git and runtime-state probes run in a bounded worker lane and are not awaited by chat dispatch.+- Gateway prewarm sync is debounced/coalesced, and MemoryRail full reindex is skipped on first registration and singleflight on real embedding changes.+- A claimed READY Session cannot switch to a different root cache merely because a Channel sent stale `mode=agent` for a code project.- Channel trajectory prediction and pool-size reduction can be layered later without changing identity ownership.## Alternatives Rejecteddiff --git a/.doc_project_maintainer/directories/jiuwenswarm__server/README.md b/.doc_project_maintainer/directories/jiuwenswarm__server/README.mdindex 4dc942afa1..d9327e2fa6 100644--- a/.doc_project_maintainer/directories/jiuwenswarm__server/README.md+++ b/.doc_project_maintainer/directories/jiuwenswarm__server/README.md@@ -4,7 +4,7 @@ encoded: jiuwenswarm__servermodules:- agentserver-runtimeconfidence: confirmed-last_updated: 2026-07-15+last_updated: 2026-08-01read_when: "Editing AgentServer entrypoints, WebSocket dispatch, runtime services, sandbox, hooks, or gateway push."---@@ -21,6 +21,7 @@ Contains the AgentServer process entrypoint, the WebSocket server used by Gatewa- `gateway_push/wire.py`: server-push E2A response wire encoder.- `gateway_push/transport.py`: default in-process transport that forwards push messages through the AgentServer singleton.- `runtime/agent_manager.py`: channel/session agent instance management and config reload boundary.+- `runtime/agent_warm_pool.py`: lazy READY-slot reconciliation and foreground-priority session preparation.- `runtime/proactive_adapter.py`: proactive recommendation engine attachment.- `runtime/session/*`: session history and metadata support.- `sandbox/jiuwenbox_runner.py`: jiuwenbox process runner.@@ -35,6 +36,7 @@ Contains the AgentServer process entrypoint, the WebSocket server used by Gatewa- `agentserver-plan-mode-exit`: checkpoint mode restoration and exit push.- `agentserver-schedule-auto-harness`: durable scheduled tasks and autonomous execution.- `agentserver-history-stream`: paged history storage-to-frontend reconstruction.+- `session-prewarm-allocation`: AgentServer-owned IDs, foreground claims, and lazy background replenishment.## Related Code Symbolsdiff --git a/.doc_project_maintainer/manifest.yaml b/.doc_project_maintainer/manifest.yamlindex 79bbb83650..ad97b7a2a6 100644--- a/.doc_project_maintainer/manifest.yaml+++ b/.doc_project_maintainer/manifest.yaml@@ -307,10 +307,20 @@ flows:- AgentWarmPool- AgentWarmPool.sync- AgentWarmPool.claim+ - AgentWarmPool.begin_foreground+ - AgentWarmPool.end_foreground- AgentWebSocketServer._handle_session_create+ - AgentWebSocketServer._handle_stream+ - AgentWebSocketServer._handle_unary+ - resolve_agent_request_mode- JiuWenSwarmDeepAdapter.prepare_session- JiuWenSwarmDeepAdapter.configure_session_runtime+ - JiuWenSwarmDeepAdapter._schedule_runtime_state_writecode_symbols:+- symbol: resolve_agent_request_mode+ kind: function+ source: jiuwenswarm/server/agent_ws_server.py+ doc: code/jiuwenswarm/server/agent_ws_server.py/resolve_agent_request_mode.md- symbol: _runkind: functionsource: jiuwenswarm/server/app_agentserver.py@@ -351,6 +361,14 @@ code_symbols:kind: methodsource: jiuwenswarm/server/runtime/agent_warm_pool.pydoc: code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/AgentWarmPool.claim.md+- symbol: AgentWarmPool.begin_foreground+ kind: method+ source: jiuwenswarm/server/runtime/agent_warm_pool.py+ doc: code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/AgentWarmPool.begin_foreground.md+- symbol: AgentWarmPool.end_foreground+ kind: method+ source: jiuwenswarm/server/runtime/agent_warm_pool.py+ doc: code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/AgentWarmPool.end_foreground.md- symbol: JiuWenSwarmDeepAdapter.prepare_sessionkind: methodsource: jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -359,6 +377,34 @@ code_symbols:kind: methodsource: jiuwenswarm/server/runtime/agent_adapter/interface_deep.pydoc: code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter.configure_session_runtime.md+- symbol: JiuWenSwarmDeepAdapter._schedule_runtime_state_write+ kind: method+ source: jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+ doc: code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter._schedule_runtime_state_write.md+- symbol: JiuWenSwarmDeepAdapter._schedule_memory_reindex+ kind: method+ source: jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+ doc: code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter._schedule_memory_reindex.md+- symbol: JiuWenSwarmDeepAdapter._handle_memory_rail_by_config+ kind: method+ source: jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+ doc: code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter._handle_memory_rail_by_config.md+- symbol: AgentWebSocketServer._handle_stream_impl+ kind: method+ source: jiuwenswarm/server/agent_ws_server.py+ doc: code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_stream_impl.md+- symbol: AgentWebSocketServer._handle_unary_impl+ kind: method+ source: jiuwenswarm/server/agent_ws_server.py+ doc: code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_unary_impl.md+- symbol: AgentWebSocketServer._handle_stream+ kind: method+ source: jiuwenswarm/server/agent_ws_server.py+ doc: code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_stream.md+- symbol: AgentWebSocketServer._handle_unary+ kind: method+ source: jiuwenswarm/server/agent_ws_server.py+ doc: code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_unary.mddecisions:- id: ADR-0001title: AgentServer Owns Prewarmed Session Identity@@ -367,6 +413,9 @@ changes:- id: CHG-20260731-001title: Add AgentServer-owned session allocation and DeepAgent prewarmingdoc: changes/records/CHG-20260731-001-session-prewarm-allocation.md+- id: CHG-20260801-001+ title: Prioritize foreground chat over background prewarming+ doc: changes/records/CHG-20260801-001-prewarm-foreground-priority.mdcode_symbol_inventory:generated_by: scripts/inventory_symbols.pysource_symbol_inventory: project/source-symbol-inventory.jsondiff --git a/.doc_project_maintainer/modules/agent-harness/README.md b/.doc_project_maintainer/modules/agent-harness/README.mdindex 76939713fe..a186a02926 100644--- a/.doc_project_maintainer/modules/agent-harness/README.md+++ b/.doc_project_maintainer/modules/agent-harness/README.md@@ -23,6 +23,10 @@ AgentServer calls this module family through `AgentManager`, adapter methods suc`JiuWenSwarmDeepAdapter.prepare_session` now creates the session-scoped child, starts the real OpenJiuwen interaction, and calls the child's public `configure_session_runtime` boundary without attaching output or sending input. Request-scoped permissions, paths, ACP capabilities, output attachment, and input remain on the real chat path.+Runtime-state Git probes and `.agent_history` Git-ignore checks no longer run synchronously on the AgentServer loop. Runtime-state writes are coalesced per adapter and limited to two worker threads, so diagnostic repository inspection cannot hold up `chat.send` dispatch.++OpenJiuwen tool/resource registration is process-global, so foreground and speculative preparation share one initialization lock. MemoryRail avoids a full reindex on first registration and singleflights reindex by normalized workspace plus embedding fingerprint when configuration actually changes.+## Related Flows- `agentserver-command-mcp`: adapter MCP reconciliation after persisted config changes.diff --git a/.doc_project_maintainer/modules/agentserver-runtime/README.md b/.doc_project_maintainer/modules/agentserver-runtime/README.mdindex 875efb0541..b2c955c927 100644--- a/.doc_project_maintainer/modules/agentserver-runtime/README.md+++ b/.doc_project_maintainer/modules/agentserver-runtime/README.md@@ -38,6 +38,10 @@ Hosts the standalone AgentServer process and the WebSocket RPC surface used by G- `agentserver-history-stream`: persisted history paging, sanitization, streamed events, and frontend reconstruction.- `session-prewarm-allocation`: Gateway channel sync, pool reconciliation, AgentServer allocation, and first-chat readiness.+Foreground `chat.send`, `chat.resume`, and `chat.user_answer` open a priority window around unary/stream dispatch. The pool globally caps speculative READY/warming work at one slot. A matching warming task is promoted; other speculative tasks are cancelled, and process-global OpenJiuwen registry initialization is serialized before foreground preparation proceeds. Remaining targets stay as lightweight pending keys.++Eligible single-Agent runtime identity follows final `work_mode`: work selects `agent` with no sub-mode, while code selects `code.normal`. Session creation persists that canonical identity and chat selection restores it from locked metadata, so Channel-provided stale mode values cannot bypass a claimed READY child.+## Related Code Symbols- `_run`: startup lifecycle for the standalone process.@@ -55,7 +59,9 @@ Hosts the standalone AgentServer process and the WebSocket RPC surface used by G- `tests/unit_tests/agentserver/test_agentserver_cli_commands.py` covers slash-command handlers.- `tests/unit_tests/agentserver/test_agent_ws_connection_close.py` covers disconnect cleanup behavior.- `tests/unit_tests/agentserver/test_agent_warm_pool.py` covers READY targets, concurrent claims, replenishment, revision replacement, and failure isolation.+- The priority regression cases cover ACP/A2A exclusion, foreground semaphore bypass, chat-time background pause, lazy one-slot dispatch, and post-chat replenishment.- The focused session-allocation contract run passed 139 tests across AgentServer, Web, project binding, and TUI ownership surfaces on 2026-08-01.+- The priority follow-up passed 139 focused AgentServer/runtime tests; a restarted local stack completed a real ham-snake Web session in about 7.5 seconds from allocated ID to final history record, without the previous 30–40 second outlier.## Known Gapsdiff --git a/.doc_project_maintainer/modules/gateway-and-channels/README.md b/.doc_project_maintainer/modules/gateway-and-channels/README.mdindex 4178617998..3fc43409f7 100644--- a/.doc_project_maintainer/modules/gateway-and-channels/README.md+++ b/.doc_project_maintainer/modules/gateway-and-channels/README.md@@ -22,7 +22,8 @@ Accepts user/channel/front-end input, normalizes it into E2A or legacy-compatibl- `jiuwenswarm/gateway/routing/agent_client.py` receives AgentServer frames, routes normal responses by request ID, and treats server-push frames as out-of-band events.- `docs/en/E2A-protocol.md` describes Gateway -> AgentServer E2A field contracts.- Tests outside the AgentServer directory cover AgentServer client queueing, reconnect/close behavior, stream tail grace, and timeout policy.-- Gateway reports live channel IDs through `agent.prewarm.sync`. Web/TUI local session creation now proxies AgentServer, IM first contact and `/new_session` allocate before forwarding, and ACP/A2A/SSH retain external IDs only as aliases.+- Gateway reports only prewarm-eligible live channel IDs through `agent.prewarm.sync`; ACP and A2A are excluded at both Gateway and AgentServer boundaries. Web/TUI local session creation proxies AgentServer, IM first contact and `/new_session` allocate before forwarding, and ACP/A2A/SSH retain external IDs only as aliases without creating warm targets.+- Startup, channel-change, and configuration-reload prewarm sync triggers are debounced and coalesced; pending delayed sync is cancelled during Gateway shutdown.- Web session creation derives `user_id` from the authenticated connection and overwrites any request-body value before forwarding to AgentServer.## Related Flowsdiff --git a/.doc_project_maintainer/project/build-plan.md b/.doc_project_maintainer/project/build-plan.mdindex 0237359385..1e75c773af 100644--- a/.doc_project_maintainer/project/build-plan.md+++ b/.doc_project_maintainer/project/build-plan.md@@ -1,5 +1,5 @@----last_updated: 2026-07-31+last_updated: 2026-08-01sync_status: partialcoverage_status: partialflow_coverage_status: partial@@ -14,8 +14,7 @@ code_symbol_coverage_status: partial- Latest expiration check: the 2026-07-15 normalized-AST scan at `10afedf2` found 0 expired audits among the 128 existing `AgentWebSocketServer` method reviews. No method card or audit signature required refresh, and no previously unaudited symbol was promoted.- Flow delivery: eight AgentServer flows are documented, including MCP, sandbox, plan exit, scheduled Auto-Harness, and history streaming.- Project status remains partial: most modules, directories, source symbol entry docs, cross-layer flows, and default-health audits are still pending.-- The 2026-07-31 scoped feature sync added `session-prewarm-allocation`, ADR-0001, and CHG-20260731-001 without widening repository coverage or claiming a health audit.-- Actionable repository queues remain 298 coverage slices and 167 default-health audit slices.+- The 2026-07-31/2026-08-01 scoped prewarm follow-ups are synced without widening coverage or claiming a health audit. They record the global slot cap, foreground promotion/cancellation, registry serialization, sync coalescing, MemoryRail singleflight, and canonical code cache identity; affected symbols remain unaudited or audit-expired.- Every stable source file inventoried: yes, by the 2026-07-15 `inventory_symbols.py --verify-docs` scan.- Every required symbol documented or out of scope: no.- Every requested-scope audit symbol closure eligible or out of scope: no; 0 AgentWebSocketServer method audits are source-expired, while 69 records currently have entry-document hash mismatches and broader repository audits remain pending.@@ -41,6 +40,7 @@ code_symbol_coverage_status: partial- 2026-07-14: `agentserver-rebase-expiration-reaudit` - re-reviewed exactly the 64 existing AgentWebSocketServer methods expired by the rebase at `39feee89`; all 64 are trusted, with no new unaudited symbol added or promoted.- 2026-07-15: `agentserver-expiration-scan` - scanned `10afedf2`; all 128 existing AgentWebSocketServer method audits remain source-current, 0 expired, and 6 newly observed unaudited server methods were left outside the frozen queue.- 2026-07-31: AgentServer-owned session allocation and one-slot DeepAgent prewarming across enabled channels/projects; Web, TUI, IM, ACP, A2A, SSH, fork, and single-Agent Cron creation paths were aligned.+- 2026-08-01: Prewarm priority/cache correction: one slot, foreground priority, canonical code identity, lightweight Adapter guard, CodeCheck cleanup, and 167 final tests.## Completed AgentServer Flow Slices@@ -56,7 +56,7 @@ code_symbol_coverage_status: partial- `jiuwenswarm/agents/harness/team`: distributed team lifecycle and remote member bootstrap.- `jiuwenswarm/channels/web`, `jiuwenswarm/channels/tui`, and `jiuwenbox`: UI state, command consumers, and sandbox service boundaries.- `tests/unit_tests/agentserver`: repository-coverage-only test symbols remain largely undocumented.-- Session prewarming: new `AgentWarmPool` symbols, `AgentManager` pool methods, `JiuWenSwarmDeepAdapter.prepare_session` and runtime split methods, Gateway/Channel allocators, and Cron allocation remain unaudited. `AgentWebSocketServer._handle_session_create` changed after its prior audit and must be treated as `audit_expired`; `_handle_agent_prewarm_sync` is unaudited.+- Session prewarming remains unaudited. Modified stream/unary wrappers are `audit_expired`; new pool, adapter, Gateway filter, and implementation-helper symbols are pending audit.## Highest-Risk Findings To Carry Forwarddiff --git a/.doc_project_maintainer/project/flows/gateway-agentserver-e2a-chat.md b/.doc_project_maintainer/project/flows/gateway-agentserver-e2a-chat.mdindex 7a9fda74b5..02651307a8 100644--- a/.doc_project_maintainer/project/flows/gateway-agentserver-e2a-chat.md+++ b/.doc_project_maintainer/project/flows/gateway-agentserver-e2a-chat.md@@ -3,7 +3,7 @@ id: gateway-agentserver-e2a-chatname: Gateway AgentServer E2A Chatstatus: partialconfidence: confirmed-last_updated: 2026-07-31+last_updated: 2026-08-01user_visible_surface: "Channel, TUI, CLI, ACP, and web responses produced from AgentServer output."source_of_truth: []modules:@@ -32,9 +32,9 @@ Gateway can send a normalized E2A or legacy-compatible request to AgentServer anGateway `WebSocketAgentServerClient` connects to AgentServer, waits for `connection.ack`, sends `E2AEnvelope.to_dict()` JSON, and receives E2A response wire frames. AgentServer `_connection_handler` creates a task per inbound frame. `_handle_message` decodes JSON, prefers `E2AEnvelope.from_dict`, falls back to legacy payload parsing when needed, injects ACP capability metadata for ACP requests, triggers before-chat hooks for chat-like methods, then dispatches by `ReqMethod`.-Requests with special methods go to local handlers. Other requests go to `_handle_stream` or `_handle_unary`, which resolve mode and agent state through `AgentManager`, call `process_message_stream` or `process_message`, encode responses through E2A wire helpers, and send them under the connection send lock.+Requests with special methods go to local handlers. Other requests go to `_handle_stream` or `_handle_unary`. Chat-like methods first increment the warm-pool foreground guard, then their implementation helpers resolve mode and agent state through `AgentManager`, call `process_message_stream` or `process_message`, encode responses through E2A wire helpers, and send them under the connection send lock. A `finally` block releases the guard so lazy background warming resumes after the final active chat.-For newly allocated single-Agent sessions, adapter resolution first awaits the warm-pool preparation Future. A READY claim has already completed DeepAgent creation and interaction startup; a miss shares the background initialization task with the first chat.+For newly allocated single-Agent sessions, adapter resolution first awaits the warm-pool preparation Future. A READY claim has already completed DeepAgent creation and interaction startup; a miss shares its foreground initialization task with the first chat and bypasses the background semaphore.## State Classificationdiff --git a/.doc_project_maintainer/project/flows/session-prewarm-allocation.md b/.doc_project_maintainer/project/flows/session-prewarm-allocation.mdindex 291c659787..f94da88742 100644--- a/.doc_project_maintainer/project/flows/session-prewarm-allocation.md+++ b/.doc_project_maintainer/project/flows/session-prewarm-allocation.md@@ -20,10 +20,17 @@ code_symbols:- AgentWarmPool- AgentWarmPool.sync- AgentWarmPool.claim+ - AgentWarmPool.begin_foreground+ - AgentWarmPool.end_foreground- AgentWebSocketServer._handle_agent_prewarm_sync- AgentWebSocketServer._handle_session_create+ - AgentWebSocketServer._handle_stream+ - AgentWebSocketServer._handle_unary+ - resolve_agent_request_mode- JiuWenSwarmDeepAdapter.prepare_session- JiuWenSwarmDeepAdapter.configure_session_runtime+ - JiuWenSwarmDeepAdapter._schedule_runtime_state_write+ - JiuWenSwarmDeepAdapter._schedule_memory_reindexentrypoints:- jiuwenswarm/gateway/app_gateway.py- jiuwenswarm/server/agent_ws_server.py@@ -33,24 +40,26 @@ entrypoints:## Outcome-For each enabled channel and visible/default project, AgentServer maintains one unclaimed, session-bound READY DeepAgent for single-Agent work or code mode. A new session receives its ID from AgentServer. A warm hit avoids `create_instance` and `start_interaction` on the first `chat.send`; a miss returns an ID immediately, initializes in the background, and makes the first message await that same task.+AgentServer keeps at most one speculative, unclaimed READY or warming DeepAgent across all eligible single-Agent work/code keys. Single-Agent identity is canonical: work uses `agent:<empty>:<project>` and code uses `code:normal:<project>` in prewarm, metadata, and chat selection. ACP and A2A never enter the target set. A warm hit avoids `create_instance` and `start_interaction` on the first `chat.send`.Team, `code.team`, and Swarm creation bypass the warm pool.## Causal Path-1. Gateway finishes channel registration and sends `agent.prewarm.sync` with the deduplicated live channel IDs. Configuration/channel changes trigger another non-blocking sync; a periodic scan is the fallback.-2. AgentServer resolves visible projects and default work/code projects into `WarmKey` values. `AgentWarmPool` reconciles one READY slot per key with bounded initialization concurrency.-3. Preparation gets the root adapter, creates the session-scoped DeepAdapter, runs `create_instance`, applies session-stable rails/tools/workspace through `configure_session_runtime`, and calls `start_interaction(session_id)`. It never calls `attach_output` or `send_input`.-4. `session.create` validates project/work-mode binding before allocation. `create_token` retries reuse the same claim. A READY slot is atomically removed and replenished; a miss starts one claimed-session preparation task.+1. Gateway finishes channel registration and sends `agent.prewarm.sync` with deduplicated eligible channel IDs after filtering ACP/A2A. AgentServer repeats the exclusion defensively. Startup, configuration, and channel triggers are debounced and coalesced so reload completion is not followed by duplicate reconcile bursts; a periodic scan is the fallback.+2. AgentServer scans visible/default projects in a worker thread and stores one immutable `WarmKey` target snapshot. Reconciliation retains missing targets as pending keys, but globally permits only one speculative READY or warming slot; it does not create one asyncio task per project/channel at startup.+3. Background preparation gets the root adapter with `(code, normal)` for code or `(agent, None)` for work, creates the session child, configures stable runtime state, and starts the interaction without sending input.+4. `session.create` validates project binding, derives the single-Agent canonical mode from final `work_mode`, and persists that mode before allocation. A READY slot is atomically claimed; matching warming work is promoted with its existing ID.5. AgentServer writes normal metadata only after claim. The prewarm marker is retained through the claim and removed only after metadata commits, closing the crash gap without exposing blank slots in normal session listings.-6. `_resolve_adapter`, unary chat, and streaming chat await the claimed session's preparation task. Request IDs, input, attachments, skills, permissions, request workspace/trusted dirs, ACP capabilities, output attachment, and real input remain request-bound.-7. Web, TUI, IM, ACP, A2A, SSH, and single-Agent Cron use the returned ID. ACP/A2A/SSH retain protocol IDs as Gateway aliases. Fork IDs are also AgentServer allocated but do not consume blank warm slots.+6. Chat selection reads the locked Session `work_mode` (falling back to the request), canonicalizes stale `mode=agent` code requests to `code.normal`, awaits the claimed task, and selects the same AgentManager cache key. Foreground cancellation and the shared registry lock prevent competing initialization.+7. MemoryRail registration does not schedule a full reindex on first registration. A real embedding-configuration change is singleflight per normalized workspace and fingerprint, preventing parallel new sessions from repeating the same repository-wide indexing work.+8. Web, TUI, IM, ACP, A2A, SSH, and single-Agent Cron use the returned ID. ACP/A2A/SSH retain protocol IDs as Gateway aliases. Fork IDs are also AgentServer allocated but do not consume blank warm slots.## State And Identity- Source of truth: claimed session metadata and history under AgentServer ownership.- Cache: READY slots, preparation tasks, `create_token` results, and external-channel aliases are process-local.+- Scheduling state: one target snapshot, at most one speculative READY/warming slot globally, pending/prioritized keys, promoted tasks, foreground count, and a shared initialization lock are process-local.- Disposable state: `.prewarm/<session_id>.json` markers identify unclaimed slots and include `boot_id`.- Revision: `boot_id + SHA-256(config/env) + sequence`; only matching current fingerprints may publish READY.- ID format: `<channel>_<timestamp/random>`.@@ -66,17 +75,18 @@ On startup, old-boot markers and unclaimed metadata-less directories are removed- Initialization exceptions are logged and never publish READY.- Continuous reconciles cancel superseded warm tasks; late old-revision completion cannot enter the pool.- A READY root stays pinned until the claimed session reaches its first AgentServer request, preventing idle retirement in the create-to-send gap.+- Foreground entry cancels non-promoted background initialization. Cancellation remains cooperative, so a synchronous third-party call may finish before releasing the shared initialization lock, but no competing foreground initializer mutates process-global registries concurrently and no successor starts while chat is active.+- Runtime-state Git probes and Git-ignore checks execute in worker threads. Runtime-state writes are coalesced per adapter and globally bounded to two concurrent probes, so they do not synchronously hold the AgentServer loop.+- A lightweight/restored adapter without an initialized diagnostic-task slot treats that slot as idle, so optional runtime-state persistence cannot abort request configuration.## Verification-- `tests/unit_tests/agentserver/test_agent_warm_pool.py`: key normalization, one READY slot, atomic concurrent claims, replenishment, config replacement, failed preparation, marker activation, and boot cleanup.-- Web `test:create-conversation-session`: AgentServer response ID and stable-token retry.-- Web production build and TUI typecheck cover channel call-site contracts.-- `tests/unit_tests/gateway/test_cron_scheduler.py`: single-Agent Cron performs `session.create` before chat and uses the returned ID.-- AgentServer ACP/plan-mode, Web identity, project binding, and TUI forwarding/KVC ownership suites: 139 passed together.-- The full Windows unit run completed with 3,791 passed, 4 skipped, and 14 failures outside this flow's changed surfaces.-- CodeCheck cleanup removed obsolete local Web/TUI creation fallbacks, reduced warm-pool condition complexity without changing guards, and replaced protected child access with a public stable-config boundary; 166 related tests passed.+- WarmPool/mode tests cover global capacity, promotion/cancellation, code `sub_mode=normal`, work-mode canonicalization, and identical prewarm/chat cache identity.+- Adapter tests cover off-loop/coalesced runtime probes and per-workspace/config MemoryRail reindex singleflight.+- AgentServer send/reload/ACP/plan-mode and Gateway ACP suites cover foreground guards and allocation boundaries.+- The latest contention/cache-identity follow-up passed 179 focused tests. Earlier channel-contract runs passed 139 tests, and the full Windows unit run recorded 3,791 passed, 4 skipped, with 14 unrelated failures.+- A restarted ham-snake Web session previously completed in about 7.5 seconds; sustained live-load verification of this contention correction remains pending.## Known Gaps-The pool is process-local and does not preserve idempotency tokens across AgentServer restart. Full live multi-channel integration, load/resource limits, checkpointer cleanup validation, long-lived unclaimed-claim pin expiry, and real OpenJiuwen timing metrics remain pending. The repository-wide symbol audit was not expanded; changed symbols remain unaudited or audit-expired.+The pool is process-local and does not preserve idempotency tokens across AgentServer restart. Full live multi-channel integration, sustained load/resource limits, cancellation of a background initializer already inside a non-cooperative third-party call, checkpointer cleanup validation, and long-lived unclaimed-claim pin expiry remain pending. The repository-wide symbol audit was not expanded; changed symbols remain unaudited or audit-expired.diff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.pyindex 5098abb837..382c4f8aad 100644--- a/jiuwenswarm/gateway/app_gateway.py+++ b/jiuwenswarm/gateway/app_gateway.py@@ -79,6 +79,7 @@ logger = logging.getLogger("jiuwenswarm.gateway")# Keep gateway idle-finalize fallback aligned with ACP channel default._PROMPT_IDLE_FINALIZE_SECONDS = 3.0+_AGENT_PREWARM_EXCLUDED_CHANNELS = frozenset({"acp", "a2a"})# IM 平台官方 API 域名(仅作为 config.yaml 缺字段时的加载兜底,不在 Config 类里硬编码)_FEISHU_DEFAULT_API_BASE = "https://open.feishu.cn"@@ -1596,15 +1597,21 @@ async def _run(# 回填引用:MessageHandler 实例化早于 ChannelManager,广播全局事件时需经它取 web channel。message_handler.set_channel_manager(channel_manager)updater_service = UpdaterService()+ prewarm_sync_debounce_task: asyncio.Task[None] | None = Noneasync def _sync_agent_prewarm_channels() -> None:try:+ prewarm_channels = {+ channel+ for channel in channel_manager.enabled_channels+ if channel.lower() not in _AGENT_PREWARM_EXCLUDED_CHANNELS+ }env = e2a_from_agent_fields(request_id=f"agent-prewarm-sync-{uuid_module.uuid4().hex[:8]}",channel_id="",req_method=ReqMethod.AGENT_PREWARM_SYNC,params={- "enabled_channels": sorted(set(channel_manager.enabled_channels)),+ "enabled_channels": sorted(prewarm_channels),},)resp = await client.send_request(env)@@ -1620,6 +1627,26 @@ async def _run(await asyncio.sleep(60)await _sync_agent_prewarm_channels()+ def _schedule_agent_prewarm_sync(+ name: str, *, delay_seconds: float = 1.0+ ) -> None:+ """Coalesce startup/config/channel churn into one settled sync."""+ nonlocal prewarm_sync_debounce_task+ previous = prewarm_sync_debounce_task+ if previous is not None and not previous.done():+ previous.cancel()++ async def _delayed_sync() -> None:+ try:+ await asyncio.sleep(max(0.0, delay_seconds))+ await _sync_agent_prewarm_channels()+ except asyncio.CancelledError:+ return++ prewarm_sync_debounce_task = asyncio.create_task(+ _delayed_sync(), name=name+ )+async def _on_config_saved(updated_env_keys: set[str] | None = None,*,@@ -1678,9 +1705,9 @@ async def _run(return Falseraise RuntimeError(f"agent.reload_config rejected: {err_msg}")- asyncio.create_task(- _sync_agent_prewarm_channels(),- name="agent-prewarm-sync-after-config",+ _schedule_agent_prewarm_sync(+ "agent-prewarm-sync-after-config",+ delay_seconds=3.0,)if updated_env_keys and (browser_runtime_keys & set(updated_env_keys)):@@ -2510,16 +2537,16 @@ async def _run(else:logger.info("[App] channels.ssh missing or invalid, SshChannel disabled")- asyncio.create_task(- _sync_agent_prewarm_channels(),- name="agent-prewarm-sync-after-channel-change",+ _schedule_agent_prewarm_sync(+ "agent-prewarm-sync-after-channel-change",+ delay_seconds=1.0,)channel_manager.set_config_callback(_apply_channel_config)await channel_manager.set_config(initial_channels_conf)- asyncio.create_task(- _sync_agent_prewarm_channels(),- name="agent-prewarm-sync-after-startup",+ _schedule_agent_prewarm_sync(+ "agent-prewarm-sync-after-startup",+ delay_seconds=3.0,)prewarm_sync_task = asyncio.create_task(_periodic_agent_prewarm_sync(),@@ -2569,6 +2596,12 @@ async def _run(except asyncio.CancelledError:passfinally:+ if prewarm_sync_debounce_task is not None:+ prewarm_sync_debounce_task.cancel()+ try:+ await prewarm_sync_debounce_task+ except asyncio.CancelledError:+ passprewarm_sync_task.cancel()try:await prewarm_sync_taskdiff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex 05d325fd85..b3dc453839 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -1551,7 +1551,11 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:if real_client is None:returncm = _resolve(channel_manager)- enabled_channels = list(getattr(cm, "enabled_channels", []) or [])+ enabled_channels = [+ channel+ for channel in list(getattr(cm, "enabled_channels", []) or [])+ if str(channel).lower() not in {"acp", "a2a"}+ ]env = e2a_from_agent_fields(request_id=f"agent-prewarm-project-{uuid.uuid4().hex[:8]}",channel_id="web",diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.pyindex 5aad2254aa..27561aa75d 100644--- a/jiuwenswarm/server/agent_ws_server.py+++ b/jiuwenswarm/server/agent_ws_server.py@@ -543,7 +543,11 @@ def _harness_error_code(exc: BaseException) -> str:return "BAD_REQUEST"-def resolve_agent_request_mode(raw_mode: Any) -> tuple[str, str | None, str]:+def resolve_agent_request_mode(+ raw_mode: Any,+ *,+ work_mode: Any = None,+) -> tuple[str, str | None, str]:"""Resolve request params.mode into manager mode, sub_mode, and canonical value.plan / fast 已合并为单一 ``agent`` 模式:任何 ``agent`` / ``agent.plan`` /@@ -555,14 +559,21 @@ def resolve_agent_request_mode(raw_mode: Any) -> tuple[str, str | None, str]:mode_text = raw_value.strip().lower() if isinstance(raw_value, str) else ""if not mode_text:mode_text = "agent"+ normalized_work_mode = (+ work_mode.strip().lower() if isinstance(work_mode, str) else ""+ )if mode_text in ("plan", "fast"):+ if normalized_work_mode == "code":+ return "code", "normal", "code.normal"return "agent", None, "agent"parts = mode_text.split(".")mode = parts[0] or "agent"if mode == "agent":# 合并模式:忽略历史子模式(plan / fast),统一 canonical "agent"。+ if normalized_work_mode == "code":+ return "code", "normal", "code.normal"return "agent", None, "agent"if mode == "team":sub_mode = parts[1] if len(parts) > 1 and parts[1] else None@@ -580,12 +591,22 @@ def resolve_agent_request_mode(raw_mode: Any) -> tuple[str, str | None, str]:if mode == "code" and sub_mode not in {"plan", "normal", "team"}:sub_mode = default_sub_modes.get(mode, "normal")canonical_mode = f"{mode}.{sub_mode}" if sub_mode else mode+ if canonical_mode in {"agent", "code", "code.normal"}:+ if normalized_work_mode == "code":+ return "code", "normal", "code.normal"+ if normalized_work_mode == "work":+ return "agent", None, "agent"return mode, sub_mode, canonical_mode-def _apply_resolved_mode_to_request(request: AgentRequest) -> tuple[str, str | None]:+def _apply_resolved_mode_to_request(+ request: AgentRequest,+ *,+ work_mode: Any = None,+) -> tuple[str, str | None]:mode, sub_mode, canonical_mode = resolve_agent_request_mode(- request.params.get("mode", "agent")+ request.params.get("mode", "agent"),+ work_mode=work_mode,)request.params["mode"] = canonical_modereturn mode, sub_mode@@ -2050,7 +2071,41 @@ class AgentWebSocketServer:params = request.params if isinstance(request.params, dict) else {}_raw_mode = params.get("mode")explicit_mode_provided = isinstance(_raw_mode, str) and bool(_raw_mode.strip())- mode, sub_mode = _apply_resolved_mode_to_request(request)+ runtime_work_mode = None+ sid = str(request.session_id or "").strip()+ if sid:+ from jiuwenswarm.server.runtime.session.session_metadata import (+ get_session_metadata,+ )++ session_metadata = get_session_metadata(+ sid,+ cache_bust=True,+ enable_writeback=False,+ )+ stored_work_mode = (+ session_metadata.get("work_mode")+ if isinstance(session_metadata, dict)+ else None+ )+ if isinstance(stored_work_mode, str) and stored_work_mode.strip().lower() in {+ "code",+ "work",+ }:+ runtime_work_mode = stored_work_mode.strip().lower()+ if runtime_work_mode is None:+ request_work_mode = params.get("work_mode")+ if isinstance(request_work_mode, str) and request_work_mode.strip().lower() in {+ "code",+ "work",+ }:+ runtime_work_mode = request_work_mode.strip().lower()+ if runtime_work_mode is not None:+ params["work_mode"] = runtime_work_mode+ mode, sub_mode = _apply_resolved_mode_to_request(+ request,+ work_mode=runtime_work_mode,+ )agent_mode = "agent" if mode == "auto_harness" else moderequested_project_dir = resolve_request_project_dir(request)# [改动] 写盘用 canonical mode(request.params["mode"],已被规范化为@@ -2211,7 +2266,27 @@ class AgentWebSocketServer:return restored_after_approval- async def _handle_unary(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:+ async def _handle_unary(+ self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock+ ) -> None:+ manager = getattr(self, "_agent_manager", None)+ foreground = (+ request.req_method in _CODE_MODE_SYNC_METHODS+ and manager is not None+ and hasattr(manager, "begin_foreground_chat")+ and hasattr(manager, "end_foreground_chat")+ )+ if foreground:+ await manager.begin_foreground_chat()+ try:+ await self._handle_unary_impl(ws, request, send_lock)+ finally:+ if foreground:+ await manager.end_foreground_chat()++ async def _handle_unary_impl(+ self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock+ ) -> None:"""非流式处理:调用 process_message,返回一条 E2AResponse 线 JSON。"""# 兜底确保 checkpointer 就绪: start() 里改为后台预热后, 首条请求可能赶在# 预热完成前到达。ensure_persistent_checkpointer 内部 lock+ready 幂等, 预热@@ -2290,7 +2365,27 @@ class AgentWebSocketServer:)- async def _handle_stream(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:+ async def _handle_stream(+ self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock+ ) -> None:+ manager = getattr(self, "_agent_manager", None)+ foreground = (+ request.req_method in _CODE_MODE_SYNC_METHODS+ and manager is not None+ and hasattr(manager, "begin_foreground_chat")+ and hasattr(manager, "end_foreground_chat")+ )+ if foreground:+ await manager.begin_foreground_chat()+ try:+ await self._handle_stream_impl(ws, request, send_lock)+ finally:+ if foreground:+ await manager.end_foreground_chat()++ async def _handle_stream_impl(+ self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock+ ) -> None:"""流式处理:调用 process_message_stream,逐条发送 E2AResponse 线 JSON。"""# 兜底确保 checkpointer 就绪 (见 _handle_unary 同名注释)。from jiuwenswarm.server.runtime.agent_adapter.interface_deep import ensure_persistent_checkpointer@@ -7523,6 +7618,12 @@ class AgentWebSocketServer:"team.plan","code.team",}+ if not is_swarm:+ mode, _, canonical_mode = resolve_agent_request_mode(+ canonical_mode,+ work_mode=final_work_mode,+ )+ params["mode"] = canonical_modeprewarm_eligible = (not is_swarmand canonical_mode in {"agent", "code", "code.normal"}diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex c41edea0e0..8d06275392 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -754,6 +754,7 @@ class JiuWenSwarmDeepAdapter:SESSION_ADAPTER_IDLE_TTL_SEC = 2 * 60 * 60SESSION_ADAPTER_EVICT_BATCH_SIZE = 3SESSION_ADAPTER_RELOAD_RETRY_INTERVAL_SEC = 30.0+ _RUNTIME_STATE_WRITE_LIMIT = threading.BoundedSemaphore(2)"""Deep SDK 适配器,实现 AgentAdapter 协议.@@ -895,6 +896,59 @@ class JiuWenSwarmDeepAdapter:self._dreaming_started = Falseself._dreaming_mode: str = "agent"self._send_file_toolkit: SendFileToolkit | None = None+ self._runtime_state_write_task: asyncio.Task[None] | None = None++ def _schedule_runtime_state_write(+ self,+ *,+ mode: str,+ language: str,+ channel: str,+ session_id: str | None,+ project_dir: str | None,+ ) -> None:+ """Persist diagnostic Git/runtime state without delaying chat handling."""+ # Some lightweight adapters are restored or constructed without the+ # full initializer (including focused rail tests). Treat the missing+ # diagnostic-task slot as idle; runtime-state persistence must never+ # break request configuration.+ current = getattr(self, "_runtime_state_write_task", None)+ if current is not None and not current.done():+ return++ async def _write() -> None:+ def _write_bounded() -> None:+ with self._RUNTIME_STATE_WRITE_LIMIT:+ self._write_runtime_state(+ mode=mode,+ language=language,+ channel=channel,+ session_id=session_id,+ project_dir=project_dir,+ )++ await asyncio.to_thread(_write_bounded)++ task = asyncio.create_task(+ _write(),+ name=f"runtime-state-{session_id or 'default'}",+ )+ self._runtime_state_write_task = task++ def _clear(done: asyncio.Task[None]) -> None:+ if self._runtime_state_write_task is done:+ self._runtime_state_write_task = None+ try:+ done.result()+ except asyncio.CancelledError:+ pass+ except Exception:+ logger.debug(+ "[JiuWenSwarmDeepAdapter] async runtime_state write failed",+ exc_info=True,+ )++ task.add_done_callback(_clear)def set_skill_manager(self, skill_manager: SkillManager) -> None:"""Inject shared SkillManager from facade for tool reuse."""@@ -3776,6 +3830,8 @@ class JiuWenSwarmDeepAdapter:# 重索引延时(秒):embedding 配置变更后,延后这段时间再跑一次全量重索引。# 配合 _schedule_memory_reindex 的 debounce,连续改多次只在最后一次后跑一次。_MEMORY_REINDEX_DELAY_SECONDS: float = 5.0+ _MEMORY_REINDEX_KEYS: set[tuple[str, str]] = set()+ _MEMORY_REINDEX_KEYS_LOCK = threading.Lock()@staticmethoddef _embedding_config_fingerprint(config: dict | None) -> str:@@ -3806,11 +3862,23 @@ class JiuWenSwarmDeepAdapter:且 openjiuwen lite 的 INDEX_CACHE 已清(aclose_memory_manager_cache)。这样延时到期时 init_memory_manager_async 会用新配置建新 manager + 新 provider。"""+ workspace = os.path.normcase(os.path.abspath(self._workspace_dir or ""))+ reindex_key = (workspace, self._memory_embedding_fingerprint)+ with self._MEMORY_REINDEX_KEYS_LOCK:+ if reindex_key in self._MEMORY_REINDEX_KEYS:+ logger.info(+ "[JiuWenSwarmDeepAdapter] memory reindex coalesced: workspace=%s",+ workspace,+ )+ return+ self._MEMORY_REINDEX_KEYS.add(reindex_key)if self._memory_reindex_task is not None and not self._memory_reindex_task.done():self._memory_reindex_task.cancel()- self._memory_reindex_task = asyncio.create_task(self._do_memory_reindex())+ self._memory_reindex_task = asyncio.create_task(+ self._do_memory_reindex(reindex_key)+ )- async def _do_memory_reindex(self) -> None:+ async def _do_memory_reindex(self, reindex_key: tuple[str, str]) -> None:try:await asyncio.sleep(self._MEMORY_REINDEX_DELAY_SECONDS)rail = self._memory_rail@@ -3830,6 +3898,9 @@ class JiuWenSwarmDeepAdapter:passexcept Exception as e:logger.warning("[JiuWenSwarmDeepAdapter] memory reindex failed: %s", e)+ finally:+ with self._MEMORY_REINDEX_KEYS_LOCK:+ self._MEMORY_REINDEX_KEYS.discard(reindex_key)async def _get_current_memory_manager(self):"""获取当前 MemoryRail 对应的 memory manager(必要时按新配置重建)。@@ -4574,6 +4645,7 @@ class JiuWenSwarmDeepAdapter:self._session_instance_sub_mode = sub_modeawait self.set_checkpoint()+ await asyncio.sleep(0)self._dreaming_mode = mode if mode and mode.startswith("agent") else "agent"self._instance_overrides = dict(config or {}) if isinstance(config, dict) else {}@@ -4600,6 +4672,7 @@ class JiuWenSwarmDeepAdapter:tool_cards = await self._get_tool_cards(agent_card.id)self._tool_cards = tool_cards+ await asyncio.sleep(0)# 权限护栏由 openjiuwen PermissionInterruptRail + ToolPermissionHost 接管;# 无需初始化 jiuwenswarm 内置 PermissionEngine(已弃用)。@@ -4649,11 +4722,15 @@ class JiuWenSwarmDeepAdapter:completion_timeout=config.get("completion_timeout", 3600.0),)+ await asyncio.sleep(0)await self._instance.ensure_initialized()initial_runtime_workspace = self._project_dir or str(get_default_project_session_workspace_dir())- self._ensure_project_gitignore_agent_history(initial_runtime_workspace)+ await asyncio.to_thread(+ self._ensure_project_gitignore_agent_history,+ initial_runtime_workspace,+ )self._seed_runtime_cwd(initial_runtime_workspace, workspace=initial_runtime_workspace)setattr(self._instance, "_jiuwenswarm_project_dir", initial_runtime_workspace)@@ -4667,6 +4744,7 @@ class JiuWenSwarmDeepAdapter:# 加载已激活的 packages(skills, rails, tools)await self._load_active_packages()+ await asyncio.sleep(0)# 动态加载用户自定义的 Rail 扩展await self.load_user_rails()@@ -5451,7 +5529,7 @@ class JiuWenSwarmDeepAdapter:circuit_breaker_rail = getattr(self, "_circuit_breaker_rail", None)if circuit_breaker_rail is not None:circuit_breaker_rail.set_language(resolved_language)- self._write_runtime_state(+ self._schedule_runtime_state_write(mode=runtime_config.mode,language=resolved_language,channel=resolved_channel,@@ -9310,6 +9388,7 @@ class JiuWenSwarmDeepAdapter:if builtin_on:# 开启记忆new_embed_fp = self._embedding_config_fingerprint(config)+ previous_embed_fp = self._memory_embedding_fingerprintif self._memory_rail is not None:cur_memory_type = is_proactive_memory(mode, config)if self._is_proactive_memory != cur_memory_type:@@ -9347,7 +9426,8 @@ class JiuWenSwarmDeepAdapter:else:logger.info(f"[JiuWenSwarmDeepAdapter] MemoryRail registered for {mode} mode")# 重建后触发延时重索引(debounce),使新 embedding 配置对历史记忆文件生效- self._schedule_memory_reindex()+ if previous_embed_fp and previous_embed_fp != new_embed_fp:+ self._schedule_memory_reindex()elif not builtin_on and self._memory_rail is not None:await self._instance.unregister_rail(self._memory_rail)self._memory_rail = Nonediff --git a/jiuwenswarm/server/runtime/agent_manager.py b/jiuwenswarm/server/runtime/agent_manager.pyindex 52247a80ff..1268c2eca8 100644--- a/jiuwenswarm/server/runtime/agent_manager.py+++ b/jiuwenswarm/server/runtime/agent_manager.py@@ -659,6 +659,12 @@ class AgentManager:if session_id:await self.warm_pool.wait_for_session(session_id)+ async def begin_foreground_chat(self) -> None:+ await self.warm_pool.begin_foreground()++ async def end_foreground_chat(self) -> None:+ await self.warm_pool.end_foreground()+def activate_session_prewarm(self, session_id: str | None) -> None:"""Mark a claimed prewarm workspace as a normal persisted session."""if session_id:diff --git a/jiuwenswarm/server/runtime/agent_warm_pool.py b/jiuwenswarm/server/runtime/agent_warm_pool.pyindex 8cc17041e2..1dbb8431b3 100644--- a/jiuwenswarm/server/runtime/agent_warm_pool.py+++ b/jiuwenswarm/server/runtime/agent_warm_pool.py@@ -49,6 +49,10 @@ class WarmKey:def agent_mode(self) -> str:return "code" if self.work_mode == "code" else "agent"+ @property+ def agent_sub_mode(self) -> str | None:+ return "normal" if self.work_mode == "code" else None+@dataclass(frozen=True, slots=True)class WarmRevision:@@ -74,23 +78,51 @@ class WarmClaim:class AgentWarmPool:- """Own one unclaimed, initialized session per enabled channel/project key."""+ """Own a bounded set of unclaimed, initialized Agent sessions."""- def __init__(self, manager: "AgentManager", *, max_concurrency: int = 2) -> None:+ EXCLUDED_CHANNELS = frozenset({"acp", "a2a"})++ def __init__(+ self,+ manager: "AgentManager",+ *,+ max_concurrency: int = 1,+ max_ready_slots: int = 1,+ max_foreground_concurrency: int = 8,+ background_cooldown_seconds: float = 0.25,+ ) -> None:self._manager = managerself._boot_id = uuid.uuid4().hexself._sequence = 0self._revision = WarmRevision(self._boot_id, "", 0)self._enabled_channels: set[str] = set()+ self._desired: set[WarmKey] = set()self._slots: dict[WarmKey, WarmSlot] = {}self._tasks: dict[WarmKey, asyncio.Task[None]] = {}self._task_revisions: dict[WarmKey, WarmRevision] = {}+ self._task_session_ids: dict[WarmKey, str] = {}+ self._pending: dict[WarmKey, WarmRevision] = {}self._session_tasks: dict[str, asyncio.Task[None]] = {}+ self._promoted_sessions: set[str] = set()self._claimed_pins: dict[str, "JiuWenSwarm"] = {}self._pin_release_tasks: set[asyncio.Task[None]] = set()self._failed: dict[WarmKey, str] = {}self._lock = asyncio.Lock()- self._semaphore = asyncio.Semaphore(max(1, int(max_concurrency)))+ # OpenJiuwen registers tools and resources in process-global managers.+ # Never let speculative and foreground DeepAgent construction mutate+ # those registries concurrently.+ self._initialization_lock = asyncio.Lock()+ self._max_concurrency = max(1, int(max_concurrency))+ self._max_ready_slots = max(1, int(max_ready_slots))+ self._semaphore = asyncio.Semaphore(self._max_concurrency)+ self._foreground_semaphore = asyncio.Semaphore(+ max(1, int(max_foreground_concurrency))+ )+ self._foreground_count = 0+ self._foreground_idle = asyncio.Event()+ self._foreground_idle.set()+ self._background_cooldown_seconds = max(0.0, float(background_cooldown_seconds))+ self._background_pump_task: asyncio.Task[None] | None = Noneself._closed = Falseself._marker_dir = get_agent_sessions_dir() / ".prewarm"self._cleanup_stale_markers()@@ -179,21 +211,23 @@ class AgentWarmPool:has_valid_path = (bool(session_id) and session_dir.parent == sessions_root)- is_uninitialized = session_dir.is_dir() and not (- session_dir / "metadata.json"- ).exists()+ is_uninitialized = (+ session_dir.is_dir()+ and not (session_dir / "metadata.json").exists()+ )if has_valid_path and is_uninitialized:shutil.rmtree(session_dir)marker.unlink(missing_ok=True)except (OSError, ValueError, TypeError):logger.warning("Invalid prewarm marker left in place: %s", marker)- def _desired_keys(self) -> set[WarmKey]:+ def _desired_keys(self, enabled_channels: set[str] | None = None) -> set[WarmKey]:+ channels = (+ self._enabled_channels if enabled_channels is None else enabled_channels+ )projects = list(project_store.list_projects(cache_bust=True))records = [- (p.project_id, p.project_dir, p.work_mode)- for p in projects- if not p.hidden+ (p.project_id, p.project_dir, p.work_mode) for p in projects if not p.hidden]records.extend([@@ -208,10 +242,21 @@ class AgentWarmPool:project_dir=project_dir,work_mode=work_mode,)- for channel in self._enabled_channels+ for channel in channelsfor project_id, project_dir, work_mode in records}+ @staticmethod+ def _key_priority(key: WarmKey) -> tuple[int, int, int, str, str]:+ """Prefer the normal Web work slot for the initial global READY slot."""+ return (+ 0 if key.channel_id == "web" else 1,+ 0 if key.work_mode == "work" else 1,+ 0 if key.project_id == DEFAULT_PROJECT_ID_WORK else 1,+ key.channel_id,+ key.project_id,+ )+async def sync(self,enabled_channels: list[str],@@ -219,12 +264,16 @@ class AgentWarmPool:config: Any,env: Any = None,) -> dict[str, int]:- channels = {- str(channel).strip()- for channel in enabled_channels- if str(channel).strip()- }+ channels: set[str] = set()+ for channel in enabled_channels:+ normalized_channel = str(channel).strip().lower()+ if normalized_channel and normalized_channel not in self.EXCLUDED_CHANNELS:+ channels.add(normalized_channel)revision = self._next_revision(config, env)+ # Project discovery can touch persistent metadata. Keep it outside both+ # the AgentServer event loop and the pool lock, then reconcile against+ # one immutable target snapshot.+ desired = await asyncio.to_thread(self._desired_keys, channels)async with self._lock:if self._closed:return {@@ -234,25 +283,36 @@ class AgentWarmPool:"failed": 0,"stale": 0,}+ if revision.sequence < self._revision.sequence:+ warming_tasks = set(self._tasks.values()) | set(+ self._session_tasks.values()+ )+ return {+ "target": len(self._desired),+ "ready": len(self._slots),+ "warming": len(warming_tasks) + len(self._pending),+ "failed": len(self._failed),+ "stale": 0,+ }config_changed = (self._revision.config_fingerprint != revision.config_fingerprint)self._enabled_channels = channels+ self._desired = desiredself._revision = revision- desired = self._desired_keys()if config_changed:self._failed.clear()else:self._failed = {- key: error- for key, error in self._failed.items()- if key in desired+ key: error for key, error in self._failed.items() if key in desired}- stale_slots = [- slot- for key, slot in list(self._slots.items())- if key not in desired or slot.revision.config_fingerprint != revision.config_fingerprint- ]+ stale_slots: list[WarmSlot] = []+ for key, slot in list(self._slots.items()):+ fingerprint_changed = (+ slot.revision.config_fingerprint != revision.config_fingerprint+ )+ if key not in desired or fingerprint_changed:+ stale_slots.append(slot)for slot in stale_slots:self._slots.pop(slot.key, None)for key, task in list(self._tasks.items()):@@ -266,10 +326,20 @@ class AgentWarmPool:task.cancel()self._tasks.pop(key, None)self._task_revisions.pop(key, None)- for key in desired:+ self._task_session_ids.pop(key, None)+ current_pending: dict[WarmKey, WarmRevision] = {}+ for key, task_revision in self._pending.items():+ fingerprint_matches = (+ task_revision.config_fingerprint == revision.config_fingerprint+ )+ if key in desired and fingerprint_matches:+ current_pending[key] = task_revision+ self._pending = current_pending+ for key in sorted(desired, key=self._key_priority):slot = self._slots.get(key)- if slot is None and key not in self._tasks:- self._schedule_prepare_locked(key, revision)+ if slot is None and key not in self._tasks and key not in self._pending:+ self._enqueue_prepare_locked(key, revision)+ self._pump_background_locked()for slot in stale_slots:asyncio.create_task(self._dispose_slot(slot))return await self.stats()@@ -297,9 +367,97 @@ class AgentWarmPool:if keep_as_slot:self._tasks[key] = taskself._task_revisions[key] = revision+ self._task_session_ids[key] = sidself._session_tasks[sid] = taskreturn sid, task+ def _enqueue_prepare_locked(+ self,+ key: WarmKey,+ revision: WarmRevision,+ *,+ prioritize: bool = False,+ ) -> None:+ """Queue a background slot without creating an unbounded task backlog."""+ if key in self._slots or key in self._tasks or key in self._pending:+ return+ if prioritize:+ self._pending = {key: revision, **self._pending}+ else:+ self._pending[key] = revision++ def _pump_background_locked(self) -> None:+ """Start only the bounded next batch while no user chat is active."""+ if self._closed or self._foreground_count > 0:+ return+ while (+ self._pending+ and len(self._tasks) < self._max_concurrency+ and len(self._slots) + len(self._tasks) < self._max_ready_slots+ ):+ key = next(iter(self._pending))+ revision = self._pending.pop(key)+ current = self._revision+ if (+ revision.boot_id != current.boot_id+ or revision.config_fingerprint != current.config_fingerprint+ or key not in self._desired+ ):+ continue+ self._schedule_prepare_locked(key, revision)++ def _schedule_background_pump_locked(self) -> None:+ """Leave an event-loop window between expensive background sessions."""+ task = self._background_pump_task+ if self._closed or (task is not None and not task.done()):+ return++ async def _delayed_pump() -> None:+ try:+ await asyncio.sleep(self._background_cooldown_seconds)+ async with self._lock:+ self._background_pump_task = None+ self._pump_background_locked()+ except asyncio.CancelledError:+ return++ self._background_pump_task = asyncio.create_task(+ _delayed_pump(), name="agent-prewarm-background-pump"+ )++ async def begin_foreground(self) -> None:+ """Preempt speculative preparation while a real chat is active."""+ cancelled = 0+ async with self._lock:+ self._foreground_count += 1+ self._foreground_idle.clear()+ for task in list(self._tasks.values()):+ if not task.done():+ task.cancel()+ cancelled += 1+ logger.info(+ "Agent prewarm background paused: foreground=%s pending=%s cancelled=%s",+ self._foreground_count,+ len(self._pending),+ cancelled,+ )+ if cancelled:+ # Deliver cancellation before the foreground path starts building a+ # second DeepAgent and touching the shared OpenJiuwen registry.+ await asyncio.sleep(0)++ async def end_foreground(self) -> None:+ """Resume lazy background preparation after the final chat completes."""+ async with self._lock:+ self._foreground_count = max(0, self._foreground_count - 1)+ if self._foreground_count == 0:+ self._foreground_idle.set()+ self._schedule_background_pump_locked()+ logger.info(+ "Agent prewarm background resumed: pending=%s",+ len(self._pending),+ )+async def _prepare(self,key: WarmKey,@@ -311,39 +469,73 @@ class AgentWarmPool:agent: "JiuWenSwarm | None" = Nonepinned = Falsepublished = False+ cancelled = False+ foreground_registered = Falseif keep_as_slot:self._write_marker(session_id, key)+ else:+ await self.begin_foreground()+ foreground_registered = True+ started_at = time.monotonic()try:- async with self._semaphore:- agent = await self._manager.get_agent(- channel_id=key.channel_id,- mode=key.agent_mode,- project_dir=key.project_dir or None,- )- if agent is None:- raise RuntimeError("agent creation returned None")- await agent.prepare_session(- session_id=session_id,- channel_id=key.channel_id,- mode="code.normal" if key.work_mode == "code" else "agent",- project_dir=key.project_dir or None,- )+ semaphore = self._semaphore if keep_as_slot else self._foreground_semaphore+ if keep_as_slot:+ await self._foreground_idle.wait()+ async with semaphore:+ async with self._initialization_lock:+ if keep_as_slot:+ await self._foreground_idle.wait()+ agent = await self._manager.get_agent(+ channel_id=key.channel_id,+ mode=key.agent_mode,+ project_dir=key.project_dir or None,+ sub_mode=key.agent_sub_mode,+ )+ if agent is None:+ raise RuntimeError("agent creation returned None")+ # Yield between root creation and session-heavy setup. If a+ # chat arrived meanwhile, cancellation wins before shared+ # OpenJiuwen resources are mutated again.+ await asyncio.sleep(0)+ if keep_as_slot:+ await self._foreground_idle.wait()+ await agent.prepare_session(+ session_id=session_id,+ channel_id=key.channel_id,+ mode=("code.normal" if key.work_mode == "code" else "agent"),+ project_dir=key.project_dir or None,+ )+ logger.info(+ "Agent prepare completed: session_id=%s foreground=%s duration_ms=%.1f",+ session_id,+ not keep_as_slot,+ (time.monotonic() - started_at) * 1000,+ )if not keep_as_slot:return- self._manager.pin_agent(agent)- pinned = Trueasync with self._lock:+ promoted = session_id in self._promoted_sessionscurrent = self._revisionrevision_changed = (current.boot_id != revision.boot_idor current.config_fingerprint != revision.config_fingerprint)- stale = (- self._closed- or revision_changed- or key not in self._desired_keys()+ stale = not promoted and (+ self._closed or revision_changed or key not in self._desired)- if not stale:+ if promoted:+ self._manager.pin_agent(agent)+ pinned = True+ self._claimed_pins[session_id] = agent+ pin_task = asyncio.create_task(+ self._release_claim_pin_after(session_id, 300),+ name=f"agent-prewarm-claim-pin-timeout-{session_id}",+ )+ self._pin_release_tasks.add(pin_task)+ pin_task.add_done_callback(self._pin_release_tasks.discard)+ elif not stale:+ self._manager.pin_agent(agent)+ pinned = Trueself._slots[key] = WarmSlot(key=key,session_id=session_id,@@ -359,13 +551,16 @@ class AgentWarmPool:)pinned = Falseexcept asyncio.CancelledError:+ cancelled = Trueif agent is not None:await self._dispose_runtime(agent, key.channel_id, session_id, pinned=pinned)raiseexcept Exception as exc:- logger.exception("Agent prewarm failed: key=%s session_id=%s", key, session_id)+ logger.exception(+ "Agent prewarm failed: key=%s session_id=%s", key, session_id+ )if agent is not None:await self._dispose_runtime(agent, key.channel_id, session_id, pinned=pinned@@ -373,15 +568,30 @@ class AgentWarmPool:async with self._lock:self._failed[key] = str(exc)finally:- if keep_as_slot and not published:+ promoted = session_id in self._promoted_sessions+ if keep_as_slot and not published and not promoted:self.clear_marker(session_id)async with self._lock:current_task = asyncio.current_task()if self._tasks.get(key) is current_task:self._tasks.pop(key, None)self._task_revisions.pop(key, None)+ self._task_session_ids.pop(key, None)if self._session_tasks.get(session_id) is current_task:self._session_tasks.pop(session_id, None)+ self._promoted_sessions.discard(session_id)+ if cancelled and keep_as_slot:+ fingerprint_matches = (+ revision.config_fingerprint == self._revision.config_fingerprint+ )+ if key in self._desired and fingerprint_matches:+ self._enqueue_prepare_locked(+ key, self._revision, prioritize=True+ )+ if keep_as_slot:+ self._schedule_background_pump_locked()+ if foreground_registered:+ await self.end_foreground()async def claim(self, key: WarmKey) -> WarmClaim:if key.is_swarm:@@ -389,7 +599,7 @@ class AgentWarmPool:async with self._lock:if self._closed:raise RuntimeError("agent warm pool is closed")- is_desired = key in self._desired_keys()+ is_desired = key in self._desiredslot = self._slots.pop(key, None)if slot is not None:self._claimed_pins[slot.session_id] = slot.agent@@ -400,28 +610,43 @@ class AgentWarmPool:self._pin_release_tasks.add(pin_task)pin_task.add_done_callback(self._pin_release_tasks.discard)if key not in self._tasks:- self._schedule_prepare_locked(key, self._revision)+ self._enqueue_prepare_locked(key, self._revision, prioritize=True)return WarmClaim(slot.session_id, True, "ready")if key in self._tasks:- # Keep the target slot intact and initialize this claimed session- # independently; its per-session adapter lock deduplicates chat.send.- sid, _ = self._schedule_prepare_locked(- key, self._revision, keep_as_slot=False- )+ # The speculative instance already owns its final Session ID.+ # Promote that exact task instead of creating a competing+ # foreground DeepAgent against the shared tool registry.+ task = self._tasks.pop(key)+ self._task_revisions.pop(key, None)+ sid = self._task_session_ids.pop(key)+ self._promoted_sessions.add(sid)+ self._session_tasks[sid] = task+ if is_desired:+ self._enqueue_prepare_locked(key, self._revision, prioritize=True)else:sid, _ = self._schedule_prepare_locked(key, self._revision, keep_as_slot=False)if is_desired:- self._schedule_prepare_locked(key, self._revision)+ self._enqueue_prepare_locked(key, self._revision, prioritize=True)return WarmClaim(sid, False, "warming")async def wait_for_session(self, session_id: str) -> None:async with self._lock:task = self._session_tasks.get(str(session_id))+ wait_started = time.monotonic()try:if task is not None:+ logger.info(+ "Waiting for foreground session preparation: session_id=%s",+ session_id,+ )await asyncio.shield(task)+ logger.info(+ "Foreground session preparation ready: session_id=%s wait_ms=%.1f",+ session_id,+ (time.monotonic() - wait_started) * 1000,+ )finally:async with self._lock:pinned_agent = self._claimed_pins.pop(str(session_id), None)@@ -462,33 +687,46 @@ class AgentWarmPool:async def stats(self) -> dict[str, int]:async with self._lock:- desired = self._desired_keys()+ warming_tasks = set(self._tasks.values()) | set(+ self._session_tasks.values()+ )return {- "target": len(desired),+ "target": len(self._desired),"ready": len(self._slots),- "warming": len(self._tasks),+ "warming": len(warming_tasks) + len(self._pending),"failed": len(self._failed),- "stale": max(0, len(self._slots) - len(desired)),+ "stale": max(0, len(self._slots) - len(self._desired)),}async def close(self) -> None:async with self._lock:self._closed = True+ self._foreground_idle.set()tasks = list({*self._tasks.values(),*self._session_tasks.values(),*self._pin_release_tasks,+ *(+ [self._background_pump_task]+ if self._background_pump_task is not None+ else []+ ),})slots = list(self._slots.values())claimed_agents = list(self._claimed_pins.values())self._tasks.clear()self._task_revisions.clear()+ self._task_session_ids.clear()+ self._pending.clear()+ self._desired.clear()self._session_tasks.clear()+ self._promoted_sessions.clear()self._slots.clear()self._claimed_pins.clear()self._pin_release_tasks.clear()+ self._background_pump_task = Nonefor task in tasks:task.cancel()if tasks:diff --git a/tests/unit_tests/agentserver/test_agent_warm_pool.py b/tests/unit_tests/agentserver/test_agent_warm_pool.pyindex 0fc21a9597..abd2f7f39b 100644--- a/tests/unit_tests/agentserver/test_agent_warm_pool.py+++ b/tests/unit_tests/agentserver/test_agent_warm_pool.py@@ -1,6 +1,7 @@from __future__ import annotationsimport asyncio+import threadingfrom pathlib import Pathimport pytest@@ -25,12 +26,33 @@ class _FakeRootAgent:return True+class _ControlledRootAgent(_FakeRootAgent):+ def __init__(self) -> None:+ super().__init__()+ self.started: list[str] = []+ self.cancelled: list[str] = []+ self.gates: dict[str, asyncio.Event] = {}++ async def prepare_session(self, *, session_id: str, **_kwargs) -> None:+ gate = asyncio.Event()+ self.gates[session_id] = gate+ self.started.append(session_id)+ try:+ await gate.wait()+ except asyncio.CancelledError:+ self.cancelled.append(session_id)+ raise+ self.prepared.append(session_id)++class _FakeManager:def __init__(self, agent: _FakeRootAgent) -> None:self.agent = agentself.pins = 0+ self.get_agent_calls: list[dict] = []- async def get_agent(self, **_kwargs):+ async def get_agent(self, **kwargs):+ self.get_agent_calls.append(kwargs)return self.agentdef pin_agent(self, _agent) -> None:@@ -75,15 +97,43 @@ def test_warm_key_normalizes_project_directory(tmp_path: Path) -> None:assert key.channel_id == "web"assert key.project_dir == str(tmp_path.resolve()).lower()assert key.agent_mode == "code"+ assert key.agent_sub_mode == "normal"@pytest.mark.asyncio-async def test_one_ready_slot_per_key_and_atomic_claim(isolated_pool) -> None:+async def test_code_prewarm_uses_same_manager_cache_identity_as_code_chat(+ isolated_pool,+) -> None:+ pool = isolated_pool(_FakeRootAgent())+ key = pool.make_key(+ channel_id="web",+ project_id="project-code",+ project_dir="/tmp/code-project",+ work_mode="code",+ )++ claim = await pool.claim(key)+ await pool.wait_for_session(claim.session_id)++ assert pool._manager.get_agent_calls == [+ {+ "channel_id": "web",+ "mode": "code",+ "project_dir": key.project_dir,+ "sub_mode": "normal",+ }+ ]+ await pool.end_foreground()+ await pool.close()+++async def test_pool_keeps_one_ready_slot_total_and_claim_is_atomic(isolated_pool) -> None:agent = _FakeRootAgent()pool = isolated_pool(agent)stats = await pool.sync(["web"], config={"model": "a"})assert stats["target"] == 2- await _wait_until(lambda: len(pool._slots) == 2)+ await _wait_until(lambda: len(pool._slots) == 1)work_key = pool.make_key(channel_id="web",@@ -95,8 +145,100 @@ async def test_one_ready_slot_per_key_and_atomic_claim(isolated_pool) -> None:assert len({claim.session_id for claim in claims}) == 2assert sum(claim.prewarm_hit for claim in claims) == 1assert {claim.prewarm_status for claim in claims} == {"ready", "warming"}+ await pool.end_foreground()await _wait_until(lambda: work_key in pool._slots)assert len([key for key in pool._slots if key == work_key]) == 1+ assert len(pool._slots) == 1+ await pool.close()+++async def test_sync_filters_non_user_protocol_channels(isolated_pool) -> None:+ pool = isolated_pool(_FakeRootAgent())+ stats = await pool.sync(["web", "acp", "a2a"], config={"model": "a"})+ assert stats["target"] == 2+ assert pool._enabled_channels == {"web"}+ await pool.close()+++async def test_foreground_bypasses_background_and_pauses_lazy_dispatch(+ monkeypatch, tmp_path: Path+) -> None:+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.agent_warm_pool.get_agent_sessions_dir",+ lambda: tmp_path,+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.agent_warm_pool.project_store.list_projects",+ lambda **_kwargs: [],+ )+ agent = _ControlledRootAgent()+ pool = AgentWarmPool(_FakeManager(agent), max_concurrency=1)+ await pool.sync(["web"], config={"model": "a"})+ await _wait_until(lambda: len(agent.started) == 1)+ assert len(pool._tasks) == 1+ assert len(pool._pending) == 1++ await pool.begin_foreground()+ key = pool.make_key(+ channel_id="web",+ project_id="default",+ project_dir="",+ work_mode="work",+ )+ claim = await pool.claim(key)+ assert claim.prewarm_hit is False+ await _wait_until(lambda: len(agent.started) == 2)++ background_id, foreground_id = agent.started+ await _wait_until(lambda: background_id in agent.cancelled)+ assert len(agent.started) == 2++ agent.gates[foreground_id].set()+ await pool.wait_for_session(foreground_id)+ assert len(agent.started) == 2++ await pool.end_foreground()+ await _wait_until(lambda: len(agent.started) == 3)+ for gate in agent.gates.values():+ gate.set()+ await pool.close()+++async def test_claim_promotes_matching_background_task_without_duplicate_prepare(+ monkeypatch, tmp_path: Path+) -> None:+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.agent_warm_pool.get_agent_sessions_dir",+ lambda: tmp_path,+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.agent_warm_pool.project_store.list_projects",+ lambda **_kwargs: [],+ )+ agent = _ControlledRootAgent()+ pool = AgentWarmPool(_FakeManager(agent), max_concurrency=1)+ await pool.sync(["web"], config={"model": "a"})+ await _wait_until(lambda: len(agent.started) == 1)+ background_id = agent.started[0]+ key = pool.make_key(+ channel_id="web",+ project_id="default",+ project_dir="",+ work_mode="work",+ )++ claim = await pool.claim(key)++ assert claim.session_id == background_id+ assert claim.prewarm_hit is False+ assert claim.prewarm_status == "warming"+ assert len(agent.started) == 1+ agent.gates[background_id].set()+ await pool.wait_for_session(background_id)+ assert len(agent.started) == 1await pool.close()@@ -105,18 +247,52 @@ async def test_config_revision_replaces_unclaimed_slots(isolated_pool) -> None:agent = _FakeRootAgent()pool = isolated_pool(agent)await pool.sync(["web"], config={"model": "old"})- await _wait_until(lambda: len(pool._slots) == 2)+ await _wait_until(lambda: len(pool._slots) == 1)old_ids = {slot.session_id for slot in pool._slots.values()}await pool.sync(["web"], config={"model": "new"})await _wait_until(- lambda: len(pool._slots) == 2+ lambda: len(pool._slots) == 1and not old_ids.intersection(slot.session_id for slot in pool._slots.values()))assert old_ids.issubset(set(agent.cleaned))await pool.close()+async def test_slow_older_sync_cannot_overwrite_newer_revision(+ isolated_pool, monkeypatch+) -> None:+ pool = isolated_pool(_FakeRootAgent())+ original_desired_keys = pool._desired_keys+ first_started = threading.Event()+ release_first = threading.Event()+ call_count = 0+ call_lock = threading.Lock()++ def _controlled_desired_keys(channels):+ nonlocal call_count+ with call_lock:+ call_count += 1+ call_number = call_count+ if call_number == 1:+ first_started.set()+ assert release_first.wait(timeout=5)+ return original_desired_keys(channels)++ monkeypatch.setattr(pool, "_desired_keys", _controlled_desired_keys)+ older = asyncio.create_task(pool.sync(["web"], config={"model": "old"}))+ await asyncio.wait_for(asyncio.to_thread(first_started.wait), timeout=1)+ await pool.sync(["web"], config={"model": "new"})+ release_first.set()+ await older++ assert pool._revision.config_fingerprint == pool.config_fingerprint(+ {"model": "new"}+ )+ await pool.close()++@pytest.mark.asyncioasync def test_failed_prepare_never_becomes_ready(isolated_pool) -> None:pool = isolated_pool(_FakeRootAgent(fail=True))@@ -124,7 +300,8 @@ async def test_failed_prepare_never_becomes_ready(isolated_pool) -> None:await _wait_until(lambda: not pool._tasks)stats = await pool.stats()assert stats["ready"] == 0- assert stats["failed"] == 2+ assert stats["failed"] == 1+ assert stats["warming"] == 1await pool.close()@@ -132,7 +309,7 @@ async def test_failed_prepare_never_becomes_ready(isolated_pool) -> None:async def test_claim_marker_survives_until_metadata_activation(isolated_pool) -> None:pool = isolated_pool(_FakeRootAgent())await pool.sync(["web"], config={"model": "ready"})- await _wait_until(lambda: len(pool._slots) == 2)+ await _wait_until(lambda: len(pool._slots) == 1)key = pool.make_key(channel_id="web",project_id="default",diff --git a/tests/unit_tests/agentserver/test_agentserver_acp.py b/tests/unit_tests/agentserver/test_agentserver_acp.pyindex 184315836f..6dd5f686d4 100644--- a/tests/unit_tests/agentserver/test_agentserver_acp.py+++ b/tests/unit_tests/agentserver/test_agentserver_acp.py@@ -731,8 +731,6 @@ async def test_handle_initialize_uses_agent_manager_capabilities(monkeypatch):"ok": True,}]--@pytest.mark.asyncioasync def test_handle_initialize_falls_back_to_default_capabilities(monkeypatch):server = AgentWebSocketServerHarness()@@ -921,6 +919,12 @@ async def test_handle_session_create_injected_default_work_mode_does_not_mismatc"ok": True,}]+ assert request.params["mode"] == "code.normal"+ from jiuwenswarm.server.runtime.session.session_metadata import get_session_metadata++ metadata = get_session_metadata("sess_code_project", cache_bust=True)+ assert metadata["mode"] == "code.normal"+ assert metadata["work_mode"] == "code"@pytest.mark.asynciodiff --git a/tests/unit_tests/agentserver/test_agentserver_modes.py b/tests/unit_tests/agentserver/test_agentserver_modes.pyindex 9a65ca4bd7..6a005dcec7 100644--- a/tests/unit_tests/agentserver/test_agentserver_modes.py+++ b/tests/unit_tests/agentserver/test_agentserver_modes.py@@ -61,6 +61,26 @@ def test_resolve_agent_request_mode_accepts_primary_and_dotted_modes(raw_mode, eassert agent_ws_server_module.resolve_agent_request_mode(raw_mode) == expected+ ("raw_mode", "work_mode", "expected"),+ [+ ("agent", "code", ("code", "normal", "code.normal")),+ ("code.normal", "work", ("agent", None, "agent")),+ ("code.plan", "code", ("code", "plan", "code.plan")),+ ("team", "code", ("team", None, "team")),+ ],+)+def test_resolve_agent_request_mode_aligns_single_agent_with_work_mode(+ raw_mode,+ work_mode,+ expected,+):+ assert agent_ws_server_module.resolve_agent_request_mode(+ raw_mode,+ work_mode=work_mode,+ ) == expected++def test_team_plan_params_are_team_mode():from jiuwenswarm.server.utils.utils import is_team_paramsdiff --git a/tests/unit_tests/agentserver/test_plan_mode_orchestration.py b/tests/unit_tests/agentserver/test_plan_mode_orchestration.pyindex ceffcd5daf..10b983155c 100644--- a/tests/unit_tests/agentserver/test_plan_mode_orchestration.py+++ b/tests/unit_tests/agentserver/test_plan_mode_orchestration.py@@ -71,6 +71,43 @@ async def test_prepare_code_mode_chat_turn_resolves_mode_and_agent() -> None:manager.wait_for_session_prewarm.assert_awaited_once_with(session_id)+async def test_prepare_chat_normalizes_agent_request_for_code_workspace() -> None:+ agent = MagicMock()+ manager = MagicMock()+ manager.get_agent = AsyncMock(return_value=agent)+ manager.wait_for_session_prewarm = AsyncMock()+ server = AgentWebSocketServer.__new__(AgentWebSocketServer)+ server._agent_manager = manager+ request = _chat_request(+ "sess_code_workspace",+ mode="agent",+ extra_params={"work_mode": "code", "project_dir": "/tmp/code-project"},+ )++ with patch(+ "jiuwenswarm.server.runtime.session.session_metadata.get_session_metadata",+ return_value={},+ ), patch.object(+ agent_ws_server_module,+ "_sync_chat_request_metadata",+ return_value="/tmp/code-project",+ ):+ mode, sub_mode, resolved_agent = await server._prepare_code_mode_chat_turn(+ request,+ "web",+ )++ assert (mode, sub_mode, resolved_agent) == ("code", "normal", agent)+ assert request.params["mode"] == "code.normal"+ manager.get_agent.assert_awaited_once_with(+ channel_id="web",+ mode="code",+ project_dir="/tmp/code-project",+ sub_mode="normal",+ )++@pytest.mark.asyncioasync def test_prepare_team_chat_turn_propagates_locked_project_dir() -> None:"""The session-locked project dir reaches TeamSpec request metadata.diff --git a/tests/unit_tests/agentserver/test_ws_send.py b/tests/unit_tests/agentserver/test_ws_send.pyindex 01c1580386..d8527e2628 100644--- a/tests/unit_tests/agentserver/test_ws_send.py+++ b/tests/unit_tests/agentserver/test_ws_send.py@@ -149,6 +149,19 @@ async def test_stream_stops_after_oversized_chunk_is_replaced(monkeypatch):server._session_stream_tasks = {}server._is_stateless_method_request = lambda request: True+ class ForegroundManager:+ def __init__(self):+ self.events = []++ async def begin_foreground_chat(self):+ self.events.append("begin")++ async def end_foreground_chat(self):+ self.events.append("end")++ foreground_manager = ForegroundManager()+ server._agent_manager = foreground_manager+async def get_agent(channel_id):return FakeAgent()@@ -181,6 +194,7 @@ async def test_stream_stops_after_oversized_chunk_is_replaced(monkeypatch):await server._handle_stream(FakeWebSocket(), request, asyncio.Lock())assert send_count == 1+ assert foreground_manager.events == ["begin", "end"]def test_agent_ws_server_has_no_direct_websocket_send_calls():diff --git a/tests/unit_tests/server/test_agent_history_gitignore.py b/tests/unit_tests/server/test_agent_history_gitignore.pyindex 49628ed2fd..da736ff955 100644--- a/tests/unit_tests/server/test_agent_history_gitignore.py+++ b/tests/unit_tests/server/test_agent_history_gitignore.py@@ -1,4 +1,6 @@+import asyncioimport subprocess+import threadingfrom pathlib import Pathimport pytest@@ -11,6 +13,82 @@ def _git(repo: Path, *args: str) -> None:subprocess.run(["git", *args], cwd=repo, check=True, capture_output=True, text=True)+async def test_runtime_state_git_probe_is_non_blocking_and_coalesced(monkeypatch):+ adapter = JiuWenSwarmDeepAdapter()+ started = threading.Event()+ release = threading.Event()+ calls = 0++ def _slow_write(**_kwargs) -> None:+ nonlocal calls+ calls += 1+ started.set()+ assert release.wait(timeout=5)++ monkeypatch.setattr(adapter, "_write_runtime_state", _slow_write)+ adapter._schedule_runtime_state_write(+ mode="agent",+ language="zh",+ channel="web",+ session_id="web_runtime_state",+ project_dir=None,+ )+ await asyncio.wait_for(asyncio.to_thread(started.wait), timeout=1)+ first_task = adapter._runtime_state_write_task+ assert first_task is not None and not first_task.done()++ adapter._schedule_runtime_state_write(+ mode="agent",+ language="zh",+ channel="web",+ session_id="web_runtime_state",+ project_dir=None,+ )+ assert adapter._runtime_state_write_task is first_task+ assert calls == 1++ release.set()+ await asyncio.wait_for(first_task, timeout=1)+++async def test_memory_reindex_is_singleflight_per_workspace_and_config(+ monkeypatch, tmp_path+):+ first = JiuWenSwarmDeepAdapter()+ second = JiuWenSwarmDeepAdapter()+ for adapter in (first, second):+ adapter._workspace_dir = str(tmp_path)+ adapter._memory_embedding_fingerprint = "embed-v2"+ started = asyncio.Event()+ release = asyncio.Event()+ calls = 0++ async def _slow_reindex(self, key):+ nonlocal calls+ calls += 1+ started.set()+ try:+ await release.wait()+ finally:+ with self._MEMORY_REINDEX_KEYS_LOCK:+ self._MEMORY_REINDEX_KEYS.discard(key)++ JiuWenSwarmDeepAdapter._MEMORY_REINDEX_KEYS.clear()+ monkeypatch.setattr(JiuWenSwarmDeepAdapter, "_do_memory_reindex", _slow_reindex)+ first._schedule_memory_reindex()+ second._schedule_memory_reindex()+ await asyncio.wait_for(started.wait(), timeout=1)++ assert calls == 1+ assert first._memory_reindex_task is not None+ assert second._memory_reindex_task is None++ release.set()+ await asyncio.wait_for(first._memory_reindex_task, timeout=1)++def test_ensure_project_gitignore_agent_history_updates_repo_root(tmp_path):repo = tmp_path / "repo"subdir = repo / "pkg"