Skip to content

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

feat(rails): 新增可插拔的永续对话护栏

kaichengs9e91bf293a04
diff --git a/jiuwenswarm/agents/harness/common/rails/eternal_conversation/__init__.py b/jiuwenswarm/agents/harness/common/rails/eternal_conversation/__init__.py
new file mode 100644
index 0000000000..87844b29be
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/rails/eternal_conversation/__init__.py
@@ -0,0 +1,6 @@
+"""Eternal-conversation Rail public surface."""
+
+from .rail import EternalConversationRail
+from .registry import close_all_session_coordinators
+
+__all__ = ["EternalConversationRail", "close_all_session_coordinators"]
diff --git a/jiuwenswarm/agents/harness/common/rails/eternal_conversation/background_agents.py b/jiuwenswarm/agents/harness/common/rails/eternal_conversation/background_agents.py
new file mode 100644
index 0000000000..6472a3ec0d
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/rails/eternal_conversation/background_agents.py
@@ -0,0 +1,138 @@
+"""Isolated model runners for Extractor (background 1) and Builder (background 2)."""
+
+from __future__ import annotations
+
+import json
+from typing import Any, Callable
+
+from openjiuwen.core.foundation.llm.schema.message import SystemMessage, UserMessage
+
+from .evidence import EvidenceWriter, jsonable
+
+
+MAX_BACKGROUND_ATTEMPTS = 6
+MAX_RETRY_RESPONSE_CHARS = 16_000
+
+RETRY_CHECKLIST = """
+Rebuild the complete JSON object from scratch; do not patch only the field named in the error.
+Before returning, validate every contract rule again:
+- emit exactly one strict JSON object with double-quoted keys and strings;
+- JSON-escape backslashes (especially Windows paths), quotes, and control characters;
+- include all six Snapshot arrays; use at most 4/4/6/4/4/6 items respectively;
+- keep every Snapshot item at most 220 characters (a safety margin below the hard limit);
+- use at most four changed_uts; every upsert content must be at most 650 characters;
+- every changed_uts action is exactly "upsert" or "retire" (never "update");
+- every upsert has 1-4 queries and 1-3 must_include strings;
+- every must_include string appears verbatim in its UT content;
+- priority is an integer from 0 through 100.
+Do not add Markdown fences or commentary outside the JSON object.
+""".strip()
+
+
+def _content_text(value: Any) -> str:
+ content = getattr(value, "content", value)
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ parts: list[str] = []
+ for item in content:
+ if isinstance(item, str):
+ parts.append(item)
+ elif isinstance(item, dict):
+ parts.append(str(item.get("text") or item.get("content") or ""))
+ else:
+ parts.append(str(item))
+ return "\n".join(parts)
+ return str(content or "")
+
+
+def _json_object(text: str) -> dict[str, Any]:
+ start = text.find("{")
+ end = text.rfind("}")
+ if start < 0 or end < start:
+ raise ValueError("background Agent did not return a JSON object")
+ value = json.loads(text[start:end + 1])
+ if not isinstance(value, dict):
+ raise ValueError("background Agent JSON must be an object")
+ return value
+
+
+class BackgroundAgentRunner:
+ def __init__(self, model_supplier: Callable[[], Any], evidence: EvidenceWriter) -> None:
+ self._model_supplier = model_supplier
+ self._evidence = evidence
+
+ def set_model_supplier(self, model_supplier: Callable[[], Any]) -> None:
+ """Rebind after a channel recreates its session-scoped Adapter."""
+ self._model_supplier = model_supplier
+
+ async def call_json(
+ self,
+ *,
+ role: str,
+ system_prompt: str,
+ request: dict[str, Any],
+ validate: Callable[[dict[str, Any]], None] | None = None,
+ ) -> dict[str, Any]:
+ model = self._model_supplier()
+ if model is None:
+ raise RuntimeError("eternal-conversation background model is unavailable")
+ original_prompt = json.dumps(request, ensure_ascii=False)
+ prompt = original_prompt
+ last_error: Exception | None = None
+ for attempt in range(1, MAX_BACKGROUND_ATTEMPTS + 1):
+ response_text: str | None = None
+ usage: Any = None
+ try:
+ response = await model.invoke(
+ [SystemMessage(content=system_prompt), UserMessage(content=prompt)],
+ temperature=0,
+ )
+ response_text = _content_text(response)
+ usage = jsonable(getattr(response, "usage_metadata", None))
+ parsed = _json_object(response_text)
+ if validate is not None:
+ validate(parsed)
+ await self._evidence.append_agent_history(
+ role,
+ {
+ "attempt": attempt,
+ "system_prompt": system_prompt,
+ "request": request,
+ "response": response_text,
+ "usage": usage,
+ "status": "accepted",
+ },
+ )
+ return parsed
+ except Exception as exc:
+ last_error = exc
+ await self._evidence.append_agent_history(
+ role,
+ {
+ "attempt": attempt,
+ "system_prompt": system_prompt,
+ "request": request,
+ "response": response_text,
+ "usage": usage,
+ "status": "rejected",
+ "error_type": type(exc).__name__,
+ "error": str(exc),
+ },
+ )
+ prompt = (
+ original_prompt
+ + "\n\nYour previous response was invalid. Here is the exact previous response"
+ + " (possibly truncated):\n"
+ + (response_text or "<no response>")[:MAX_RETRY_RESPONSE_CHARS]
+ + "\n\nValidation error: "
+ + str(exc)
+ + "\n"
+ + RETRY_CHECKLIST
+ )
+ if last_error is None:
+ raise RuntimeError("background Agent exhausted retries without an error")
+ raise last_error
+
+
+__all__ = ["BackgroundAgentRunner"]
diff --git a/jiuwenswarm/agents/harness/common/rails/eternal_conversation/coordinator.py b/jiuwenswarm/agents/harness/common/rails/eternal_conversation/coordinator.py
new file mode 100644
index 0000000000..c7aa642787
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/rails/eternal_conversation/coordinator.py
@@ -0,0 +1,618 @@
+"""Session-scoped Extractor/Builder scheduling and atomic publication."""
+
+from __future__ import annotations
+
+import asyncio
+import contextvars
+import hashlib
+import json
+from pathlib import Path
+from typing import Any, Callable
+from weakref import WeakSet
+
+from .background_agents import BackgroundAgentRunner
+from .evidence import (
+ EvidenceWriter,
+ read_json,
+ resolve_evidence_blobs,
+ utc_now,
+ write_json_atomic,
+)
+from .memory_cli import DynamicMemoryGateway
+from .prompts import BUILDER_SYSTEM_PROMPT, EXTRACTOR_SYSTEM_PROMPT, prompt_hashes
+
+
+SNAPSHOT_LIMITS = {
+ "resident_memory": 4,
+ "recent_context": 4,
+ "current_state": 6,
+ "completed": 4,
+ "next_actions": 4,
+ "constraints": 6,
+}
+
+# A lagging worker must never turn many completed foreground tasks into one
+# unbounded model request. Four natural-task boundaries preserve throughput
+# while keeping each extraction independently retryable and auditable.
+MAX_TASKS_PER_EXTRACTION = 4
+PROTOCOL_STRING_INLINE_LIMIT = 2048
+PROTOCOL_CONTAINER_INLINE_LIMIT = 256 * 1024
+FROZEN_WORKING_MEMORY_INLINE_LIMIT = 512 * 1024
+
+
+def _compact_protocol_value(value: Any) -> Any:
+ """Bound protocol-heavy evidence without interpreting its semantics.
+
+ Raw History remains byte-for-byte reconstructable. The semantic Agent's
+ view keeps the exact object shape and all small scalar metadata, while a
+ large protocol string is represented by an exact digest and byte count.
+ This prevents tool output, write payloads, and repeated model responses
+ from consuming a model's entire context window.
+ """
+ if isinstance(value, str):
+ encoded = value.encode("utf-8")
+ if len(encoded) <= PROTOCOL_STRING_INLINE_LIMIT:
+ return value
+ return {
+ "$raw_history_content": True,
+ "sha256": hashlib.sha256(encoded).hexdigest(),
+ "utf8_bytes": len(encoded),
+ }
+ if isinstance(value, dict):
+ return {str(key): _compact_protocol_value(item) for key, item in value.items()}
+ if isinstance(value, list):
+ return [_compact_protocol_value(item) for item in value]
+ return value
+
+
+def _compact_protocol_container(value: Any) -> Any:
+ """Content-address an oversized aggregate while Raw History keeps it exact."""
+ if not isinstance(value, (dict, list)):
+ return _compact_protocol_value(value)
+ encoded = json.dumps(
+ value,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ default=str,
+ ).encode("utf-8")
+ if len(encoded) <= PROTOCOL_CONTAINER_INLINE_LIMIT:
+ return value
+ return {
+ "$raw_history_container": True,
+ "sha256": hashlib.sha256(encoded).hexdigest(),
+ "utf8_bytes": len(encoded),
+ "item_count": len(value),
+ }
+
+
+def _bound_frozen_working_memory(events: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Keep semantic boundary records plus a complete structural ledger when oversized."""
+ encoded = json.dumps(
+ events,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ default=str,
+ ).encode("utf-8")
+ if len(encoded) <= FROZEN_WORKING_MEMORY_INLINE_LIMIT:
+ return events
+ boundary_types = {
+ "task-started",
+ "user-message",
+ "task-finished",
+ "context-replaced",
+ }
+ boundary_events = [event for event in events if event.get("type") in boundary_types]
+ ledger = [
+ {
+ "cursor": event.get("cursor"),
+ "type": event.get("type"),
+ "task_id": event.get("task_id"),
+ "hash": event.get("hash"),
+ }
+ for event in events
+ ]
+ return [
+ *boundary_events,
+ {
+ "type": "structural-event-ledger",
+ "payload": {
+ "event_count": len(events),
+ "events": ledger,
+ "compacted_view_sha256": hashlib.sha256(encoded).hexdigest(),
+ "compacted_view_utf8_bytes": len(encoded),
+ "complete_raw_history_path": "raw-history/events.jsonl",
+ },
+ },
+ ]
+
+
+def _tool_inventory(value: Any) -> list[str]:
+ """Return tool identifiers only; schemas remain in the complete Raw History."""
+ if not isinstance(value, list):
+ return []
+ names: list[str] = []
+ for item in value:
+ if isinstance(item, str):
+ name = item
+ elif isinstance(item, dict):
+ function = item.get("function")
+ name = str(
+ item.get("name")
+ or (function.get("name") if isinstance(function, dict) else "")
+ or ""
+ )
+ else:
+ name = str(getattr(item, "name", "") or "")
+ if name and name not in names:
+ names.append(name)
+ return names
+
+
+def _validate_extractor(value: dict[str, Any]) -> None:
+ snapshot = value.get("snapshot")
+ if not isinstance(snapshot, dict):
+ raise ValueError("extractor snapshot must be an object")
+ for field, limit in SNAPSHOT_LIMITS.items():
+ items = snapshot.get(field)
+ if not isinstance(items, list) or not all(isinstance(item, str) for item in items):
+ raise ValueError(f"snapshot.{field} must be a string list")
+ if len(items) > limit:
+ raise ValueError(
+ f"snapshot.{field} has {len(items)} items; hard limit is {limit}. "
+ f"Merge or remove {len(items) - limit} item(s)."
+ )
+ for index, item in enumerate(items):
+ if len(item) > 280:
+ raise ValueError(
+ f"snapshot.{field}[{index}] has {len(item)} characters; hard limit is 280. "
+ "Rewrite that item to at most 220 characters without dropping its durable facts."
+ )
+ changes = value.get("changed_uts")
+ if not isinstance(changes, list) or len(changes) > 4:
+ raise ValueError("changed_uts must contain at most four items")
+ for change in changes:
+ if not isinstance(change, dict):
+ raise ValueError("each UT change must be an object")
+ action = change.get("action", "upsert")
+ if action not in {"upsert", "retire"}:
+ raise ValueError("UT action must be upsert or retire")
+ if action == "retire":
+ if not str(change.get("id") or "").strip():
+ raise ValueError("retire requires id")
+ continue
+ content = change.get("content")
+ queries = change.get("queries")
+ must_include = change.get("must_include")
+ if not isinstance(content, str) or not content.strip() or len(content) > 700:
+ raise ValueError("UT content must be a non-empty string of at most 700 characters")
+ if not isinstance(queries, list) or not queries or len(queries) > 4:
+ raise ValueError("UT queries must contain one to four items")
+ if not isinstance(must_include, list) or not must_include or len(must_include) > 3:
+ raise ValueError("UT must_include must contain one to three items")
+ for phrase in must_include:
+ if not isinstance(phrase, str) or phrase not in content:
+ raise ValueError("every must_include phrase must be an exact content substring")
+
+
+def _validate_builder(value: dict[str, Any]) -> None:
+ if not isinstance(value.get("approved"), bool):
+ raise ValueError("builder approved must be boolean")
+ if not isinstance(value.get("diagnostics"), list):
+ raise ValueError("builder diagnostics must be a list")
+
+
+def _normalize_changes(
+ changes: list[dict[str, Any]], session_id: str, evidence_ref: str
+) -> list[dict[str, Any]]:
+ """Fill structural ownership fields without changing Agent-authored semantics."""
+ normalized: list[dict[str, Any]] = []
+ for item in changes:
+ value = dict(item)
+ if value.get("action", "upsert") == "upsert":
+ value["action"] = "upsert"
+ value["source"] = session_id
+ value["evidence_refs"] = [evidence_ref]
+ value.setdefault("tags", [])
+ value.setdefault("memory_id", f"memory-{value.get('id')}")
+ normalized.append(value)
+ return normalized
+
+
+def _raw_range(
+ path: Path,
+ start: int,
+ end: int,
+ *,
+ max_finished_tasks: int = MAX_TASKS_PER_EXTRACTION,
+) -> list[dict[str, Any]]:
+ result: list[dict[str, Any]] = []
+ finished_tasks = 0
+ try:
+ with path.open("r", encoding="utf-8") as handle:
+ for line in handle:
+ if not line.strip():
+ continue
+ event = resolve_evidence_blobs(json.loads(line), path.parent)
+ cursor = int(event.get("cursor") or 0)
+ if start <= cursor <= end:
+ result.append(event)
+ if event.get("type") == "task-finished":
+ finished_tasks += 1
+ if finished_tasks >= max_finished_tasks:
+ break
+ except FileNotFoundError:
+ pass
+ return result
+
+
+def _extractor_evidence(events: list[dict[str, Any]]) -> dict[str, Any]:
+ """Build a non-semantic, bounded view over a frozen Raw History range.
+
+ Every model-visible envelope contains the whole accumulated message list,
+ so copying every envelope into the Extractor prompt repeats the same
+ context many times. Raw History remains untouched. The Extractor gets
+ the latest exact Final Visible Context, every non-envelope event, and an
+ envelope ledger retaining each response/status/usage/hash. This follows
+ the architecture's semantic-view/evidence-view split without asking the
+ Harness to decide what should be remembered.
+ """
+ compact_events: list[dict[str, Any]] = []
+ latest_visible: dict[str, Any] | None = None
+ envelope_count = 0
+ for event in events:
+ if event.get("type") != "model-visible-envelope":
+ if event.get("type") in {"tool-call", "tool-result"}:
+ compact = dict(event)
+ compact["payload"] = _compact_protocol_value(event.get("payload"))
+ compact_events.append(compact)
+ elif event.get("type") == "context-replaced":
+ compact = dict(event)
+ payload = dict(event.get("payload") or {})
+ payload["replaced_messages"] = _compact_protocol_container(
+ payload.get("replaced_messages")
+ )
+ compact["payload"] = payload
+ compact_events.append(compact)
+ elif event.get("type") == "task-finished":
+ compact = dict(event)
+ compact["payload"] = _compact_protocol_value(event.get("payload"))
+ compact_events.append(compact)
+ else:
+ compact_events.append(event)
+ continue
+ envelope_count += 1
+ payload = dict(event.get("payload") or {})
+ latest_visible = {
+ "cursor": event.get("cursor"),
+ "hash": event.get("hash"),
+ "task_id": event.get("task_id"),
+ "created_at": event.get("created_at"),
+ "messages": _compact_protocol_container(payload.get("messages")),
+ "tools": _tool_inventory(payload.get("tools")),
+ "status": payload.get("status"),
+ }
+ compact_events.append(
+ {
+ "cursor": event.get("cursor"),
+ "type": event.get("type"),
+ "session_id": event.get("session_id"),
+ "task_id": event.get("task_id"),
+ "created_at": event.get("created_at"),
+ "previous_hash": event.get("previous_hash"),
+ "hash": event.get("hash"),
+ "payload": {
+ "status": payload.get("status"),
+ "response": _compact_protocol_value(payload.get("response")),
+ "usage": payload.get("usage"),
+ "exception": payload.get("exception"),
+ "visible_context_cursor": event.get("cursor"),
+ },
+ }
+ )
+ return {
+ "final_visible_context": latest_visible,
+ "frozen_working_memory": _bound_frozen_working_memory(compact_events),
+ "raw_history_manifest": {
+ "from_cursor": events[0].get("cursor") if events else None,
+ "to_cursor": events[-1].get("cursor") if events else None,
+ "event_count": len(events),
+ "model_visible_envelope_count": envelope_count,
+ "first_hash": events[0].get("hash") if events else None,
+ "last_hash": events[-1].get("hash") if events else None,
+ "complete_raw_history_path": "raw-history/events.jsonl",
+ },
+ }
+
+
+def _memory_query(events: list[dict[str, Any]]) -> str:
+ parts: list[str] = []
+ for event in reversed(events):
+ if event.get("type") not in {"user-message", "task-started", "model-visible-envelope"}:
+ continue
+ payload = event.get("payload")
+ text = json.dumps(payload, ensure_ascii=False) if not isinstance(payload, str) else payload
+ if text.strip():
+ parts.append(text[:800])
+ if len(parts) == 4:
+ break
+ return " ".join(reversed(parts))[:2400] or "recent conversation"
+
+
+_LIVE_COORDINATORS: WeakSet["SessionCoordinator"] = WeakSet()
+
+
+class SessionCoordinator:
+ """Own all mutable eternal state for exactly one product Session."""
+
+ def __init__(
+ self,
+ root: Path,
+ session_id: str,
+ model_supplier: Callable[[], Any],
+ ) -> None:
+ self.root = root
+ self.session_id = session_id
+ self.evidence = EvidenceWriter(root, session_id)
+ self.memory = DynamicMemoryGateway(root / "memory", self.evidence)
+ self.agents = BackgroundAgentRunner(model_supplier, self.evidence)
+ self.state_path = root / "state" / "harness.json"
+ self.projection_path = root / "state" / "eternal-conversation.json"
+ self._worker: asyncio.Task[None] | None = None
+ self._builder: asyncio.Task[None] | None = None
+ self._closed = False
+ self._schedule_lock = asyncio.Lock()
+ self._write_manifest()
+ _LIVE_COORDINATORS.add(self)
+
+ @property
+ def closed(self) -> bool:
+ return self._closed
+
+ def _write_manifest(self) -> None:
+ path = self.root / "audit" / "source-manifest.json"
+ if path.exists():
+ return
+ write_json_atomic(
+ path,
+ {
+ "implementation": "jiuwenswarm.persist-session",
+ "schema_version": 1,
+ "prompt_hashes": prompt_hashes(),
+ },
+ )
+
+ async def request_extract(self, cursor: int) -> None:
+ if self._closed:
+ return
+ async with self._schedule_lock:
+ if self._closed:
+ return
+ state = read_json(self.state_path, {}) or {}
+ requested = max(int(state.get("requested_cursor") or 0), int(cursor))
+ state["requested_cursor"] = requested
+ state["updated_at"] = utc_now()
+ state.pop("extractor_error", None)
+ await asyncio.to_thread(write_json_atomic, self.state_path, state)
+ if self._worker is None or self._worker.done():
+ # A clean Context prevents foreground request/session bindings
+ # from leaking into either background Agent.
+ clean = contextvars.Context()
+ self._worker = asyncio.create_task(
+ self._guarded_extract_loop(),
+ name=f"eternal-extractor:{self.session_id}",
+ context=clean,
+ )
+
+ async def resume_background(self) -> None:
+ """Resume durable cursor/Pending work after an Adapter or process restart."""
+ state = read_json(self.state_path, {}) or {}
+ requested = int(state.get("requested_cursor") or 0)
+ if requested:
+ # Starting a new durable retry boundary supersedes a failure from
+ # the previous process/request. Clear it synchronously before the
+ # extractor task is scheduled: otherwise an observer can see the
+ # stale builder failure and fail fast while the retry is already
+ # queued but has not reached _schedule_builder() yet.
+ await self._clear_worker_error("builder")
+ await self.request_extract(requested)
+ elif (self.root / "memory" / "memory.sqlite3").exists():
+ await self._schedule_builder()
+
+ async def _guarded_extract_loop(self) -> None:
+ try:
+ await self._extract_loop()
+ except Exception as exc:
+ await self.evidence.append_agent_history(
+ "extractor",
+ {"status": "error", "error_type": type(exc).__name__, "error": str(exc)},
+ )
+ await self._record_worker_error("extractor", exc)
+
+ async def _extract_loop(self) -> None:
+ await self.memory.ensure_initialized()
+ while not self._closed:
+ requested = int((read_json(self.state_path, {}) or {}).get("requested_cursor") or 0)
+ formal = await self.memory.projection()
+ covered = int(formal.get("covered_through") or 0)
+ if requested <= covered:
+ await self._schedule_builder()
+ return
+ events = await asyncio.to_thread(
+ _raw_range, self.evidence.raw_path, covered + 1, requested
+ )
+ if not events or int(events[0].get("cursor") or 0) != covered + 1:
+ raise RuntimeError("raw history range is incomplete; refusing publication")
+ target = int(events[-1].get("cursor") or 0)
+ if target > requested or events[-1].get("type") != "task-finished":
+ raise RuntimeError("raw history batch has no complete task boundary")
+ published = await self.memory.call("list", "--full")
+ memories = list(published.get("memories") or [])
+ related = await self.memory.search(_memory_query(events)) if memories else {"matches": []}
+ related_ids = [str(item.get("id")) for item in related.get("matches") or []][:32]
+ by_id = {str(item.get("id")): item for item in memories}
+ high_priority = sorted(memories, key=lambda item: int(item.get("priority") or 0), reverse=True)[:12]
+ references: list[dict[str, Any]] = []
+ seen: set[str] = set()
+ for item in [*(by_id[item_id] for item_id in related_ids if item_id in by_id), *high_priority]:
+ item_id = str(item.get("id"))
+ if item_id not in seen:
+ seen.add(item_id)
+ references.append(item)
+ evidence_ref = f"raw-history:cursor-{covered + 1}-{target}"
+ evidence_view = _extractor_evidence(events)
+ request = {
+ "old_snapshot": formal.get("snapshot") or {},
+ **evidence_view,
+ "published_uts": references,
+ "source": self.session_id,
+ "evidence_ref": evidence_ref,
+ }
+ parsed = await self.agents.call_json(
+ role="extractor",
+ system_prompt=EXTRACTOR_SYSTEM_PROMPT,
+ request=request,
+ validate=_validate_extractor,
+ )
+ proposal = {
+ "base_memory_revision": formal["memory_revision"],
+ "base_snapshot_revision": formal["snapshot_revision"],
+ "from_cursor": covered + 1,
+ "to_cursor": target,
+ "snapshot": parsed["snapshot"],
+ "changed_uts": _normalize_changes(
+ list(parsed.get("changed_uts") or []), self.session_id, evidence_ref
+ ),
+ "evidence_refs": [evidence_ref],
+ "semantic_statement": parsed.get("semantic_statement")
+ or "All future-relevant effects are carried.",
+ }
+ result = await self.memory.file_command(
+ "publish-pending", proposal, f"proposal-{covered + 1}-{target}"
+ )
+ await asyncio.to_thread(write_json_atomic, self.projection_path, result)
+ await self.evidence.append_audit(
+ "publications", {"proposal": proposal, "result": result}
+ )
+ await self._schedule_builder()
+
+ async def _schedule_builder(self) -> None:
+ if self._closed:
+ return
+ if self._builder is None or self._builder.done():
+ await self._clear_worker_error("builder")
+ if self._closed:
+ return
+ self._builder = asyncio.create_task(
+ self._guarded_build_loop(),
+ name=f"eternal-builder:{self.session_id}",
+ context=contextvars.Context(),
+ )
+
+ async def _guarded_build_loop(self) -> None:
+ try:
+ await self._build_loop()
+ except Exception as exc:
+ await self.evidence.append_agent_history(
+ "builder",
+ {"status": "error", "error_type": type(exc).__name__, "error": str(exc)},
+ )
+ await self._record_worker_error("builder", exc)
+
+ async def _clear_worker_error(self, worker: str) -> None:
+ async with self._schedule_lock:
+ state = read_json(self.state_path, {}) or {}
+ if state.pop(f"{worker}_error", None) is None:
+ return
+ state["updated_at"] = utc_now()
+ await asyncio.to_thread(write_json_atomic, self.state_path, state)
+
+ async def _record_worker_error(self, worker: str, exc: Exception) -> None:
+ async with self._schedule_lock:
+ state = read_json(self.state_path, {}) or {}
+ state[f"{worker}_error"] = {
+ "at": utc_now(),
+ "error_type": type(exc).__name__,
+ "error": str(exc),
+ }
+ state["updated_at"] = utc_now()
+ await asyncio.to_thread(write_json_atomic, self.state_path, state)
+
+ async def _build_loop(self) -> None:
+ while not self._closed:
+ output = self.root / "memory" / "jobs" / f"build-{utc_now().replace(':', '-')}.json"
+ frozen = await self.memory.call("freeze-pending", "--output", str(output))
+ if int(frozen.get("count") or 0) == 0:
+ return
+ batch = read_json(output, {}) or {}
+ review = await self.agents.call_json(
+ role="builder",
+ system_prompt=BUILDER_SYSTEM_PROMPT,
+ request=batch,
+ validate=_validate_builder,
+ )
+ if not review["approved"]:
+ await self.evidence.append_audit("builds", {"batch": str(output), "review": review})
+ diagnostics = "; ".join(str(item) for item in review.get("diagnostics") or [])
+ raise RuntimeError(
+ "builder rejected frozen Pending batch"
+ + (f": {diagnostics}" if diagnostics else "")
+ )
+ result = await self.memory.call("build-pending", "--file", str(output))
+ await self.evidence.append_audit(
+ "builds", {"batch": str(output), "review": review, "result": result}
+ )
+
+ async def projection_for_boundary(self, *, force: bool = False) -> dict[str, Any] | None:
+ """Return a projection only when no newer foreground task can be lost."""
+ if not (self.root / "memory" / "memory.sqlite3").exists():
+ return None
+ formal = await self.memory.projection()
+ requested = int((read_json(self.state_path, {}) or {}).get("requested_cursor") or 0)
+ revision = int(formal.get("snapshot_revision") or 0)
+ state = read_json(self.state_path, {}) or {}
+ applied = int(state.get("applied_snapshot_revision") or 0)
+ if (revision <= applied and not force) or int(formal.get("covered_through") or 0) != requested:
+ return None
+ return formal
+
+ async def mark_projection_applied(self, revision: int) -> None:
+ async with self._schedule_lock:
+ state = read_json(self.state_path, {}) or {}
+ state["applied_snapshot_revision"] = int(revision)
+ state["updated_at"] = utc_now()
+ await asyncio.to_thread(write_json_atomic, self.state_path, state)
+
+ async def wait_idle(self) -> None:
+ while True:
+ active = [task for task in (self._worker, self._builder) if task is not None and not task.done()]
+ if not active:
+ return
+ await asyncio.gather(*active, return_exceptions=True)
+
+ async def close(self) -> None:
+ """Stop Extractor/Builder and in-flight memory-cli processes.
+
+ Rail.close() must not call this: Adapter retirement is not Session end.
+ Process shutdown and tests use close_all_session_coordinators().
+ """
+ if self._closed:
+ await self.wait_idle()
+ return
+ self._closed = True
+ await self.memory.abort()
+ for task in (self._worker, self._builder):
+ if task is not None and not task.done():
+ task.cancel()
+ await self.wait_idle()
+
+
+async def close_live_coordinators() -> None:
+ coordinators = list(_LIVE_COORDINATORS)
+ _LIVE_COORDINATORS.clear()
+ for coordinator in coordinators:
+ await coordinator.close()
+
+
+__all__ = ["SessionCoordinator", "close_live_coordinators"]
diff --git a/jiuwenswarm/agents/harness/common/rails/eternal_conversation/evidence.py b/jiuwenswarm/agents/harness/common/rails/eternal_conversation/evidence.py
new file mode 100644
index 0000000000..862a4724ee
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/rails/eternal_conversation/evidence.py
@@ -0,0 +1,506 @@
+"""Append-only, hash-chained evidence for eternal conversations."""
+
+from __future__ import annotations
+
+import asyncio
+import dataclasses
+import hashlib
+import json
+import logging
+import os
+import tempfile
+import threading
+from datetime import datetime, timezone
+from enum import Enum
+from pathlib import Path
+from typing import Any
+
+import portalocker
+
+logger = logging.getLogger(__name__)
+
+
+def utc_now() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def jsonable(value: Any) -> Any:
+ """Convert framework objects without interpreting or summarizing them."""
+ if value is None or isinstance(value, (str, int, float, bool)):
+ return value
+ if isinstance(value, Path):
+ return str(value)
+ if isinstance(value, Enum):
+ return value.value
+ if dataclasses.is_dataclass(value):
+ return jsonable(dataclasses.asdict(value))
+ model_dump = getattr(value, "model_dump", None)
+ if callable(model_dump):
+ try:
+ return jsonable(model_dump(mode="json"))
+ except TypeError:
+ return jsonable(model_dump())
+ if isinstance(value, dict):
+ return {str(key): jsonable(item) for key, item in value.items()}
+ if isinstance(value, (list, tuple, set, frozenset)):
+ return [jsonable(item) for item in value]
+ data = getattr(value, "__dict__", None)
+ if isinstance(data, dict):
+ public = {key: item for key, item in data.items() if not key.startswith("_")}
+ if public:
+ return jsonable(public)
+ return str(value)
+
+
+def read_json(path: Path, default: Any = None) -> Any:
+ try:
+ with path.open("r", encoding="utf-8") as handle:
+ return json.load(handle)
+ except FileNotFoundError:
+ return default
+
+
+def write_json_atomic(path: Path, value: Any) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ encoded = json.dumps(jsonable(value), ensure_ascii=False, indent=2, sort_keys=True)
+ fd, temporary = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
+ handle.write(encoded)
+ handle.write("\n")
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.replace(temporary, path)
+ finally:
+ if os.path.exists(temporary):
+ os.unlink(temporary)
+
+
+def append_jsonl(path: Path, value: Any) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ line = json.dumps(jsonable(value), ensure_ascii=False, sort_keys=True, separators=(",", ":"))
+ with path.open("a", encoding="utf-8", newline="\n") as handle:
+ handle.write(line)
+ handle.write("\n")
+ handle.flush()
+ os.fsync(handle.fileno())
+
+
+def _append_auxiliary_jsonl(root: Path, relative_path: Path, value: Any) -> None:
+ """Serialize non-cursor JSONL across tasks, adapters, and processes.
+
+ Audit and background-Agent histories do not participate in the Raw History
+ cursor chain, but each line must still be atomic and independently parseable.
+ Large UTF-8 records can span multiple OS writes, so append mode alone is not
+ a sufficient concurrency boundary.
+ """
+ lock_name = hashlib.sha256(relative_path.as_posix().encode("utf-8")).hexdigest()
+ with _path_lock(root):
+ lock_path = root / "state" / "auxiliary-locks" / f"{lock_name}.lock"
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
+ with portalocker.Lock(str(lock_path), timeout=60):
+ append_jsonl(root / relative_path, value)
+
+
+_AGENT_HISTORY_INLINE_LIMIT = 256 * 1024
+_RAW_HISTORY_INLINE_LIMIT = 256 * 1024
+
+# Adapter recreation can briefly construct more than one EvidenceWriter for
+# the same durable Session. An instance-local asyncio.Lock cannot serialize
+# those writers, so cursor allocation is also protected by feature path.
+_PATH_LOCKS_GUARD = threading.Lock()
+_PATH_LOCKS: dict[str, threading.Lock] = {}
+
+
+def _path_lock(root: Path) -> threading.Lock:
+ key = str(root.resolve())
+ with _PATH_LOCKS_GUARD:
+ return _PATH_LOCKS.setdefault(key, threading.Lock())
+
+
+def _encoded_json(value: Any) -> bytes:
+ return json.dumps(
+ value,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ ).encode("utf-8")
+
+
+def _blob_reference(root: Path, value: Any, *, inline_limit: int) -> Any:
+ """Store one large value by digest without changing its JSON semantics."""
+ encoded = _encoded_json(value)
+ if len(encoded) <= inline_limit:
+ return value
+ digest = hashlib.sha256(encoded).hexdigest()
+ relative = Path("blobs") / f"{digest}.json"
+ blob_path = root / relative
+ if not blob_path.exists():
+ write_json_atomic(blob_path, value)
+ return {
+ "$evidence_blob": relative.as_posix(),
+ "bytes": len(encoded),
+ "encoding": "json/utf-8",
+ "sha256": digest,
+ }
+
+
+def resolve_evidence_blobs(value: Any, root: Path) -> Any:
+ """Resolve and verify content-addressed evidence references recursively."""
+ if isinstance(value, dict) and "$evidence_blob" in value:
+ relative = Path(str(value["$evidence_blob"]))
+ if relative.is_absolute() or ".." in relative.parts:
+ raise RuntimeError("evidence blob path escapes its history root")
+ resolved = read_json(root / relative)
+ encoded = _encoded_json(resolved)
+ if len(encoded) != int(value.get("bytes") or -1):
+ raise RuntimeError("evidence blob byte count mismatch")
+ if hashlib.sha256(encoded).hexdigest() != str(value.get("sha256") or ""):
+ raise RuntimeError("evidence blob digest mismatch")
+ return resolved
+ if isinstance(value, dict):
+ return {key: resolve_evidence_blobs(item, root) for key, item in value.items()}
+ if isinstance(value, list):
+ return [resolve_evidence_blobs(item, root) for item in value]
+ return value
+
+
+def _search_view_event(event: dict[str, Any], logical_payload: Any) -> dict[str, Any]:
+ """Create the non-semantic, grep-friendly projection of one Raw event."""
+ search_payload = logical_payload
+ if isinstance(logical_payload, dict):
+ search_payload = dict(logical_payload)
+ if event.get("type") == "model-visible-envelope":
+ search_payload.pop("messages", None)
+ search_payload.pop("tools", None)
+ elif event.get("type") == "context-replaced":
+ replaced = search_payload.pop("replaced_messages", None)
+ search_payload["replaced_message_count"] = (
+ len(replaced) if isinstance(replaced, list) else 0
+ )
+ return {
+ "cursor": event.get("cursor"),
+ "type": event.get("type"),
+ "session_id": event.get("session_id"),
+ "task_id": event.get("task_id"),
+ "created_at": event.get("created_at"),
+ "hash": event.get("hash"),
+ "payload": search_payload,
+ }
+
+
+def _append_agent_history(root: Path, role: str, payload: Any) -> None:
+ """Append a complete, reconstructable background-Agent history record.
+
+ Extractor inputs can legitimately contain a large frozen evidence batch.
+ Repeating that batch inline for every retry makes the audit log grow
+ quadratically. Large top-level values are therefore stored once as
+ content-addressed JSON blobs. This is structural deduplication only: the
+ history record carries the digest, byte count and relative path needed to
+ reconstruct the exact model input without semantic summarisation.
+ """
+ record = jsonable(payload)
+ if not isinstance(record, dict):
+ record = {"value": record}
+ history_root = root / "agent-history" / role
+ compact: dict[str, Any] = {}
+ for key, value in record.items():
+ compact[key] = _blob_reference(
+ history_root,
+ value,
+ inline_limit=_AGENT_HISTORY_INLINE_LIMIT,
+ )
+ append_jsonl(
+ history_root / "conversation.jsonl",
+ {"created_at": utc_now(), **compact},
+ )
+
+
+class EvidenceWriter:
+ """The sole cursor authority for one session-scoped feature directory."""
+
+ def __init__(self, root: Path, session_id: str) -> None:
+ self.root = root
+ self.session_id = session_id
+ self.raw_path = root / "raw-history" / "events.jsonl"
+ self.state_path = root / "state" / "evidence.json"
+ self._lock = asyncio.Lock()
+ state = read_json(self.state_path, {}) or {}
+ self._cursor, self._last_hash = self._recover_durable_tail(state)
+
+ def _recover_durable_tail(self, state: dict[str, Any]) -> tuple[int, str]:
+ """Validate the WAL and recover a state/mirror tail after a crash.
+
+ Raw History is authoritative. It is written before both the foreground
+ mirror and the small cursor state file, so either derived file may lag
+ by one or more complete JSONL records when a process is terminated.
+ Semantic repair is deliberately forbidden here: only byte-equivalent
+ records from the already durable Raw History are replayed.
+ """
+ events: list[dict[str, Any]] = []
+ if self.raw_path.exists():
+ with self.raw_path.open("r", encoding="utf-8") as handle:
+ for line_number, line in enumerate(handle, start=1):
+ if not line.strip():
+ continue
+ try:
+ event = json.loads(line)
+ except json.JSONDecodeError as exc:
+ raise RuntimeError(
+ f"corrupt Raw History JSON at line {line_number}"
+ ) from exc
+ expected_cursor = len(events) + 1
+ if int(event.get("cursor") or 0) != expected_cursor:
+ raise RuntimeError(
+ f"non-monotonic Raw History cursor at line {line_number}"
+ )
+ if str(event.get("session_id") or "") != self.session_id:
+ raise RuntimeError(
+ f"Raw History session mismatch at line {line_number}"
+ )
+ previous_hash = events[-1]["hash"] if events else None
+ if event.get("previous_hash") != previous_hash:
+ raise RuntimeError(
+ f"broken Raw History hash chain at line {line_number}"
+ )
+ claimed_hash = str(event.get("hash") or "")
+ digest_value = dict(event)
+ digest_value.pop("hash", None)
+ digest_source = json.dumps(
+ digest_value,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ )
+ actual_hash = hashlib.sha256(digest_source.encode("utf-8")).hexdigest()
+ if claimed_hash != actual_hash:
+ raise RuntimeError(
+ f"invalid Raw History hash at line {line_number}"
+ )
+ events.append(event)
+
+ durable_cursor = len(events)
+ durable_hash = str(events[-1]["hash"]) if events else ""
+ state_cursor = int(state.get("cursor") or 0)
+ state_hash = str(state.get("last_hash") or "")
+ if state_cursor > durable_cursor:
+ raise RuntimeError("evidence cursor state is ahead of Raw History")
+ if state_cursor:
+ expected_state_hash = str(events[state_cursor - 1]["hash"])
+ if state_hash != expected_state_hash:
+ raise RuntimeError("evidence cursor state disagrees with Raw History")
+
+ mirror_path = self.root / "agent-history" / "foreground" / "conversation.jsonl"
+ mirrored: list[dict[str, Any]] = []
+ if mirror_path.exists():
+ with mirror_path.open("r", encoding="utf-8") as handle:
+ for line_number, line in enumerate(handle, start=1):
+ if not line.strip():
+ continue
+ try:
+ mirrored.append(json.loads(line))
+ except json.JSONDecodeError as exc:
+ raise RuntimeError(
+ f"corrupt foreground history JSON at line {line_number}"
+ ) from exc
+ if len(mirrored) > len(events) or mirrored != events[: len(mirrored)]:
+ raise RuntimeError("foreground history is not a prefix of Raw History")
+ for event in events[len(mirrored):]:
+ append_jsonl(mirror_path, event)
+
+ search_path = self.root / "raw-history" / "search.jsonl"
+ searchable: list[dict[str, Any]] = []
+ if search_path.exists():
+ try:
+ with search_path.open("r", encoding="utf-8") as handle:
+ searchable = [json.loads(line) for line in handle if line.strip()]
+ except json.JSONDecodeError:
+ # search.jsonl is a derived, fully rebuildable view of the
+ # authoritative Raw History; a partial/corrupt write must not
+ # disable the whole feature. Drop it and rebuild from scratch.
+ logger.warning(
+ "corrupt search view at %s; rebuilding from Raw History",
+ search_path,
+ )
+ search_path.unlink()
+ searchable = []
+ if len(searchable) > len(events):
+ raise RuntimeError("Raw History search view is ahead of canonical evidence")
+ for index, row in enumerate(searchable):
+ event = events[index]
+ if row.get("cursor") != event.get("cursor") or row.get("hash") != event.get("hash"):
+ raise RuntimeError("Raw History search view disagrees with canonical evidence")
+ for event in events[len(searchable):]:
+ logical_payload = resolve_evidence_blobs(
+ event.get("payload"),
+ self.root / "raw-history",
+ )
+ append_jsonl(search_path, _search_view_event(event, logical_payload))
+
+ if state_cursor != durable_cursor or state_hash != durable_hash:
+ write_json_atomic(
+ self.state_path,
+ {"cursor": durable_cursor, "last_hash": durable_hash},
+ )
+ return durable_cursor, durable_hash
+
+ @property
+ def cursor(self) -> int:
+ return self._cursor
+
+ async def append(
+ self,
+ event_type: str,
+ payload: Any,
+ *,
+ task_id: str | None = None,
+ mirror_role: str | None = "foreground",
+ ) -> dict[str, Any]:
+ async with self._lock:
+ return await asyncio.to_thread(
+ self._append_sync,
+ event_type,
+ payload,
+ task_id,
+ mirror_role,
+ )
+
+ def _append_sync(
+ self,
+ event_type: str,
+ payload: Any,
+ task_id: str | None,
+ mirror_role: str | None,
+ ) -> dict[str, Any]:
+ with _path_lock(self.root):
+ lock_path = self.root / "state" / "evidence.lock"
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
+ with portalocker.Lock(str(lock_path), timeout=60):
+ state = read_json(self.state_path, {}) or {}
+ state_cursor = int(state.get("cursor") or 0)
+ state_hash = str(state.get("last_hash") or "")
+ if state_cursor < self._cursor:
+ raise RuntimeError("evidence cursor state moved backwards")
+ if state_cursor > self._cursor:
+ self._cursor = state_cursor
+ self._last_hash = state_hash
+ return self._append_sync_locked(event_type, payload, task_id, mirror_role)
+
+ def _append_sync_locked(
+ self,
+ event_type: str,
+ payload: Any,
+ task_id: str | None,
+ mirror_role: str | None,
+ ) -> dict[str, Any]:
+ cursor = self._cursor + 1
+ raw_root = self.root / "raw-history"
+ logical_payload = jsonable(payload)
+ if isinstance(logical_payload, dict):
+ durable_payload = {
+ key: _blob_reference(
+ raw_root,
+ value,
+ inline_limit=_RAW_HISTORY_INLINE_LIMIT,
+ )
+ for key, value in logical_payload.items()
+ }
+ else:
+ durable_payload = _blob_reference(
+ raw_root,
+ logical_payload,
+ inline_limit=_RAW_HISTORY_INLINE_LIMIT,
+ )
+ event = {
+ "cursor": cursor,
+ "type": event_type,
+ "session_id": self.session_id,
+ "task_id": task_id,
+ "created_at": utc_now(),
+ "previous_hash": self._last_hash or None,
+ "payload": durable_payload,
+ }
+ digest_source = json.dumps(event, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
+ event_hash = hashlib.sha256(digest_source.encode("utf-8")).hexdigest()
+ event["hash"] = event_hash
+
+ # Raw History is the write-ahead evidence layer. A crash after this
+ # append can leave an uncovered tail, but can never publish memory that
+ # refers to evidence which was not durably recorded first.
+ append_jsonl(self.raw_path, event)
+ if mirror_role:
+ append_jsonl(
+ self.root / "agent-history" / mirror_role / "conversation.jsonl",
+ event,
+ )
+ # A task-local structural mirror makes acceptance/audit reads bounded.
+ # It contains the exact hash-chained event (including blob references),
+ # so it never becomes a second semantic source of truth.
+ if task_id:
+ task_digest = hashlib.sha256(task_id.encode("utf-8")).hexdigest()
+ append_jsonl(raw_root / "tasks" / f"{task_digest}.jsonl", event)
+
+ # The reference prompt requires direct evidence lookup. This compact
+ # view removes only fields that repeat the complete accumulated model
+ # context; direct user messages, tool evidence and model responses stay
+ # verbatim and retain their canonical cursor/hash backlink.
+ append_jsonl(raw_root / "search.jsonl", _search_view_event(event, logical_payload))
+ write_json_atomic(self.state_path, {"cursor": cursor, "last_hash": event_hash})
+ self._cursor = cursor
+ self._last_hash = event_hash
+ return event
+
+ async def append_agent_history(self, role: str, payload: Any) -> None:
+ await asyncio.to_thread(
+ self._append_agent_history_sync,
+ role,
+ payload,
+ )
+
+ def _append_agent_history_sync(self, role: str, payload: Any) -> None:
+ relative = Path("agent-history") / role / "conversation.jsonl"
+ compact = jsonable(payload)
+ if isinstance(compact, dict):
+ compact = {
+ key: _blob_reference(
+ self.root / "agent-history" / role,
+ value,
+ inline_limit=_AGENT_HISTORY_INLINE_LIMIT,
+ )
+ for key, value in compact.items()
+ }
+ else:
+ compact = {
+ "value": _blob_reference(
+ self.root / "agent-history" / role,
+ compact,
+ inline_limit=_AGENT_HISTORY_INLINE_LIMIT,
+ )
+ }
+ _append_auxiliary_jsonl(
+ self.root,
+ relative,
+ {"created_at": utc_now(), **compact},
+ )
+
+ async def append_audit(self, name: str, payload: Any) -> None:
+ record = jsonable(payload)
+ if not isinstance(record, dict):
+ record = {"value": record}
+ await asyncio.to_thread(
+ _append_auxiliary_jsonl,
+ self.root,
+ Path("audit") / f"{name}.jsonl",
+ {"created_at": utc_now(), **record},
+ )
+
+
+__all__ = [
+ "EvidenceWriter",
+ "append_jsonl",
+ "jsonable",
+ "read_json",
+ "resolve_evidence_blobs",
+ "utc_now",
+ "write_json_atomic",
+]
diff --git a/jiuwenswarm/agents/harness/common/rails/eternal_conversation/memory_cli.py b/jiuwenswarm/agents/harness/common/rails/eternal_conversation/memory_cli.py
new file mode 100644
index 0000000000..836aeaef82
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/rails/eternal_conversation/memory_cli.py
@@ -0,0 +1,162 @@
+"""Audited async gateway to the vendored dynamic-memory-cli contract."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import sys
+import uuid
+from pathlib import Path
+from typing import Any
+
+from .evidence import EvidenceWriter, write_json_atomic
+
+
+VENDORED_SKILL = (
+ Path(__file__).resolve().parents[5]
+ / "resources"
+ / "agent"
+ / "workspace"
+ / "skills"
+ / "dynamic-memory-cli"
+)
+
+
+class DynamicMemoryGateway:
+ """One formal memory state machine; callers never bypass this process."""
+
+ def __init__(
+ self,
+ root: Path,
+ evidence: EvidenceWriter,
+ *,
+ script: Path | None = None,
+ invoke_timeout: float = 600.0,
+ ) -> None:
+ self.root = root
+ self.evidence = evidence
+ self.script = script or VENDORED_SKILL / "scripts" / "dynamic_memory_cli.py"
+ self.invoke_timeout = invoke_timeout
+ self._init_lock = asyncio.Lock()
+ self._initialized = False
+ self._processes: set[asyncio.subprocess.Process] = set()
+
+ async def ensure_initialized(self) -> None:
+ if self._initialized:
+ return
+ async with self._init_lock:
+ if self._initialized:
+ return
+ if not self.script.is_file():
+ raise FileNotFoundError(f"vendored dynamic-memory-cli not found: {self.script}")
+ if not (self.root / "memory.sqlite3").is_file():
+ await self._invoke("init", "--path", str(self.root), include_root=False)
+ self._initialized = True
+
+ async def call(self, *args: str) -> dict[str, Any]:
+ await self.ensure_initialized()
+ return await self._invoke(*args, include_root=True)
+
+ async def abort(self) -> None:
+ """Kill in-flight CLI processes so cancelled Tasks can leave communicate()."""
+ for process in list(self._processes):
+ await _stop_process(process)
+
+ async def _invoke(self, *args: str, include_root: bool) -> dict[str, Any]:
+ self.root.mkdir(parents=True, exist_ok=True)
+ command = [sys.executable, str(self.script)]
+ if include_root:
+ command.extend(("--root", str(self.root)))
+ command.extend(args)
+ env = dict(os.environ)
+ env.update({"PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"})
+ started = asyncio.get_running_loop().time()
+ process = await asyncio.create_subprocess_exec(
+ *command,
+ cwd=str(self.root),
+ env=env,
+ stdin=asyncio.subprocess.DEVNULL,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ )
+ self._processes.add(process)
+ try:
+ stdout, stderr = await asyncio.wait_for(
+ process.communicate(), timeout=self.invoke_timeout
+ )
+ except asyncio.TimeoutError:
+ await _stop_process(process)
+ elapsed_ms = (asyncio.get_running_loop().time() - started) * 1000
+ await self.evidence.append_audit(
+ "memory-cli-calls",
+ {
+ "args": list(args),
+ "returncode": None,
+ "elapsed_ms": elapsed_ms,
+ "result": {"error": "timeout", "timeout_s": self.invoke_timeout},
+ },
+ )
+ raise RuntimeError(
+ f"dynamic-memory-cli timed out after {self.invoke_timeout}s: {list(args)}"
+ ) from None
+ except asyncio.CancelledError:
+ # Session/loop teardown may cancel an in-flight invoke. Without
+ # stopping the child here it is abandoned still running and its
+ # transport detonates later as unraisable ResourceWarnings
+ # attributed to whichever test is running when GC fires.
+ await _stop_process(process)
+ raise
+ finally:
+ self._processes.discard(process)
+ elapsed_ms = (asyncio.get_running_loop().time() - started) * 1000
+ text = stdout.decode("utf-8", errors="replace")
+ error_text = stderr.decode("utf-8", errors="replace")
+ try:
+ result = json.loads(text)
+ except json.JSONDecodeError as exc:
+ result = {"error": "invalid_json", "stdout": text, "stderr": error_text}
+ await self.evidence.append_audit(
+ "memory-cli-calls",
+ {"args": list(args), "returncode": process.returncode, "elapsed_ms": elapsed_ms, "result": result},
+ )
+ raise RuntimeError(f"dynamic-memory-cli returned invalid JSON: {text or error_text}") from exc
+ await self.evidence.append_audit(
+ "memory-cli-calls",
+ {"args": list(args), "returncode": process.returncode, "elapsed_ms": elapsed_ms, "result": result},
+ )
+ if process.returncode != 0:
+ raise RuntimeError(f"dynamic-memory-cli failed: {result}")
+ return result
+
+ async def file_command(self, command: str, payload: dict[str, Any], stem: str) -> dict[str, Any]:
+ jobs = self.root / "jobs"
+ path = jobs / f"{stem}-{uuid.uuid4().hex}.json"
+ await asyncio.to_thread(write_json_atomic, path, payload)
+ return await self.call(command, "--file", str(path))
+
+ async def search(self, query: str) -> dict[str, Any]:
+ query = str(query or "").strip()
+ if not query:
+ return {"query": "", "matches": []}
+ # This exact CLI path merges published Pending and Built UTs.
+ return await self.call("search", query)
+
+ async def projection(self) -> dict[str, Any]:
+ return await self.call("get-state")
+
+
+async def _stop_process(process: asyncio.subprocess.Process) -> None:
+ if process.returncode is not None:
+ return
+ try:
+ process.kill()
+ except ProcessLookupError:
+ return
+ try:
+ await process.wait()
+ except (ProcessLookupError, asyncio.CancelledError):
+ return
+
+
+__all__ = ["DynamicMemoryGateway", "VENDORED_SKILL"]
diff --git a/jiuwenswarm/agents/harness/common/rails/eternal_conversation/prompts.py b/jiuwenswarm/agents/harness/common/rails/eternal_conversation/prompts.py
new file mode 100644
index 0000000000..e61fef2662
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/rails/eternal_conversation/prompts.py
@@ -0,0 +1,201 @@
+"""Versioned prompts for the Persist Session foreground and workers.
+
+JiuwenSwarm-specific wiring lives outside this module so prompt revisions are
+easy to audit independently from runtime integration.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+from pathlib import Path
+from typing import Any
+
+
+EXTRACTOR_SYSTEM_PROMPT = """You are the memory extraction Agent in an eternal-conversation Harness.
+Return one JSON object only. Use the old Snapshot plus the frozen Working Memory as the continuous
+history input. Compare proposed memories with the published UTs and resolve conflicts by updating
+stable UT IDs. Preserve exact answer-bearing facts, decisions, constraints, commitments, active work,
+and likely future retrieval phrasings. Version support windows, deprecation deadlines, compatibility
+promises, and constraints the user asks not to publish in project documentation are still durable
+memory and MUST be retained with their exact version/date boundary. A durable user decision or
+constraint MUST have its own stable UT and MUST NOT share a UT with an evolving implementation
+summary; this separation prevents later code updates from overwriting it. Treat user-defined proper
+nouns, internal codenames, aliases, environment names, and their referents as durable retrieval keys
+whenever they may affect future behavior. Preserve the exact user-authored name in the UT content,
+at least one query, and must_include; never leave it only in the Snapshot. A request to keep a name
+out of source code, repository files, or project documentation means memory-only visibility, not
+permission to omit it. Before returning, self-audit every future-relevant named entity and alias in
+the continuous history and ensure an existing or changed stable UT carries both the exact name and
+its meaning. When updating an existing UT, carry forward every still-effective decision,
+constraint, commitment, and exact boundary from the published UT; absence from the frozen Working
+Memory is not evidence that an older constraint became stale. Do not decide cursor or
+publication legality.
+
+Conflict resolution rule: a later request overrides an existing decision only when that direct
+user message refers to the earlier constraint or option and communicates intent to replace it.
+A merely contradictory request is unacknowledged and MUST preserve the earlier decision unchanged;
+repeating the same contradictory request any number of times is still not acknowledgment. Agent
+answers, tool edits, passing tests, retry counts, and task-completion events never turn an
+unacknowledged request into an override. If a published UT or Snapshot incorrectly claims such an
+override, repair it from the earliest relevant direct-user evidence and keep the conflict unresolved
+until the user explicitly chooses. Direct user messages outrank Agent narration and implementation
+results for deciding whether a constraint was overridden. Concrete compatibility rule: when an
+earlier commitment keeps v1 available through or beyond release 0.4, a later message that only says
+to delete a v1 entry or compatibility alias is unacknowledged unless it explicitly names that 0.4
+support window or the prior commitment and chooses to replace it. Narrowing the deletion to one
+module, or observing that an Agent already made the edit, does not avoid or resolve that conflict.
+
+Output: {"snapshot": {"resident_memory":[],"recent_context":[],"current_state":[],
+"completed":[],"next_actions":[],"constraints":[]}, "changed_uts": [UT changes],
+"semantic_statement":"..."}. Each upsert UT needs action,id,memory_id,priority,content,queries,
+must_include,evidence_refs,source,tags. priority MUST be an integer from 0 through 100. Every
+must_include item MUST be an exact substring of content. Use action=retire with id only when evidence makes a UT stale.
+An empty changed_uts list is valid. The Snapshot must carry everything the foreground must know
+without retrieval and must treat later Working Memory as newer than the Snapshot. Keep the result
+compact: at most 4 changed UTs; merge updates into stable component-level UTs; each UT content at
+most 700 characters, at most 4 queries, and at most 3 must_include phrases. Snapshot limits are:
+resident_memory 4 items, recent_context 4, current_state 6, completed 4, next_actions 4, constraints
+6; each item at most 280 characters. Prefer exact dense facts over narration. Never copy old
+Snapshot items unchanged when a shorter merged item preserves them."""
+
+
+BUILDER_SYSTEM_PROMPT = """You are the memory build Agent. Review the frozen Pending UT batch for
+internal consistency and build readiness without changing memory semantics. Return JSON only:
+{"approved":true,"diagnostics":[]} or {"approved":false,"diagnostics":["..."]}.
+Your boundary is structural, not semantic. The extraction Agent exclusively owns fact selection,
+omission decisions, semantic conflict resolution, and Snapshot/UT wording. Do not reject because a
+UT or Snapshot omits a historical item, uses a different summary, or appears narratively incomplete.
+Reject only when this frozen batch itself cannot be deterministically built as written, for example
+an invalid schema, broken content hash, duplicate IDs with incompatible payloads, or internally
+impossible build metadata. Review the supplied batch directly and decide without open-ended
+investigation. The top-level frozen_at is the time the immutable batch was captured; each item
+updated_at is the time that UT was last published and therefore normally precedes frozen_at.
+Neither field is a UT creation timestamp, and that normal ordering is not an inconsistency.
+The content_hash is SHA-256 of canonical JSON over the UT semantic fields (id, memory_id,
+priority, content, queries, must_include, evidence_refs, source, tags, and status); it is NOT the
+SHA-256 of the content field alone. Never reject a batch by comparing content_hash with a digest
+of content alone. The Harness validates this canonical hash deterministically.
+The Harness performs deterministic construction, Built-only tests, exact-content comparison, and
+atomic migration after your approval."""
+
+
+def render_memory_context(
+ session_root: str | Path,
+ projection: dict[str, Any],
+ relevant_memory: dict[str, Any] | None = None,
+) -> str:
+ """Render the foreground contract plus the latest atomically published snapshot."""
+ root = Path(session_root)
+ raw = root / "raw-history" / "search.jsonl"
+ canonical_raw = root / "raw-history" / "events.jsonl"
+ snapshot = projection.get("snapshot") or {}
+ revision = int(projection.get("snapshot_revision") or 0)
+ covered = int(projection.get("covered_through") or 0)
+ prefetched = relevant_memory or {"query": "", "matches": []}
+ return "\n".join(
+ (
+ "<memory-access-instruction>",
+ (
+ "Use the mounted search_long_term_memory tool when the Snapshot is insufficient "
+ "or the task depends on prior decisions, constraints, commitments, preferences, "
+ "or detailed history."
+ ),
+ "Published memory records prior decisions, not immutable authority.",
+ (
+ "Conflict protocol (apply before acting or changing files): an override is "
+ "acknowledged only when the current user message refers to the earlier constraint "
+ "or decision and communicates an intent to replace it. A message that states only "
+ "the new, contradictory behavior is always unacknowledged; never infer "
+ "acknowledgment merely because the requested behavior is clearly opposite."
+ ),
+ (
+ "Compatibility example: if memory promises v1 support through or beyond release "
+ "0.4, a later request that merely says to delete a v1 entry or alias is still an "
+ "unacknowledged conflict. Ask whether to keep the 0.4 support window or override "
+ "it, even if the request can be narrowed to one module or an Agent previously "
+ "reported the deletion as completed."
+ ),
+ (
+ "Evidence wording requirement: when relevant prefetched or searched memory "
+ "contains the literal support boundary 0.4 and the request removes v1, the "
+ "conflict statement and the final clarification question MUST both repeat the "
+ "literal 0.4. A question only about module scope does not resolve that support-"
+ "window conflict."
+ ),
+ (
+ "For every suspected conflict, make at least two search_long_term_memory calls "
+ "before asking the user: search once for the exact proper noun, codename, alias, "
+ "or named constraint, and once for the affected component or contradictory "
+ "behavior. Do this even when the Snapshot already states the conflict. The "
+ "Snapshot helps notice the conflict; the published UT searches supply auditable "
+ "decision evidence. If a retrieved UT contains a user-defined proper noun, "
+ "codename, alias, or environment name, repeat that exact original term in both "
+ "the conflict statement and final question; never replace it only with a generic "
+ "label."
+ ),
+ (
+ "For an unacknowledged conflict, pause before acting. Stop further exploration "
+ "immediately. Do not accept the new request, reject it, or choose a workaround on "
+ "the user's behalf. After the required memory search returns, respond in at most "
+ "120 words: state the conflict briefly, then end with exactly one direct "
+ "clarification question naming the prior option and the new option. The final "
+ "character MUST be ? or ?. A conflict response that only explains the conflict "
+ "and omits this final question is invalid. Wait for the user's answer."
+ ),
+ "Search tool: search_long_term_memory(query)",
+ f"Complete observable Raw History search view: {raw}",
+ f"Canonical hash-chained Raw History (large fields may be content-addressed): {canonical_raw}",
+ (
+ "Use read/grep tools on the Raw History search view for evidence. It is a lossless "
+ "structural search projection for direct user messages, tool evidence, and model "
+ "responses, with canonical cursor/hash backlinks; it omits only repeated "
+ "accumulated model-context copies. Before changing existing behavior, search both "
+ "dynamic memory and Raw History for prior user constraints, commitments, "
+ "preferences, and environment assumptions. For compatibility removal, alias "
+ "removal, deprecation, or version migration, explicitly search Raw History for "
+ "the affected feature name together with support-window, version, release, "
+ "compatibility, and deprecation terms before editing. Preserve the earliest "
+ "relevant direct-user matches; a tail-only view can hide the original constraint "
+ "and is not sufficient evidence. If memory search returns only implementation "
+ "facts rather than direct user intent, Raw History is the required fallback. "
+ "Never invent missing history."
+ ),
+ "</memory-access-instruction>",
+ f'<memory-snapshot revision="{revision}" covered-through="{covered}">',
+ json.dumps(snapshot, ensure_ascii=False, indent=2),
+ "</memory-snapshot>",
+ "<relevant-long-term-memory>",
+ json.dumps(prefetched, ensure_ascii=False, indent=2),
+ "</relevant-long-term-memory>",
+ "<memory-action-gate>",
+ (
+ "Before the first non-memory tool call, inspect every prefetched match above. "
+ "A later implementation report, repeated contradictory request, or narrower "
+ "module scope does not acknowledge or replace an earlier user constraint. If "
+ "any active constraint may conflict, the only permitted tools are the required "
+ "memory searches; do not inspect or change project files until the user resolves "
+ "the conflict. In particular, a retrieved v1 support window through release 0.4 "
+ "requires a clarification that names 0.4 before any v1 entry or alias is removed."
+ ),
+ "</memory-action-gate>",
+ )
+ )
+
+
+def prompt_hashes() -> dict[str, str]:
+ """Hashes stored in every acceptance/audit manifest."""
+ values = {
+ "foreground": render_memory_context("<session-root>", {}),
+ "extractor": EXTRACTOR_SYSTEM_PROMPT,
+ "builder": BUILDER_SYSTEM_PROMPT,
+ }
+ return {name: hashlib.sha256(text.encode("utf-8")).hexdigest() for name, text in values.items()}
+
+
+__all__ = [
+ "BUILDER_SYSTEM_PROMPT",
+ "EXTRACTOR_SYSTEM_PROMPT",
+ "prompt_hashes",
+ "render_memory_context",
+]
diff --git a/jiuwenswarm/agents/harness/common/rails/eternal_conversation/rail.py b/jiuwenswarm/agents/harness/common/rails/eternal_conversation/rail.py
new file mode 100644
index 0000000000..04f45494e0
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/rails/eternal_conversation/rail.py
@@ -0,0 +1,430 @@
+"""Pluggable, inert-by-default eternal-conversation Rail."""
+
+from __future__ import annotations
+
+import json
+import logging
+import uuid
+from typing import Any
+
+from openjiuwen.core.foundation.tool.base import ToolCard
+from openjiuwen.core.foundation.tool.function.function import LocalFunction
+from openjiuwen.core.single_agent.rail.base import AgentCallbackContext
+from openjiuwen.harness.prompts import PromptSection
+from openjiuwen.harness.rails.base import DeepAgentRail
+
+from jiuwenswarm.common.utils import get_agent_sessions_dir
+
+from .coordinator import SessionCoordinator
+from .evidence import jsonable, read_json
+from .prompts import render_memory_context
+from .registry import get_session_coordinator
+
+logger = logging.getLogger(__name__)
+
+FOREGROUND_CONTEXT_REPLACEMENT_MESSAGE_LIMIT = 1000
+FOREGROUND_CONTEXT_REPLACEMENT_BYTE_LIMIT = 512 * 1024
+
+
+class EternalConversationRail(DeepAgentRail):
+ """Record foreground evidence and schedule two isolated background Agents.
+
+ One instance belongs to one session-scoped Adapter. It is always mounted so
+ enabling the feature does not rebuild the Agent, but does no work and does
+ not expose its tool until the request runtime flag is true.
+
+ Stateful session-level Rail: init/configure_runtime bind _agent/_builder/
+ _session_id/_coordinator. It must never be inherited by reference into a
+ general-purpose subagent (factory._inject_general_purpose_subagent), whose
+ _ensure_initialized would rebind the shared instance — the rail/base.py
+ inheritance trap. TaskExecutionRail / ProgressiveToolRail /
+ CodingArtifactPostProcessRail opt out the same way.
+ """
+
+ inherit_to_subagents = False
+
+ priority = 80
+ SECTION_NAME = "eternal_conversation"
+ # Upstream develop resolves this via SystemPromptPriority.ETERNAL_CONVERSATION
+ # in prompt/priority_registry.py (commit dc4f6e911); dev-stable does not carry
+ # that registry yet. 94 matches upstream and avoids colliding with the 90
+ # slot shared by trusted_dirs_policy (runtime_prompt_rail) and the framework
+ # offload/compression_recall/reload/todo sections.
+ SECTION_PRIORITY = 94
+ TOOL_NAME = "search_long_term_memory"
+
+ def __init__(self) -> None:
+ super().__init__()
+ self._agent: Any = None
+ self._builder: Any = None
+ self._enabled = False
+ self._session_id: str | None = None
+ self._request_id: str | None = None
+ self._mode = ""
+ self._channel = ""
+ self._project_dir: str | None = None
+ self._model: Any = None
+ self._coordinator: SessionCoordinator | None = None
+ self._tool_card: ToolCard | None = None
+ self._tool: LocalFunction | None = None
+ self._tool_registered = False
+ self._task_id: str | None = None
+ self._interaction_resume = False
+ self._pending_projection: dict[str, Any] | None = None
+ self._prefetched_memory: dict[str, Any] | None = None
+
+ def init(self, agent: Any) -> None:
+ self._agent = agent
+ self._builder = getattr(agent, "system_prompt_builder", None)
+ self._tool_card = ToolCard(
+ id="eternal_conversation_search_long_term_memory",
+ name=self.TOOL_NAME,
+ description=(
+ "Search all published long-term memory. Results uniformly include both "
+ "Pending and Built retrieval units. Use exact project names, aliases, "
+ "constraints, version boundaries, or short key phrases."
+ ),
+ input_params={
+ "type": "object",
+ "properties": {
+ "query": {"type": "string", "description": "Keyword or key phrase"}
+ },
+ "required": ["query"],
+ },
+ parallel_safe=True,
+ stateless=False,
+ idempotent=True,
+ )
+
+ async def search_long_term_memory(query: str) -> dict[str, Any]:
+ if not self._enabled or self._coordinator is None:
+ return {"error": "eternal_conversation_disabled", "matches": []}
+ result = await self._coordinator.memory.search(query)
+ await self._coordinator.evidence.append_audit(
+ "foreground-memory-searches",
+ {"task_id": self._task_id, "query": query, "result": result},
+ )
+ return result
+
+ self._tool = LocalFunction(card=self._tool_card, func=search_long_term_memory)
+ self._set_tool_enabled(False)
+
+ def uninit(self, agent: Any) -> None:
+ if self._builder is not None:
+ self._builder.remove_section(self.SECTION_NAME)
+ self._set_tool_enabled(False)
+ self._agent = None
+ self._builder = None
+
+ def configure_runtime(
+ self,
+ *,
+ enabled: bool,
+ session_id: str | None,
+ request_id: str | None,
+ mode: str,
+ channel: str,
+ project_dir: str | None,
+ model: Any,
+ interaction_resume: bool = False,
+ ) -> None:
+ """Bind request values without sharing mutable state across Sessions."""
+ normalized_session = str(session_id or "").strip() or None
+ if enabled and normalized_session is None:
+ raise ValueError("eternal conversation requires a session_id")
+ if (
+ self._session_id is not None
+ and normalized_session is not None
+ and self._session_id != normalized_session
+ ):
+ raise RuntimeError("one EternalConversationRail cannot serve multiple Sessions")
+ self._enabled = bool(enabled)
+ self._session_id = normalized_session or self._session_id
+ self._request_id = request_id
+ self._mode = str(mode or "")
+ self._channel = str(channel or "")
+ self._project_dir = project_dir
+ self._model = model
+ self._interaction_resume = bool(interaction_resume)
+ if self._enabled and self._coordinator is None:
+ root = get_agent_sessions_dir() / self._session_id / "eternal-conversation"
+ self._coordinator = get_session_coordinator(
+ root, self._session_id, lambda: self._model
+ )
+ self._set_tool_enabled(self._enabled)
+ if not self._enabled and self._builder is not None:
+ self._builder.remove_section(self.SECTION_NAME)
+
+ def _set_tool_enabled(self, enabled: bool) -> None:
+ manager = getattr(self._agent, "ability_manager", None)
+ if manager is None or self._tool_card is None or self._tool is None:
+ return
+ if enabled and not self._tool_registered:
+ result = manager.add_ability(self._tool_card, self._tool)
+ self._tool_registered = bool(getattr(result, "added", True))
+ elif not enabled and self._tool_registered:
+ remove_ability = getattr(manager, "remove_ability", None)
+ if callable(remove_ability):
+ remove_ability(self.TOOL_NAME)
+ else:
+ manager.remove(self.TOOL_NAME)
+ self._tool_registered = False
+
+ async def before_invoke(self, ctx: AgentCallbackContext) -> None:
+ if not self._enabled or self._coordinator is None:
+ return
+ await self._coordinator.resume_background()
+ if self._interaction_resume:
+ if self._task_id is None:
+ raise RuntimeError("eternal conversation resume has no active natural task")
+ await self._coordinator.evidence.append(
+ "task-resumed",
+ {"interaction_request_id": self._request_id},
+ task_id=self._task_id,
+ )
+ return
+ self._task_id = self._request_id or f"task-{uuid.uuid4().hex}"
+ query = str(getattr(ctx.inputs, "query", None) or "").strip()
+ self._prefetched_memory = None
+ if query:
+ try:
+ result = await self._coordinator.memory.search(query)
+ matches = list(result.get("matches") or [])
+ matches.sort(
+ key=lambda item: (
+ "support-window" not in set(item.get("tags") or []),
+ "constraint" not in set(item.get("tags") or []),
+ )
+ )
+ self._prefetched_memory = {
+ "query": query,
+ "matches": matches[:12],
+ }
+ except Exception as exc:
+ # Automatic prefetch enriches the prompt but is not required for
+ # the foreground task. The explicit search tool remains available.
+ logger.exception(
+ "Eternal-conversation automatic memory prefetch failed "
+ "for session=%s task=%s",
+ self._session_id,
+ self._task_id,
+ )
+ try:
+ await self._coordinator.evidence.append_audit(
+ "foreground-memory-searches",
+ {
+ "task_id": self._task_id,
+ "query": query,
+ "source": "automatic-request-prefetch",
+ "status": "failed",
+ "error_type": type(exc).__name__,
+ },
+ )
+ except Exception:
+ logger.exception(
+ "Failed to record automatic memory prefetch failure "
+ "for session=%s task=%s",
+ self._session_id,
+ self._task_id,
+ )
+ else:
+ try:
+ await self._coordinator.evidence.append_audit(
+ "foreground-memory-searches",
+ {
+ "task_id": self._task_id,
+ "query": query,
+ "result": self._prefetched_memory,
+ "source": "automatic-request-prefetch",
+ "status": "succeeded",
+ },
+ )
+ except Exception:
+ logger.exception(
+ "Failed to audit automatic memory prefetch "
+ "for session=%s task=%s",
+ self._session_id,
+ self._task_id,
+ )
+ # In the real ReactAgent lifecycle BEFORE_INVOKE fires before the
+ # ModelContext is initialized. Prepare the revision here, then apply it
+ # in ON_USER_MESSAGE, which runs after context initialization but before
+ # the new user input is admitted. This creates an actual safe boundary
+ # without changing the framework's Rail mechanism.
+ self._pending_projection = await self._coordinator.projection_for_boundary()
+ await self._coordinator.evidence.append(
+ "task-started",
+ {
+ "query": getattr(ctx.inputs, "query", None),
+ "mode": self._mode,
+ "channel": self._channel,
+ "project_dir": self._project_dir,
+ },
+ task_id=self._task_id,
+ )
+
+ async def on_user_message(self, ctx: AgentCallbackContext) -> None:
+ if not self._enabled or self._coordinator is None:
+ return
+ source = getattr(ctx.inputs, "source", None)
+ if not self._interaction_resume and source == "query":
+ if self._pending_projection is None:
+ self._pending_projection = (
+ await self._coordinator.projection_for_boundary()
+ )
+ context = getattr(ctx, "context", None)
+ if self._pending_projection is None and context is not None:
+ messages = context.get_messages()
+ encoded_size = len(
+ json.dumps(
+ jsonable(messages),
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ ).encode("utf-8")
+ )
+ if (
+ len(messages) > FOREGROUND_CONTEXT_REPLACEMENT_MESSAGE_LIMIT
+ or encoded_size > FOREGROUND_CONTEXT_REPLACEMENT_BYTE_LIMIT
+ ):
+ self._pending_projection = (
+ await self._coordinator.projection_for_boundary(force=True)
+ )
+ await self._apply_pending_projection(ctx)
+ await self._coordinator.evidence.append(
+ "user-message",
+ {"parts": getattr(ctx.inputs, "parts", []), "source": source},
+ task_id=self._task_id,
+ )
+
+ async def _apply_pending_projection(self, ctx: AgentCallbackContext) -> None:
+ projection = self._pending_projection
+ context = getattr(ctx, "context", None)
+ if projection is None or context is None or self._coordinator is None:
+ return
+ previous = context.get_messages()
+ context.set_messages([])
+ await self._coordinator.evidence.append(
+ "context-replaced",
+ {
+ "snapshot_revision": projection.get("snapshot_revision"),
+ "memory_revision": projection.get("memory_revision"),
+ "covered_through": projection.get("covered_through"),
+ "replaced_messages": previous,
+ "safe_boundary": "before-user-message-admission",
+ },
+ task_id=self._task_id,
+ )
+ await self._coordinator.mark_projection_applied(
+ int(projection.get("snapshot_revision") or 0)
+ )
+ self._pending_projection = None
+
+ async def before_model_call(self, ctx: AgentCallbackContext) -> None:
+ if not self._enabled or self._coordinator is None or self._builder is None:
+ return
+ projection = read_json(self._coordinator.projection_path, {}) or {}
+ content = render_memory_context(
+ self._coordinator.root,
+ projection,
+ self._prefetched_memory,
+ )
+ language = getattr(self._builder, "language", "cn") or "cn"
+ self._builder.add_section(
+ PromptSection(
+ name=self.SECTION_NAME,
+ content={"cn": content, "en": content, language: content},
+ priority=self.SECTION_PRIORITY,
+ )
+ )
+
+ async def after_model_call(self, ctx: AgentCallbackContext) -> None:
+ await self._record_model_envelope(ctx, status="succeeded")
+
+ async def on_model_exception(self, ctx: AgentCallbackContext) -> None:
+ await self._record_model_envelope(ctx, status="failed")
+
+ async def _record_model_envelope(self, ctx: AgentCallbackContext, *, status: str) -> None:
+ if not self._enabled or self._coordinator is None:
+ return
+ response = getattr(ctx.inputs, "response", None)
+ await self._coordinator.evidence.append(
+ "model-visible-envelope",
+ {
+ "status": status,
+ "messages": getattr(ctx.inputs, "messages", []),
+ "tools": getattr(ctx.inputs, "tools", None),
+ "response": response,
+ "usage": getattr(response, "usage_metadata", None),
+ "exception": str(ctx.exception) if ctx.exception else None,
+ },
+ task_id=self._task_id,
+ )
+
+ async def before_tool_call(self, ctx: AgentCallbackContext) -> None:
+ if not self._enabled or self._coordinator is None:
+ return
+ await self._coordinator.evidence.append(
+ "tool-call",
+ {
+ "tool_name": getattr(ctx.inputs, "tool_name", ""),
+ "tool_args": getattr(ctx.inputs, "tool_args", None),
+ "tool_call": getattr(ctx.inputs, "tool_call", None),
+ },
+ task_id=self._task_id,
+ )
+
+ async def after_tool_call(self, ctx: AgentCallbackContext) -> None:
+ await self._record_tool_result(ctx, status="succeeded")
+
+ async def on_tool_exception(self, ctx: AgentCallbackContext) -> None:
+ await self._record_tool_result(ctx, status="failed")
+
+ async def _record_tool_result(self, ctx: AgentCallbackContext, *, status: str) -> None:
+ if not self._enabled or self._coordinator is None:
+ return
+ await self._coordinator.evidence.append(
+ "tool-result",
+ {
+ "status": status,
+ "tool_name": getattr(ctx.inputs, "tool_name", ""),
+ "tool_args": getattr(ctx.inputs, "tool_args", None),
+ "tool_result": getattr(ctx.inputs, "tool_result", None),
+ "tool_message": getattr(ctx.inputs, "tool_msg", None),
+ "exception": str(ctx.exception) if ctx.exception else None,
+ },
+ task_id=self._task_id,
+ )
+
+ async def after_invoke(self, ctx: AgentCallbackContext) -> None:
+ if not self._enabled or self._coordinator is None:
+ return
+ result = jsonable(getattr(ctx.inputs, "result", None))
+ if isinstance(result, dict) and result.get("result_type") == "interrupt":
+ await self._coordinator.evidence.append(
+ "task-suspended",
+ {"result": result},
+ task_id=self._task_id,
+ )
+ return
+ event = await self._coordinator.evidence.append(
+ "task-finished",
+ {"result": result},
+ task_id=self._task_id,
+ )
+ await self._coordinator.request_extract(int(event["cursor"]))
+
+ async def close(self) -> None:
+ # Coordinator lifetime follows the durable Session. Web/TUI routinely
+ # retire short-lived Adapters before Extractor/Builder has converged.
+ self._agent = None
+ self._builder = None
+ self._pending_projection = None
+ self._prefetched_memory = None
+
+ async def wait_idle(self) -> None:
+ if self._coordinator is not None:
+ await self._coordinator.wait_idle()
+
+
+__all__ = ["EternalConversationRail"]
diff --git a/jiuwenswarm/agents/harness/common/rails/eternal_conversation/registry.py b/jiuwenswarm/agents/harness/common/rails/eternal_conversation/registry.py
new file mode 100644
index 0000000000..848a34f3f6
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/rails/eternal_conversation/registry.py
@@ -0,0 +1,46 @@
+"""Process-level Session ownership for eternal-conversation coordinators."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any, Callable
+from weakref import WeakValueDictionary
+
+from .coordinator import SessionCoordinator
+
+
+_COORDINATORS: WeakValueDictionary[tuple[str, str], SessionCoordinator] = (
+ WeakValueDictionary()
+)
+
+
+def get_session_coordinator(
+ root: Path,
+ session_id: str,
+ model_supplier: Callable[[], Any],
+) -> SessionCoordinator:
+ """Return the one coordinator for a durable product Session.
+
+ Web/TUI may retire and recreate their session-scoped Adapter while the two
+ background Agents are still running. Coordinator ownership therefore
+ follows the product Session, not the short-lived Adapter/Rail instance.
+ """
+ key = (str(root.resolve()), session_id)
+ coordinator = _COORDINATORS.get(key)
+ if coordinator is None or coordinator.closed:
+ coordinator = SessionCoordinator(root, session_id, model_supplier)
+ _COORDINATORS[key] = coordinator
+ else:
+ coordinator.agents.set_model_supplier(model_supplier)
+ return coordinator
+
+
+async def close_all_session_coordinators() -> None:
+ """Explicit process-shutdown/test hook; ordinary Rail cleanup must not call it."""
+ from .coordinator import close_live_coordinators
+
+ _COORDINATORS.clear()
+ await close_live_coordinators()
+
+
+__all__ = ["close_all_session_coordinators", "get_session_coordinator"]
diff --git a/jiuwenswarm/common/schema/chat_send.py b/jiuwenswarm/common/schema/chat_send.py
index a8041312a0..5eed426f55 100644
--- a/jiuwenswarm/common/schema/chat_send.py
+++ b/jiuwenswarm/common/schema/chat_send.py
@@ -63,6 +63,13 @@ class ChatSendParams(TypedDict, total=False):
supports_user_interaction: NotRequired[bool]
"""客户端是否能处理 ask_user 等用户交互。缺省为 True,兼容现有客户端。"""
+ eternal_conversation_enabled: NotRequired[bool]
+ """DEPRECATED:旧 Session 的一次性迁移字段。
+
+ 新客户端必须在 ``session.create`` 发送 ``persist_session``;本字段不能覆盖
+ 已初始化 Session 的权威值。
+ """
+
plan_entry_source: NotRequired[str]
"""plan 模式入口来源(internal use)。"""
diff --git a/jiuwenswarm/resources/agent/workspace/skills/dynamic-memory-cli/SKILL.md b/jiuwenswarm/resources/agent/workspace/skills/dynamic-memory-cli/SKILL.md
new file mode 100644
index 0000000000..f9e204a218
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/dynamic-memory-cli/SKILL.md
@@ -0,0 +1,54 @@
+---
+name: dynamic-memory-cli
+description: Operate a dynamic, UT-backed agent memory with atomic Pending publication, merged Pending/Built search, Memory Snapshot and history cursor state, Built-only validation, and exact-content migration. Use when an agent Harness must extract memory asynchronously while foreground work continues, publish immediately searchable Pending UTs, build them into a stable index, or inspect and recover an eternal-conversation memory project.
+---
+
+# Dynamic Memory CLI
+
+Use `scripts/dynamic_memory_cli.py` as the deterministic boundary between a conversation Harness and its memory state. Keep semantic selection in the extraction Agent; keep validation, revisions, cursors, publication, search, and migration in this CLI.
+
+## Required workflow
+
+1. Run `init --path <session-memory-dir>` once.
+2. Let the extraction Agent read the old Snapshot, frozen Working Memory, published UTs, and Raw History evidence.
+3. Submit one proposal with `publish-pending --file <proposal.json>`. Never expose an Agent's scratch buffer directly.
+4. Use `search` immediately. Published Pending UTs participate through lexical matching and are marked `pending` in results.
+5. Run `freeze-pending --output <batch.json>` for a stable exact-content batch.
+6. Let the builder Agent review that batch, then run `build-pending --file <batch.json>`.
+7. Treat a successful build as an atomic representation migration. It does not advance semantic memory revision, Snapshot revision, or history cursor.
+
+Read [references/dynamic-memory-contract.md](references/dynamic-memory-contract.md) before creating proposals or integrating a Harness.
+
+## Command contract
+
+Run from the memory project directory unless `init --path` is used:
+
+```text
+python scripts/dynamic_memory_cli.py init --path <dir>
+python scripts/dynamic_memory_cli.py search <query> [query...]
+python scripts/dynamic_memory_cli.py list [--full]
+python scripts/dynamic_memory_cli.py show <id>
+python scripts/dynamic_memory_cli.py check-conflicts --file <candidate.json>
+python scripts/dynamic_memory_cli.py add --file <ut.json> [--force]
+python scripts/dynamic_memory_cli.py update <id> --file <updates.json>
+python scripts/dynamic_memory_cli.py retire <id> [--reason <text>]
+python scripts/dynamic_memory_cli.py get-state
+python scripts/dynamic_memory_cli.py publish-pending --file <proposal.json>
+python scripts/dynamic_memory_cli.py freeze-pending --output <batch.json>
+python scripts/dynamic_memory_cli.py build-pending --file <batch.json>
+python scripts/dynamic_memory_cli.py test [--built-only]
+python scripts/dynamic_memory_cli.py bench
+```
+
+Use the global `--root <session-memory-dir>` option before the subcommand when the caller cannot change its working directory.
+
+Do not edit `memory.sqlite3` manually. Preserve stable UT IDs. Modifying a Built UT must republish it as Pending. Do not advance a cursor unless Snapshot and UT changes are committed in the same `publish-pending` transaction.
+
+## Agent boundaries
+
+- Extraction Agent: decide what to remember, resolve semantic conflicts, author UTs, and produce Snapshot content.
+- Builder Agent: review a frozen Pending batch and request deterministic construction and Built-only validation.
+- Harness: verify identity/range/version inputs and invoke atomic commands.
+- CLI: enforce schemas, continuity, exact-content comparison, transactions, search merging, and test gates.
+
+Save each foreground, extractor, and builder transcript outside the database in the session's Raw History or agent-history area. Store evidence references on every changed UT and on empty-UT proposals.
diff --git a/jiuwenswarm/resources/agent/workspace/skills/dynamic-memory-cli/SOURCE.json b/jiuwenswarm/resources/agent/workspace/skills/dynamic-memory-cli/SOURCE.json
new file mode 100644
index 0000000000..4a342546cf
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/dynamic-memory-cli/SOURCE.json
@@ -0,0 +1,6 @@
+{
+ "implementation": "jiuwenswarm.dynamic-memory-cli",
+ "contract_version": 1,
+ "path": "skills/dynamic-memory-cli/",
+ "integration": "persist-session"
+}
diff --git a/jiuwenswarm/resources/agent/workspace/skills/dynamic-memory-cli/agents/openai.yaml b/jiuwenswarm/resources/agent/workspace/skills/dynamic-memory-cli/agents/openai.yaml
new file mode 100644
index 0000000000..de8c189bba
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/dynamic-memory-cli/agents/openai.yaml
@@ -0,0 +1,4 @@
+interface:
+ display_name: "Dynamic Memory CLI"
+ short_description: "Operate atomic Pending and Built agent memory."
+ default_prompt: "Use $dynamic-memory-cli to publish Pending retrieval UTs, search merged memory, and build verified Built indexes."
diff --git a/jiuwenswarm/resources/agent/workspace/skills/dynamic-memory-cli/references/dynamic-memory-contract.md b/jiuwenswarm/resources/agent/workspace/skills/dynamic-memory-cli/references/dynamic-memory-contract.md
new file mode 100644
index 0000000000..575c484897
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/dynamic-memory-cli/references/dynamic-memory-contract.md
@@ -0,0 +1,60 @@
+# Dynamic Memory Contract
+
+## Formal state
+
+The SQLite database owns the atomically published tuple:
+
+```text
+(memory_revision, snapshot_revision, covered_through, snapshot, UT set, Built index)
+```
+
+UT build state has exactly two values: `pending` and `built`. A task-local proposal file is not published memory. A UT becomes formal Long-term Memory only after `publish-pending` commits it with the Snapshot and cursor.
+
+## Proposal schema
+
+```json
+{
+ "base_memory_revision": 4,
+ "base_snapshot_revision": 7,
+ "from_cursor": 81,
+ "to_cursor": 120,
+ "snapshot": {
+ "resident_memory": [],
+ "recent_context": [],
+ "current_state": [],
+ "completed": [],
+ "next_actions": [],
+ "constraints": []
+ },
+ "changed_uts": [
+ {
+ "action": "upsert",
+ "id": "ut-stable-id",
+ "memory_id": "memory-stable-id",
+ "priority": 80,
+ "content": "Answer-bearing durable memory.",
+ "queries": ["future query one", "future query two"],
+ "must_include": ["durable memory"],
+ "evidence_refs": ["raw-history:event-101"],
+ "source": "session-id",
+ "tags": ["decision"]
+ }
+ ],
+ "evidence_refs": ["raw-history:range-81-120"],
+ "semantic_statement": "The Snapshot and UT changes preserve every future-relevant effect in the frozen range."
+}
+```
+
+`from_cursor` must equal the current `covered_through + 1`, and `to_cursor` must not move backward. Empty `changed_uts` is valid but still requires a non-empty Snapshot, evidence references, and semantic statement.
+
+## Retrieval
+
+Pending search scores the current UT content and Agent-authored queries directly. Built search scores only the committed Built document whose content hash still matches the current UT. Merge by stable UT ID; current Pending content shadows a stale Built artifact. Return complete memory content and `build_state`.
+
+Pending and Built have the same target semantics. Built-only validation proves every frozen UT query retrieves its own complete content with every `must_include` assertion present. It deliberately disables Pending fallback.
+
+## Concurrency and recovery
+
+Use SQLite `BEGIN IMMEDIATE` transactions for publication and migration. A frozen build batch includes stable IDs, exact content, and content hashes. `build-pending` skips or rejects any item changed since freezing; it never clears unrelated Pending UTs. Failure leaves the prior published state searchable.
+
+The Harness may retry a proposal only against the revisions and cursor on which it was based. A stale proposal must be regenerated by the extraction Agent.
diff --git a/jiuwenswarm/resources/agent/workspace/skills/dynamic-memory-cli/scripts/dynamic_memory_cli.py b/jiuwenswarm/resources/agent/workspace/skills/dynamic-memory-cli/scripts/dynamic_memory_cli.py
new file mode 100644
index 0000000000..4c7601b595
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/dynamic-memory-cli/scripts/dynamic_memory_cli.py
@@ -0,0 +1,590 @@
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import logging
+import os
+import re
+import sqlite3
+import statistics
+import sys
+import time
+import unicodedata
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+
+SCHEMA_VERSION = 1
+DB_NAME = "memory.sqlite3"
+
+
+class ClosingConnection(sqlite3.Connection):
+ def __exit__(self, exc_type: Any, exc: Any, traceback: Any) -> bool:
+ try:
+ return super().__exit__(exc_type, exc, traceback)
+ finally:
+ self.close()
+
+
+def now() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def normalize(value: Any) -> str:
+ return unicodedata.normalize("NFKC", str(value)).casefold()
+
+
+def tokens(value: Any) -> list[str]:
+ return re.findall(r"\w+", normalize(value), flags=re.UNICODE)
+
+
+def content_hash(record: dict[str, Any]) -> str:
+ semantic: dict[str, Any] = {}
+ semantic_keys = (
+ "id", "memory_id", "priority", "content", "queries", "must_include",
+ "evidence_refs", "source", "tags", "status",
+ )
+ for key in semantic_keys:
+ semantic[key] = record.get(key)
+ payload = json.dumps(semantic, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()
+
+
+def root_path(value: str | Path | None = None) -> Path:
+ return Path(value or Path.cwd()).expanduser().resolve()
+
+
+def connect(root: Path) -> sqlite3.Connection:
+ root.mkdir(parents=True, exist_ok=True)
+ conn = sqlite3.connect(root / DB_NAME, timeout=30, factory=ClosingConnection)
+ conn.row_factory = sqlite3.Row
+ conn.execute("PRAGMA journal_mode=WAL")
+ conn.execute("PRAGMA foreign_keys=ON")
+ return conn
+
+
+def init_project(root: Path) -> dict[str, Any]:
+ with connect(root) as conn:
+ conn.executescript(
+ """
+ CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY, value TEXT NOT NULL);
+ CREATE TABLE IF NOT EXISTS uts(
+ id TEXT PRIMARY KEY, memory_id TEXT NOT NULL, priority INTEGER NOT NULL,
+ status TEXT NOT NULL, build_state TEXT NOT NULL, content TEXT NOT NULL,
+ queries_json TEXT NOT NULL, must_include_json TEXT NOT NULL,
+ evidence_refs_json TEXT NOT NULL, source TEXT NOT NULL, tags_json TEXT NOT NULL,
+ content_hash TEXT NOT NULL, updated_at TEXT NOT NULL
+ );
+ CREATE TABLE IF NOT EXISTS built_docs(
+ ut_id TEXT PRIMARY KEY REFERENCES uts(id) ON DELETE CASCADE,
+ content_hash TEXT NOT NULL, document TEXT NOT NULL, built_at TEXT NOT NULL
+ );
+ """
+ )
+ defaults = {
+ "schema_version": SCHEMA_VERSION,
+ "memory_revision": 0,
+ "snapshot_revision": 0,
+ "covered_through": 0,
+ "snapshot": {},
+ }
+ for key, value in defaults.items():
+ conn.execute("INSERT OR IGNORE INTO meta(key,value) VALUES(?,?)", (key, json.dumps(value)))
+ return {"status": "initialized", "root": str(root), "database": str(root / DB_NAME)}
+
+
+def require_project(root: Path) -> None:
+ if not (root / DB_NAME).exists():
+ raise ValueError(f"dynamic memory project not found at {root}")
+
+
+def get_meta(conn: sqlite3.Connection, key: str) -> Any:
+ row = conn.execute("SELECT value FROM meta WHERE key=?", (key,)).fetchone()
+ if row is None:
+ raise ValueError(f"missing metadata: {key}")
+ return json.loads(row["value"])
+
+
+def set_meta(conn: sqlite3.Connection, key: str, value: Any) -> None:
+ conn.execute(
+ "INSERT INTO meta(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
+ (key, json.dumps(value, ensure_ascii=False)),
+ )
+
+
+def state(conn: sqlite3.Connection) -> dict[str, Any]:
+ result: dict[str, Any] = {}
+ metadata_keys = (
+ "schema_version", "memory_revision", "snapshot_revision", "covered_through", "snapshot"
+ )
+ for key in metadata_keys:
+ result[key] = get_meta(conn, key)
+ return result
+
+
+def decode_row(row: sqlite3.Row) -> dict[str, Any]:
+ value = dict(row)
+ for field in ("queries", "must_include", "evidence_refs", "tags"):
+ value[field] = json.loads(value.pop(f"{field}_json"))
+ return value
+
+
+def validate_ut(value: dict[str, Any]) -> list[dict[str, Any]]:
+ errors: list[dict[str, Any]] = []
+ required = ("id", "memory_id", "priority", "content", "queries", "must_include", "evidence_refs", "source")
+ missing = [key for key in required if key not in value]
+ if missing:
+ errors.append({"code": "missing_fields", "fields": missing})
+ for key in ("id", "memory_id", "content", "source"):
+ if not isinstance(value.get(key), str) or not value.get(key, "").strip():
+ errors.append({"code": "invalid_string", "field": key})
+ priority = value.get("priority")
+ if not isinstance(priority, int) or isinstance(priority, bool) or not 0 <= priority <= 100:
+ errors.append({"code": "invalid_priority"})
+ for key in ("queries", "must_include", "evidence_refs"):
+ items = value.get(key)
+ if not isinstance(items, list) or not items or not all(isinstance(x, str) and x.strip() for x in items):
+ errors.append({"code": "invalid_string_list", "field": key})
+ content = normalize(value.get("content", ""))
+ for phrase in value.get("must_include") or []:
+ if normalize(phrase) not in content:
+ errors.append({"code": "must_include_missing", "phrase": phrase})
+ if value.get("status", "active") not in {"active", "retired"}:
+ errors.append({"code": "invalid_status"})
+ return errors
+
+
+def upsert_ut(conn: sqlite3.Connection, value: dict[str, Any], *, force_pending: bool = True) -> None:
+ errors = validate_ut(value)
+ if errors:
+ raise ValueError(json.dumps(errors, ensure_ascii=False))
+ record = {
+ **value,
+ "status": value.get("status", "active"),
+ "tags": value.get("tags", []),
+ "build_state": "pending" if force_pending else value.get("build_state", "pending"),
+ }
+ digest = content_hash(record)
+ conn.execute(
+ """INSERT INTO uts(id,memory_id,priority,status,build_state,content,queries_json,
+ must_include_json,evidence_refs_json,source,tags_json,content_hash,updated_at)
+ VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)
+ ON CONFLICT(id) DO UPDATE SET memory_id=excluded.memory_id,priority=excluded.priority,
+ status=excluded.status,build_state=excluded.build_state,content=excluded.content,
+ queries_json=excluded.queries_json,must_include_json=excluded.must_include_json,
+ evidence_refs_json=excluded.evidence_refs_json,source=excluded.source,tags_json=excluded.tags_json,
+ content_hash=excluded.content_hash,updated_at=excluded.updated_at""",
+ (
+ record.get("id"),
+ record.get("memory_id"),
+ record.get("priority"),
+ record.get("status"),
+ record.get("build_state"),
+ record.get("content"),
+ json.dumps(record.get("queries"), ensure_ascii=False),
+ json.dumps(record.get("must_include"), ensure_ascii=False),
+ json.dumps(record.get("evidence_refs"), ensure_ascii=False),
+ record.get("source"),
+ json.dumps(record.get("tags"), ensure_ascii=False),
+ digest,
+ now(),
+ ),
+ )
+
+
+def score(query: str, document: str) -> int:
+ q = normalize(query).strip()
+ d = normalize(document)
+ if not q:
+ return 0
+ value = 20 if q in d else 0
+ q_tokens = tokens(q)
+ d_tokens = set(tokens(d))
+ value += sum(3 for token in q_tokens if token in d_tokens)
+ return value
+
+
+def search_one(
+ conn: sqlite3.Connection,
+ query: str,
+ *,
+ built_only: bool = False,
+ candidate_ids: set[str] | None = None,
+) -> dict[str, Any]:
+ matches: dict[str, dict[str, Any]] = {}
+ candidate_ids = candidate_ids or set()
+ rows = conn.execute("SELECT * FROM uts WHERE status='active'").fetchall()
+ for row in rows:
+ ut = decode_row(row)
+ if not built_only and ut["build_state"] == "pending":
+ document = "\n".join(
+ [ut["content"], *ut["queries"], *ut["must_include"], *ut["tags"], ut["source"]]
+ )
+ else:
+ built = conn.execute("SELECT * FROM built_docs WHERE ut_id=?", (ut["id"],)).fetchone()
+ eligible = ut["build_state"] == "built" or ut["id"] in candidate_ids
+ if built is None or not eligible or built["content_hash"] != ut["content_hash"]:
+ continue
+ document = built["document"]
+ rank = score(query, document)
+ if rank <= 0:
+ continue
+ matches[ut["id"]] = {
+ "id": ut["id"], "memory_id": ut["memory_id"], "priority": ut["priority"],
+ "score": rank, "content": ut["content"], "tags": ut["tags"],
+ "source": ut["source"], "evidence_refs": ut["evidence_refs"],
+ "build_state": "built" if built_only or ut["build_state"] == "built" else "pending",
+ }
+ ordered = sorted(
+ matches.values(),
+ key=lambda item: (-item["priority"], -item["score"], item["id"]),
+ )
+ return {"query": query, "matches": ordered}
+
+
+def search(root: Path, queries: list[str], *, built_only: bool = False) -> dict[str, Any]:
+ with connect(root) as conn:
+ groups = [search_one(conn, query, built_only=built_only) for query in queries]
+ return groups[0] if len(groups) == 1 else {"queries": groups}
+
+
+def list_uts(root: Path, *, full: bool = False) -> dict[str, Any]:
+ with connect(root) as conn:
+ values = [decode_row(row) for row in conn.execute("SELECT * FROM uts ORDER BY priority DESC,id")]
+ if not full:
+ summary_keys = ("id", "memory_id", "priority", "status", "build_state", "source")
+ values = [{key: value[key] for key in summary_keys} for value in values]
+ return {"memories": values}
+
+
+def show(root: Path, ut_id: str) -> dict[str, Any]:
+ with connect(root) as conn:
+ row = conn.execute("SELECT * FROM uts WHERE id=?", (ut_id,)).fetchone()
+ return {"error": "not_found", "id": ut_id} if row is None else {"memory": decode_row(row)}
+
+
+def publish_pending(root: Path, proposal: dict[str, Any]) -> dict[str, Any]:
+ required_keys = (
+ "base_memory_revision",
+ "base_snapshot_revision",
+ "from_cursor",
+ "to_cursor",
+ "snapshot",
+ "changed_uts",
+ "evidence_refs",
+ "semantic_statement",
+ )
+ for key in required_keys:
+ if key not in proposal:
+ raise ValueError(f"proposal missing {key}")
+ if not isinstance(proposal["snapshot"], dict) or not proposal["snapshot"]:
+ raise ValueError("snapshot must be a non-empty object")
+ if not proposal["evidence_refs"] or not str(proposal["semantic_statement"]).strip():
+ raise ValueError("proposal requires evidence_refs and semantic_statement")
+ with connect(root) as conn:
+ conn.execute("BEGIN IMMEDIATE")
+ current = state(conn)
+ stale_memory = proposal["base_memory_revision"] != current["memory_revision"]
+ stale_snapshot = proposal["base_snapshot_revision"] != current["snapshot_revision"]
+ if stale_memory or stale_snapshot:
+ raise ValueError("stale proposal revision")
+ if int(proposal["from_cursor"]) != int(current["covered_through"]) + 1:
+ raise ValueError("proposal range is not continuous")
+ if int(proposal["to_cursor"]) < int(proposal["from_cursor"]):
+ raise ValueError("proposal range is empty or reversed")
+ changed = list(proposal["changed_uts"])
+ for change in changed:
+ action = change.get("action", "upsert")
+ if action == "upsert":
+ upsert_ut(conn, change)
+ elif action == "retire":
+ cursor = conn.execute(
+ "UPDATE uts SET status='retired',updated_at=? WHERE id=?",
+ (now(), change.get("id")),
+ )
+ if cursor.rowcount != 1:
+ raise ValueError(f"cannot retire missing UT {change.get('id')}")
+ else:
+ raise ValueError(f"unsupported UT action: {action}")
+ if changed:
+ set_meta(conn, "memory_revision", int(current["memory_revision"]) + 1)
+ set_meta(conn, "snapshot_revision", int(current["snapshot_revision"]) + 1)
+ set_meta(conn, "covered_through", int(proposal["to_cursor"]))
+ set_meta(conn, "snapshot", proposal["snapshot"])
+ result = state(conn)
+ conn.commit()
+ return {"status": "published", "changed_ut_ids": [item.get("id") for item in changed], **result}
+
+
+def freeze_pending(root: Path, output: Path) -> dict[str, Any]:
+ with connect(root) as conn:
+ rows = conn.execute(
+ "SELECT * FROM uts WHERE status='active' AND build_state='pending' ORDER BY id"
+ )
+ items = [decode_row(row) for row in rows]
+ # This timestamp belongs to the immutable build batch, not to any UT.
+ # Calling it ``created_at`` is structurally ambiguous to the Builder: a
+ # perfectly valid UT.updated_at necessarily precedes the time at which the
+ # batch is frozen. Keep that ordering explicit in the wire format.
+ batch = {"frozen_at": now(), "items": items}
+ output.parent.mkdir(parents=True, exist_ok=True)
+ temporary = output.with_name(f".{output.name}.{os.getpid()}.tmp")
+ temporary.write_text(
+ json.dumps(batch, ensure_ascii=False, indent=2) + "\n",
+ encoding="utf-8",
+ )
+ os.replace(temporary, output)
+ return {"status": "frozen", "count": len(items), "output": str(output)}
+
+
+def build_pending(root: Path, batch: dict[str, Any]) -> dict[str, Any]:
+ items = list(batch.get("items") or [])
+ with connect(root) as conn:
+ conn.execute("BEGIN IMMEDIATE")
+ ids: set[str] = set()
+ skipped: list[str] = []
+ for frozen in items:
+ row = conn.execute(
+ "SELECT * FROM uts WHERE id=? AND status='active'",
+ (frozen.get("id"),),
+ ).fetchone()
+ if row is None:
+ skipped.append(str(frozen.get("id")))
+ continue
+ current = decode_row(row)
+ if (
+ current["build_state"] != "pending"
+ or current["content_hash"] != frozen.get("content_hash")
+ ):
+ skipped.append(current["id"])
+ continue
+ document = "\n".join(
+ [
+ current["content"],
+ *current["queries"],
+ *current["must_include"],
+ *current["tags"],
+ current["source"],
+ ]
+ )
+ conn.execute(
+ """INSERT INTO built_docs(ut_id,content_hash,document,built_at)
+ VALUES(?,?,?,?) ON CONFLICT(ut_id) DO UPDATE SET
+ content_hash=excluded.content_hash,document=excluded.document,
+ built_at=excluded.built_at""",
+ (current["id"], current["content_hash"], document, now()),
+ )
+ ids.add(current["id"])
+ failures: list[dict[str, Any]] = []
+ for ut_id in ids:
+ row = conn.execute("SELECT * FROM uts WHERE id=?", (ut_id,)).fetchone()
+ ut = decode_row(row)
+ for query in ut["queries"]:
+ result = search_one(conn, query, built_only=True, candidate_ids=ids)
+ match = next((item for item in result["matches"] if item["id"] == ut_id), None)
+ missing_phrase = match is not None and any(
+ normalize(phrase) not in normalize(match["content"])
+ for phrase in ut["must_include"]
+ )
+ if match is None or missing_phrase:
+ failures.append({"id": ut_id, "query": query})
+ if failures:
+ conn.rollback()
+ return {"status": "failed", "failures": failures, "built": [], "skipped": skipped}
+ for ut_id in ids:
+ conn.execute(
+ "UPDATE uts SET build_state='built',updated_at=? WHERE id=?",
+ (now(), ut_id),
+ )
+ conn.commit()
+ return {"status": "built", "built": sorted(ids), "skipped": skipped, "failures": []}
+
+
+def run_tests(root: Path, *, built_only: bool = False) -> dict[str, Any]:
+ failures: list[dict[str, Any]] = []
+ total = 0
+ with connect(root) as conn:
+ rows = conn.execute("SELECT * FROM uts WHERE status='active'").fetchall()
+ for row in rows:
+ ut = decode_row(row)
+ if built_only and ut["build_state"] != "built":
+ continue
+ for query in ut["queries"]:
+ total += 1
+ result = search_one(conn, query, built_only=built_only)
+ match = next((item for item in result["matches"] if item["id"] == ut["id"]), None)
+ missing_phrase = match is not None and any(
+ normalize(phrase) not in normalize(match["content"])
+ for phrase in ut["must_include"]
+ )
+ if match is None or missing_phrase:
+ failures.append({"id": ut["id"], "query": query})
+ return {"total": total, "failed": len(failures), "failures": failures, "built_only": built_only}
+
+
+def read_json(path: str | Path) -> dict[str, Any]:
+ return json.loads(Path(path).read_text(encoding="utf-8"))
+
+
+def manual_add(root: Path, value: dict[str, Any], *, force: bool) -> dict[str, Any]:
+ with connect(root) as conn:
+ conn.execute("BEGIN IMMEDIATE")
+ existing = conn.execute("SELECT 1 FROM uts WHERE id=?", (value.get("id"),)).fetchone()
+ if existing and not force:
+ return {"status": "exists", "id": value.get("id")}
+ upsert_ut(conn, value)
+ set_meta(conn, "memory_revision", int(get_meta(conn, "memory_revision")) + 1)
+ conn.commit()
+ return {"status": "added", "id": value["id"], "build_state": "pending"}
+
+
+def update(root: Path, ut_id: str, updates: dict[str, Any]) -> dict[str, Any]:
+ shown = show(root, ut_id)
+ if "memory" not in shown:
+ return shown
+ current = shown["memory"]
+ for key in ("updated_at", "content_hash", "build_state"):
+ current.pop(key, None)
+ current.update(updates)
+ current["id"] = ut_id
+ return manual_add(root, current, force=True) | {"status": "updated"}
+
+
+def retire(root: Path, ut_id: str, reason: str | None) -> dict[str, Any]:
+ with connect(root) as conn:
+ conn.execute("BEGIN IMMEDIATE")
+ cursor = conn.execute(
+ "UPDATE uts SET status='retired',updated_at=? WHERE id=?",
+ (now(), ut_id),
+ )
+ if cursor.rowcount != 1:
+ return {"status": "not_found", "id": ut_id}
+ set_meta(conn, "memory_revision", int(get_meta(conn, "memory_revision")) + 1)
+ conn.commit()
+ return {"status": "retired", "id": ut_id, "reason": reason}
+
+
+def bench(root: Path) -> dict[str, Any]:
+ with connect(root) as conn:
+ queries: list[str] = []
+ rows = conn.execute("SELECT queries_json FROM uts WHERE status='active'")
+ for row in rows:
+ queries.extend(json.loads(row["queries_json"]))
+ samples: list[float] = []
+ for query in queries:
+ started = time.perf_counter()
+ search(root, [query])
+ samples.append((time.perf_counter() - started) * 1000)
+ samples.sort()
+ p95 = samples[min(len(samples) - 1, int(len(samples) * 0.95))] if samples else 0.0
+ return {
+ "queries": len(samples),
+ "p95_search_ms": round(p95, 3),
+ "mean_search_ms": round(statistics.mean(samples), 3) if samples else 0.0,
+ }
+
+
+def emit_json(value: dict[str, Any]) -> None:
+ """Write one JSON document through logging without decorating the CLI protocol."""
+ logger = logging.getLogger("dynamic-memory-cli.output")
+ handler = logging.StreamHandler(sys.stdout)
+ handler.setFormatter(logging.Formatter("%(message)s"))
+ logger.handlers.clear()
+ logger.addHandler(handler)
+ logger.setLevel(logging.INFO)
+ logger.propagate = False
+ try:
+ logger.info(json.dumps(value, ensure_ascii=False, indent=2))
+ handler.flush()
+ finally:
+ logger.removeHandler(handler)
+ handler.close()
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(prog="dynamic-memory-cli")
+ parser.add_argument("--root")
+ sub = parser.add_subparsers(dest="command", required=True)
+ init = sub.add_parser("init")
+ init.add_argument("--path", required=True)
+ search_p = sub.add_parser("search")
+ search_p.add_argument("query", nargs="+")
+ list_p = sub.add_parser("list")
+ list_p.add_argument("--full", action="store_true")
+ show_p = sub.add_parser("show")
+ show_p.add_argument("id")
+ check = sub.add_parser("check-conflicts")
+ check.add_argument("--file", required=True)
+ add = sub.add_parser("add")
+ add.add_argument("--file", required=True)
+ add.add_argument("--force", action="store_true")
+ update_p = sub.add_parser("update")
+ update_p.add_argument("id")
+ update_p.add_argument("--file", required=True)
+ retire_p = sub.add_parser("retire")
+ retire_p.add_argument("id")
+ retire_p.add_argument("--reason")
+ sub.add_parser("get-state")
+ publish = sub.add_parser("publish-pending")
+ publish.add_argument("--file", required=True)
+ freeze = sub.add_parser("freeze-pending")
+ freeze.add_argument("--output", required=True)
+ build = sub.add_parser("build-pending")
+ build.add_argument("--file", required=True)
+ test_p = sub.add_parser("test")
+ test_p.add_argument("--built-only", action="store_true")
+ sub.add_parser("bench")
+ args = parser.parse_args(argv)
+ try:
+ if args.command == "init":
+ result = init_project(root_path(args.path))
+ else:
+ root = root_path(args.root)
+ require_project(root)
+ if args.command == "search":
+ result = search(root, args.query)
+ elif args.command == "list":
+ result = list_uts(root, full=args.full)
+ elif args.command == "show":
+ result = show(root, args.id)
+ elif args.command == "check-conflicts":
+ candidate = read_json(args.file)
+ errors = validate_ut(candidate)
+ matches = [] if errors else [search(root, [query]) for query in candidate["queries"]]
+ result = {"valid": not errors, "errors": errors, "matches": matches}
+ elif args.command == "add":
+ result = manual_add(root, read_json(args.file), force=args.force)
+ elif args.command == "update":
+ result = update(root, args.id, read_json(args.file))
+ elif args.command == "retire":
+ result = retire(root, args.id, args.reason)
+ elif args.command == "get-state":
+ with connect(root) as conn:
+ result = state(conn)
+ elif args.command == "publish-pending":
+ result = publish_pending(root, read_json(args.file))
+ elif args.command == "freeze-pending":
+ result = freeze_pending(root, Path(args.output).resolve())
+ elif args.command == "build-pending":
+ result = build_pending(root, read_json(args.file))
+ elif args.command == "test":
+ result = run_tests(root, built_only=args.built_only)
+ elif args.command == "bench":
+ result = bench(root)
+ else:
+ raise ValueError(f"unsupported command: {args.command}")
+ emit_json(result)
+ return 1 if result.get("status") in {"failed", "exists", "not_found"} or result.get("failed", 0) else 0
+ except Exception as exc:
+ emit_json({"error": type(exc).__name__, "message": str(exc)})
+ return 1
+
+
+if __name__ == "__main__":
+ if hasattr(sys.stdout, "reconfigure"):
+ sys.stdout.reconfigure(encoding="utf-8")
+ if hasattr(sys.stderr, "reconfigure"):
+ sys.stderr.reconfigure(encoding="utf-8")
+ sys.exit(main())
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
index 734318f3b7..6dd114581c 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
@@ -770,6 +770,11 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
_RailBuildInfo("_code_task_planning_rail", self._build_code_task_planning_rail),
_RailBuildInfo("_code_agent_rail", self._build_code_agent_rail),
_RailBuildInfo("_code_plan_approval_rail", self._build_plan_approval_rail),
+ # 与上游 02957a531 对齐:挂到链路末端(context_processor 之后),
+ # 保证 ON_USER_MESSAGE 投影替换发生在上下文初始化链路之后。
+ _RailBuildInfo(
+ "_eternal_conversation_rail", self._build_eternal_conversation_rail
+ ),
]
normalized_sub_mode = _normalize_code_sub_mode(sub_mode)
@@ -1518,6 +1523,21 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
self._runtime_prompt_rail.set_request_system_prompt(
runtime_config.request_system_prompt
)
+ eternal_conversation_rail = getattr(self, "_eternal_conversation_rail", None)
+ if eternal_conversation_rail is not None:
+ self._eternal_conversation_enabled = runtime_config.eternal_conversation_enabled
+ eternal_conversation_rail.configure_runtime(
+ enabled=runtime_config.eternal_conversation_enabled,
+ session_id=runtime_config.session_id,
+ request_id=runtime_config.request_id,
+ mode=runtime_config.mode,
+ channel=resolved_channel,
+ project_dir=runtime_config.project_dir or self._project_dir,
+ model=getattr(self, "_active_request_model", None) or self._model,
+ interaction_resume=runtime_config.interaction_resume,
+ )
+ if self._eternal_conversation_enabled and self._context_processor_rail is not None:
+ self.shutdown_context_session_memory(self._context_processor_rail)
# PermissionInterruptRail: per-request trusted_dirs 注入,使 external_directory
# 检查将这些子树视为 internal 而跳过 ask/deny(与 RuntimePromptRail 对齐)。
# 用 getattr 兼容绕过 __init__ 的测试构造(_permission_rail 仅在 rail 构建流程赋值)。
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index 195ce7a3d7..033d40e616 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -185,6 +185,12 @@ _SKILL_TURBO_TOOL_ID_SUFFIX = "_skill_turbo"
# 信号本身无用户可见内容,_parse_stream_chunk 对未知类型返回 None 将其吞掉。
_RESUME_SIGNAL_CHUNK_TYPE = "__resume_signal__"
+# shutdown_context_session_memory 用哨兵区分"属性缺失(框架改名/异型
+# rail)"与"属性合法为 None(未配置或已关闭,框架初始即 None,仅在
+# session_memory_compressor_config.enabled=true 时创建)"——两者日志
+# 级别不同,getattr 默认值无法表达该区分(CR-5)。
+_MISSING_SESSION_MEMORY_MGR = object()
+
def _is_foreign_stream_source(payload: Any) -> bool:
"""True when the frame was mirrored from a nested stream (subagent / skill node).
@@ -298,6 +304,7 @@ from jiuwenswarm.server.runtime.agent_adapter.llm_io_trace import (
)
from jiuwenswarm.agents.harness.common.auto_harness import AutoHarnessService
from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import (
+ INTERRUPT_RESUME_SOURCES,
SKILL_EVOLUTION_APPROVAL_SCHEMA,
PermissionRailBuildOptions,
build_permission_rail,
@@ -330,6 +337,9 @@ from jiuwenswarm.agents.harness.common.rails import (
TaskExecutionRail,
ContextOverflowRecoveryRail,
)
+from jiuwenswarm.agents.harness.common.rails.eternal_conversation import (
+ EternalConversationRail,
+)
from jiuwenswarm.agents.harness.common.rails.disabled_tools_rail import (
DisabledToolsRail,
)
@@ -2726,6 +2736,8 @@ class JiuWenSwarmDeepAdapter:
self._context_assemble_rail: ContextAssembleRail | None = None
self._context_assemble_mode: str | None = None
self._context_processor_rail: ContextProcessorRail | None = None
+ self._eternal_conversation_rail: EternalConversationRail | None = None
+ self._eternal_conversation_enabled: bool = False
self._runtime_prompt_rail: RuntimePromptRail | None = None
self._response_prompt_rail: ResponsePromptRail | None = None
self._personal_context_rail: PersonalContextRail | None = None
@@ -10343,6 +10355,63 @@ class JiuWenSwarmDeepAdapter:
rail = None
return rail
+ @staticmethod
+ def _build_eternal_conversation_rail() -> EternalConversationRail | None:
+ """Mount an inert Rail; a Session request flag activates it later."""
+ try:
+ rail = EternalConversationRail()
+ logger.info("[JiuWenSwarmDeepAdapter] EternalConversationRail created (disabled)")
+ return rail
+ except Exception as exc:
+ logger.warning("[JiuWenSwarmDeepAdapter] EternalConversationRail create failed: %s", exc)
+ return None
+
+ @staticmethod
+ def shutdown_context_session_memory(context_processor_rail: ContextProcessorRail) -> bool:
+ """Stop overlapping semantic session memory through a stable Adapter API.
+
+ 三态区分(CR-5),保证日志不失实:
+
+ - manager 在位:shutdown 并置 None,返回 True;
+ - 属性为 None:未配置(框架默认,仅在
+ session_memory_compressor_config.enabled=true 时创建)或已
+ 关闭的合法幂等态,debug 即可,不告警;
+ - 属性缺失(agent-core 私有属性被改名 / rail 类型不符):
+ 保留 CR-2 加固的 WARNING——SessionMemoryManager 可能仍在
+ eternal conversation 旁 unnoticed 运行(双记忆后端风险)。
+
+ 上游 02957a531 对两种非在位状态都是静默 False;缺失属性告警
+ 是本地有意的加强。
+ """
+ session_memory_manager = getattr(
+ context_processor_rail, "_session_memory_mgr", _MISSING_SESSION_MEMORY_MGR
+ )
+ if session_memory_manager is _MISSING_SESSION_MEMORY_MGR:
+ # _session_memory_mgr is a private agent-core attribute; a renamed
+ # attribute or a wrong rail type would otherwise fail silently
+ # and leave SessionMemoryManager writing beside eternal conversation.
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] shutdown_context_session_memory found no "
+ "_session_memory_mgr attribute on %r; the framework may have renamed "
+ "it and SessionMemoryManager may keep running beside eternal "
+ "conversation (double memory backend)",
+ type(context_processor_rail).__name__,
+ )
+ return False
+ if session_memory_manager is None:
+ # 合法幂等态:未配置或已成功关闭。上游在 None 时也静默返回
+ # False;这里只留 debug 便于排障,不打 WARNING(CR-5)。
+ logger.debug(
+ "[JiuWenSwarmDeepAdapter] shutdown_context_session_memory: "
+ "no active SessionMemoryManager on %r (not configured or "
+ "already shut down)",
+ type(context_processor_rail).__name__,
+ )
+ return False
+ session_memory_manager.shutdown()
+ setattr(context_processor_rail, "_session_memory_mgr", None)
+ return True
+
def _build_skill_retrieval_prompt_rail(self) -> SkillRetrievalPromptRail | None:
"""Build lightweight agentic skill retrieval prompt guidance."""
if not is_skill_retrieval_enabled():
@@ -10788,6 +10857,11 @@ class JiuWenSwarmDeepAdapter:
_build_context_processor_rail,
{"config": self._config_cache},
),
+ # 与上游 02957a531 对齐:挂到 context_processor_rail 之后,
+ # 保证 ON_USER_MESSAGE 投影替换发生在上下文初始化链路之后。
+ _RailBuildInfo(
+ "_eternal_conversation_rail", self._build_eternal_conversation_rail
+ ),
]
# SkillEvolutionRail / TTSERail 不在冷启动时挂载,由 _update_rails_for_mode
@@ -13378,6 +13452,8 @@ class JiuWenSwarmDeepAdapter:
workspace: str | None = None
project_dir: str | None = None
supports_user_interaction: bool = True
+ eternal_conversation_enabled: bool = False
+ interaction_resume: bool = False
interactive_ask: bool = False
request_system_prompt: str | None = None
# 用户上传附件(request.params["files"]):注入 metadata 供 skill_turbo
@@ -13409,6 +13485,29 @@ class JiuWenSwarmDeepAdapter:
metadata = request.metadata if isinstance(getattr(request, "metadata", None), dict) else None
return extract_interactive_ask(params, metadata)
+ @staticmethod
+ def _resolve_eternal_conversation_enabled(params: Any) -> bool:
+ """Resolve the V1 frontend runtime flag; absent remains disabled."""
+ if not isinstance(params, dict):
+ return False
+ value = params.get("eternal_conversation_enabled", False)
+ if isinstance(value, bool):
+ return value
+ if isinstance(value, str):
+ return value.strip().casefold() in {"1", "true", "yes", "on", "enabled"}
+ return bool(value)
+
+ @staticmethod
+ def _is_eternal_interaction_resume(params: Any) -> bool:
+ if not isinstance(params, dict):
+ return False
+ # Single source of truth with the HITL resume dispatch: every source the
+ # framework treats as an interrupt resume (permission/confirm/ask_user/
+ # evolution) must resume the suspended natural task instead of starting
+ # a new one, otherwise ask_user answers would split one natural task in
+ # the eternal-conversation evidence chain.
+ return str(params.get("source") or "").strip() in INTERRUPT_RESUME_SOURCES
+
async def configure_session_runtime(
self,
*,
@@ -13542,6 +13641,31 @@ 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)
+
+ eternal_conversation_rail = getattr(self, "_eternal_conversation_rail", None)
+ if eternal_conversation_rail is not None:
+ self._eternal_conversation_enabled = runtime_config.eternal_conversation_enabled
+ eternal_conversation_rail.configure_runtime(
+ enabled=runtime_config.eternal_conversation_enabled,
+ session_id=runtime_config.session_id,
+ request_id=runtime_config.request_id,
+ mode=runtime_config.mode,
+ channel=resolved_channel,
+ project_dir=runtime_config.project_dir or self._project_dir,
+ model=getattr(self, "_active_request_model", None) or self._model,
+ interaction_resume=runtime_config.interaction_resume,
+ )
+ if (
+ self._eternal_conversation_enabled
+ and self._context_processor_rail is not None
+ and self.shutdown_context_session_memory(self._context_processor_rail)
+ ):
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] SessionMemoryManager disabled: "
+ "eternal conversation owns semantic memory"
+ )
+ stage_timer.mark("eternal_conversation")
+
if self._runtime_prompt_rail:
self._runtime_prompt_rail.set_language(resolved_language)
self._runtime_prompt_rail.set_channel(resolved_channel)
@@ -15081,6 +15205,14 @@ class JiuWenSwarmDeepAdapter:
async def cleanup(self) -> None:
"""Release adapter-owned external runtime resources."""
+ eternal_conversation_rail = getattr(self, "_eternal_conversation_rail", None)
+ if eternal_conversation_rail is not None:
+ try:
+ await eternal_conversation_rail.close()
+ except Exception as exc:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] eternal conversation cleanup failed: %s", exc
+ )
if not self._is_session_scoped_adapter:
for adapter in list(self._session_adapters.values()):
try:
@@ -19619,6 +19751,10 @@ class JiuWenSwarmDeepAdapter:
supports_user_interaction=inputs.get(
"supports_user_interaction", True
),
+ eternal_conversation_enabled=self._resolve_eternal_conversation_enabled(
+ request.params
+ ),
+ interaction_resume=self._is_eternal_interaction_resume(request.params),
interactive_ask=self._extract_request_interactive_ask(request),
request_system_prompt=self._extract_request_system_prompt(request),
files=(
@@ -20385,6 +20521,10 @@ class JiuWenSwarmDeepAdapter:
supports_user_interaction=inputs.get(
"supports_user_interaction", True
),
+ eternal_conversation_enabled=self._resolve_eternal_conversation_enabled(
+ request.params
+ ),
+ interaction_resume=self._is_eternal_interaction_resume(request.params),
interactive_ask=self._extract_request_interactive_ask(request),
request_system_prompt=self._extract_request_system_prompt(request),
files=(
@@ -20800,6 +20940,10 @@ class JiuWenSwarmDeepAdapter:
supports_user_interaction=inputs.get(
"supports_user_interaction", True
),
+ eternal_conversation_enabled=self._resolve_eternal_conversation_enabled(
+ request.params
+ ),
+ interaction_resume=self._is_eternal_interaction_resume(request.params),
interactive_ask=self._extract_request_interactive_ask(request),
request_system_prompt=self._extract_request_system_prompt(request),
files=(
@@ -23076,7 +23220,11 @@ class JiuWenSwarmDeepAdapter:
)
if get_memory_mode(config) == "local":
# 引擎门禁:memory.engine 未放行内置时,等同于禁用
- builtin_on = is_builtin_memory_allowed(config) and is_memory_enabled(mode, config)
+ builtin_on = (
+ not getattr(self, "_eternal_conversation_enabled", False)
+ and is_builtin_memory_allowed(config)
+ and is_memory_enabled(mode, config)
+ )
if builtin_on:
# 开启记忆
new_embed_fp = self._embedding_config_fingerprint(config)
@@ -23151,7 +23299,9 @@ class JiuWenSwarmDeepAdapter:
)
config = get_config()
- if is_external_memory_enabled(config):
+ if is_external_memory_enabled(config) and not getattr(
+ self, "_eternal_conversation_enabled", False
+ ):
if self._external_memory_rail_registered:
return
if self._external_memory_rail is None:
diff --git a/tests/unit_tests/agentserver/rails/test_eternal_conversation_inherit_flag.py b/tests/unit_tests/agentserver/rails/test_eternal_conversation_inherit_flag.py
new file mode 100644
index 0000000000..5dc2846182
--- /dev/null
+++ b/tests/unit_tests/agentserver/rails/test_eternal_conversation_inherit_flag.py
@@ -0,0 +1,104 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Regression guard for ``EternalConversationRail.inherit_to_subagents = False``.
+
+EternalConversationRail is a stateful session-level Rail: ``init`` binds
+``_agent`` / ``system_prompt_builder`` and ``configure_runtime`` binds
+``_session_id`` / ``_coordinator``. A general-purpose subagent inherits parent
+rails by reference (``factory._inject_general_purpose_subagent``); the child's
+``init_rail`` would then rebind the shared instance, pollute the session
+evidence chain with subagent tasks and silently break the parent's memory
+section injection. ``inherit_to_subagents = False`` opts the rail out at
+factory injection, matching TaskExecutionRail / ProgressiveToolRail /
+CodingArtifactPostProcessRail.
+
+This test locks the swarm-side half: the flag value as declared in source.
+It reads the module via ``ast`` — NOT importing it — so it runs in CI
+gates where the openjiuwen dependency may be unavailable.
+
+The ``ast`` work runs in a throwaway interpreter. On the CI runners
+(Python 3.11.5, pytest-xdist) an in-process ``ast.parse`` of rail files
+intermittently dies with ``SystemError: AST constructor recursion depth
+mismatch`` — the AST constructor's recursion counter is process-wide and
+can be left corrupted by earlier parses in the same worker. A fresh
+interpreter starts with clean state and cannot inherit that corruption.
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[4]
+RAIL_PATH = (
+ ROOT
+ / "jiuwenswarm"
+ / "agents"
+ / "harness"
+ / "common"
+ / "rails"
+ / "eternal_conversation"
+ / "rail.py"
+)
+
+# Child interpreter script: read and parse the rail file, dump the top-level
+# assignments of the requested class, and emit the reference dump of the
+# literal False. The file is read (and only read) inside the child so the
+# source never crosses a locale-dependent stdio pipe.
+_CHILD_SCRIPT = """\
+import ast, json, sys
+with open(sys.argv[1], encoding="utf-8") as fh:
+ source = fh.read()
+tree = ast.parse(source, filename=sys.argv[1])
+assigns = {}
+for node in ast.walk(tree):
+ if isinstance(node, ast.ClassDef) and node.name == sys.argv[2]:
+ for stmt in node.body:
+ if (
+ isinstance(stmt, ast.Assign)
+ and len(stmt.targets) == 1
+ and isinstance(stmt.targets[0], ast.Name)
+ ):
+ assigns[stmt.targets[0].id] = ast.dump(stmt.value)
+ break
+false_dump = ast.dump(ast.parse("False", mode="eval").body)
+print(json.dumps({"assigns": assigns, "false_dump": false_dump}))
+"""
+
+
+def _find_class_assignments(class_name: str) -> tuple[dict[str, str], str]:
+ """Parse in a child interpreter; return ({attr_name: dump}, literal-False dump)."""
+ proc = subprocess.run(
+ [sys.executable, "-I", "-B", "-c", _CHILD_SCRIPT, str(RAIL_PATH), class_name],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=120,
+ check=False,
+ )
+ if proc.returncode != 0 or not proc.stdout.strip():
+ raise AssertionError(
+ f"child ast.parse of {RAIL_PATH} failed (rc={proc.returncode}):\n{proc.stderr}"
+ )
+ payload = json.loads(proc.stdout)
+ return payload["assigns"], payload["false_dump"]
+
+
+def test_inherit_to_subagents_is_false():
+ """Flag must stay False — guards against accidental deletion/flipping."""
+ assert RAIL_PATH.is_file(), f"rail source not found: {RAIL_PATH}"
+ assigns, false_dump = _find_class_assignments("EternalConversationRail")
+
+ assert "inherit_to_subagents" in assigns, (
+ "EternalConversationRail must declare inherit_to_subagents = False; "
+ "removing the flag lets factory._inject_general_purpose_subagent copy "
+ "the rail by reference into general-purpose subagents, whose "
+ "init_rail rebinds _agent/_builder and pollutes the session "
+ "evidence chain (rail/base.py inheritance trap)"
+ )
+ assert assigns["inherit_to_subagents"] == false_dump, (
+ "EternalConversationRail.inherit_to_subagents must be the literal False"
+ )
diff --git a/tests/unit_tests/agentserver/rails/test_eternal_conversation_rail.py b/tests/unit_tests/agentserver/rails/test_eternal_conversation_rail.py
new file mode 100644
index 0000000000..a534ae9cf0
--- /dev/null
+++ b/tests/unit_tests/agentserver/rails/test_eternal_conversation_rail.py
@@ -0,0 +1,955 @@
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import json
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from openjiuwen.harness.prompts import SystemPromptBuilder
+
+from jiuwenswarm.agents.harness.common.rails.eternal_conversation.background_agents import (
+ RETRY_CHECKLIST,
+ BackgroundAgentRunner,
+)
+from jiuwenswarm.agents.harness.common.rails.eternal_conversation.coordinator import (
+ SessionCoordinator,
+ _extractor_evidence,
+ _raw_range,
+ _validate_extractor,
+)
+from jiuwenswarm.agents.harness.common.rails.eternal_conversation.evidence import (
+ EvidenceWriter,
+ resolve_evidence_blobs,
+ write_json_atomic,
+)
+from jiuwenswarm.agents.harness.common.rails.eternal_conversation.memory_cli import (
+ DynamicMemoryGateway,
+)
+from jiuwenswarm.agents.harness.common.rails.eternal_conversation.rail import (
+ EternalConversationRail,
+)
+from jiuwenswarm.agents.harness.common.rails.eternal_conversation.prompts import (
+ BUILDER_SYSTEM_PROMPT,
+ EXTRACTOR_SYSTEM_PROMPT,
+)
+from jiuwenswarm.agents.harness.common.rails.eternal_conversation.registry import (
+ get_session_coordinator,
+)
+from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import (
+ INTERRUPT_RESUME_SOURCES,
+)
+from jiuwenswarm.server.runtime.agent_adapter.interface_deep import JiuWenSwarmDeepAdapter
+
+
+def _read_jsonl(path: Path) -> list[dict]:
+ return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line]
+
+
+
+
+async def test_raw_history_is_monotonic_hash_chained_and_mirrored(tmp_path: Path) -> None:
+ writer = EvidenceWriter(tmp_path, "session-a")
+
+ first = await writer.append("user-message", {"text": "one"}, task_id="t1")
+ second = await writer.append("tool-result", {"value": 2}, task_id="t1")
+
+ assert first["cursor"] == 1
+ assert second["cursor"] == 2
+ assert second["previous_hash"] == first["hash"]
+ raw = _read_jsonl(tmp_path / "raw-history" / "events.jsonl")
+ foreground = _read_jsonl(tmp_path / "agent-history" / "foreground" / "conversation.jsonl")
+ assert raw == foreground
+
+
+
+
+async def test_two_writer_instances_share_one_cursor_authority(tmp_path: Path) -> None:
+ first = EvidenceWriter(tmp_path, "session-a")
+ stale_peer = EvidenceWriter(tmp_path, "session-a")
+
+ one, two = await asyncio.gather(
+ first.append("tool-call", {"name": "one"}, task_id="t1"),
+ stale_peer.append("tool-result", {"name": "two"}, task_id="t1"),
+ )
+
+ rows = _read_jsonl(tmp_path / "raw-history" / "events.jsonl")
+ assert sorted((one["cursor"], two["cursor"])) == [1, 2]
+ assert [row["cursor"] for row in rows] == [1, 2]
+ assert rows[1]["previous_hash"] == rows[0]["hash"]
+ recovered = EvidenceWriter(tmp_path, "session-a")
+ assert recovered.cursor == 2
+
+
+
+
+async def test_large_background_history_is_content_addressed_and_reconstructable(
+ tmp_path: Path,
+) -> None:
+ writer = EvidenceWriter(tmp_path, "session-a")
+ request = {"frozen_working_memory": "x" * (300 * 1024)}
+
+ await writer.append_agent_history(
+ "extractor",
+ {"status": "accepted", "system_prompt": "prompt", "request": request},
+ )
+
+ row = _read_jsonl(
+ tmp_path / "agent-history" / "extractor" / "conversation.jsonl"
+ )[0]
+ reference = row["request"]
+ blob = (
+ tmp_path
+ / "agent-history"
+ / "extractor"
+ / reference["$evidence_blob"]
+ )
+ reconstructed = json.loads(blob.read_text(encoding="utf-8"))
+ canonical = json.dumps(
+ reconstructed,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ ).encode("utf-8")
+ assert reconstructed == request
+ assert hashlib.sha256(canonical).hexdigest() == reference["sha256"]
+ assert len(canonical) == reference["bytes"]
+
+
+def test_extractor_evidence_keeps_latest_visible_context_without_repeating_messages() -> None:
+ events = [
+ {
+ "cursor": 1,
+ "type": "model-visible-envelope",
+ "session_id": "session-a",
+ "task_id": "t1",
+ "created_at": "now",
+ "previous_hash": None,
+ "hash": "h1",
+ "payload": {
+ "messages": ["old context"],
+ "tools": ["tool-a"],
+ "response": "first answer",
+ "status": "succeeded",
+ "usage": {"input_tokens": 10},
+ },
+ },
+ {
+ "cursor": 2,
+ "type": "tool-result",
+ "session_id": "session-a",
+ "task_id": "t1",
+ "created_at": "now",
+ "previous_hash": "h1",
+ "hash": "h2",
+ "payload": {"tool_result": "direct evidence"},
+ },
+ {
+ "cursor": 3,
+ "type": "model-visible-envelope",
+ "session_id": "session-a",
+ "task_id": "t1",
+ "created_at": "now",
+ "previous_hash": "h2",
+ "hash": "h3",
+ "payload": {
+ "messages": ["final visible context"],
+ "tools": ["tool-b"],
+ "response": "final answer",
+ "status": "succeeded",
+ "usage": {"input_tokens": 20},
+ },
+ },
+ ]
+
+ view = _extractor_evidence(events)
+
+ assert view["final_visible_context"]["messages"] == ["final visible context"]
+ assert view["final_visible_context"]["tools"] == ["tool-b"]
+ assert view["raw_history_manifest"]["event_count"] == 3
+ assert view["raw_history_manifest"]["model_visible_envelope_count"] == 2
+ assert view["frozen_working_memory"][0]["payload"]["response"] == "first answer"
+ assert "messages" not in view["frozen_working_memory"][0]["payload"]
+ assert view["frozen_working_memory"][1]["payload"]["tool_result"] == "direct evidence"
+
+
+def test_extractor_evidence_structurally_bounds_large_protocol_payloads() -> None:
+ large = "NimbusGate:" + "x" * 20_000
+ events = [
+ {
+ "cursor": 1,
+ "type": "tool-result",
+ "hash": "h1",
+ "payload": {
+ "tool_name": "read_file",
+ "status": "succeeded",
+ "tool_result": large,
+ },
+ },
+ {
+ "cursor": 2,
+ "type": "model-visible-envelope",
+ "hash": "h2",
+ "payload": {
+ "messages": ["Keep the exact user term NimbusGate"],
+ "tools": [
+ {
+ "type": "function",
+ "function": {"name": "read_file", "description": large},
+ }
+ ],
+ "response": large,
+ "status": "succeeded",
+ },
+ },
+ ]
+
+ view = _extractor_evidence(events)
+
+ assert events[0]["payload"]["tool_result"] == large
+ descriptor = view["frozen_working_memory"][0]["payload"]["tool_result"]
+ assert descriptor == {
+ "$raw_history_content": True,
+ "sha256": hashlib.sha256(large.encode("utf-8")).hexdigest(),
+ "utf8_bytes": len(large.encode("utf-8")),
+ }
+ assert view["frozen_working_memory"][1]["payload"]["response"] == descriptor
+ assert view["final_visible_context"]["messages"] == [
+ "Keep the exact user term NimbusGate"
+ ]
+ assert view["final_visible_context"]["tools"] == ["read_file"]
+
+
+def test_raw_range_batches_only_at_complete_natural_task_boundaries(tmp_path: Path) -> None:
+ path = tmp_path / "events.jsonl"
+ rows: list[dict] = []
+ cursor = 0
+ for task_number in range(1, 7):
+ for kind in ("task-started", "task-finished"):
+ cursor += 1
+ rows.append({"cursor": cursor, "type": kind, "task_id": f"t{task_number}"})
+ path.write_text(
+ "".join(json.dumps(row) + "\n" for row in rows),
+ encoding="utf-8",
+ )
+
+ first = _raw_range(path, 1, cursor)
+ second = _raw_range(path, int(first[-1]["cursor"]) + 1, cursor)
+
+ assert [row["task_id"] for row in first if row["type"] == "task-finished"] == [
+ "t1",
+ "t2",
+ "t3",
+ "t4",
+ ]
+ assert first[-1]["type"] == "task-finished"
+ assert second[-1]["task_id"] == "t6"
+
+
+def test_extractor_rejects_unsupported_ut_action_before_memory_cli() -> None:
+ value = {
+ "snapshot": {
+ "resident_memory": [],
+ "recent_context": [],
+ "current_state": [],
+ "completed": [],
+ "next_actions": [],
+ "constraints": [],
+ },
+ "changed_uts": [
+ {
+ "action": "update",
+ "id": "ut-one",
+ "content": "Keep NimbusGate exact.",
+ "queries": ["NimbusGate"],
+ "must_include": ["NimbusGate"],
+ }
+ ],
+ }
+
+ with pytest.raises(ValueError, match="upsert or retire"):
+ _validate_extractor(value)
+
+
+def test_builder_prompt_cannot_take_over_extractor_semantic_judgment() -> None:
+ assert "boundary is structural, not semantic" in BUILDER_SYSTEM_PROMPT
+ assert "extraction Agent exclusively owns" in BUILDER_SYSTEM_PROMPT
+ assert "Do not reject because a" in BUILDER_SYSTEM_PROMPT
+ assert "UT or Snapshot omits a historical item" in BUILDER_SYSTEM_PROMPT
+
+
+def test_extractor_never_infers_override_from_repetition_or_agent_work() -> None:
+ assert "repeating the same contradictory request any number of times" in EXTRACTOR_SYSTEM_PROMPT
+ assert "answers, tool edits, passing tests" in EXTRACTOR_SYSTEM_PROMPT
+ assert "Direct user messages outrank Agent narration" in EXTRACTOR_SYSTEM_PROMPT
+
+
+
+
+async def test_raw_history_recovers_state_and_foreground_mirror_after_crash(
+ tmp_path: Path,
+) -> None:
+ writer = EvidenceWriter(tmp_path, "session-a")
+ first = await writer.append("user-message", {"text": "one"}, task_id="t1")
+ second = await writer.append("task-finished", {"result": "ok"}, task_id="t1")
+
+ # Simulate termination after Raw History fsync but before the two derived
+ # writes by rolling both derived files back to the first complete record.
+ foreground_path = tmp_path / "agent-history" / "foreground" / "conversation.jsonl"
+ foreground_path.write_text(
+ json.dumps(first, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n",
+ encoding="utf-8",
+ )
+ (tmp_path / "state" / "evidence.json").write_text(
+ json.dumps({"cursor": 1, "last_hash": first["hash"]}),
+ encoding="utf-8",
+ )
+ (tmp_path / "raw-history" / "search.jsonl").unlink()
+
+ recovered = EvidenceWriter(tmp_path, "session-a")
+ assert recovered.cursor == second["cursor"]
+ assert _read_jsonl(foreground_path) == _read_jsonl(
+ tmp_path / "raw-history" / "events.jsonl"
+ )
+ search = _read_jsonl(tmp_path / "raw-history" / "search.jsonl")
+ assert [row["hash"] for row in search] == [first["hash"], second["hash"]]
+
+
+
+
+async def test_dynamic_memory_search_unifies_pending_and_built(tmp_path: Path) -> None:
+ writer = EvidenceWriter(tmp_path / "feature", "session-a")
+ gateway = DynamicMemoryGateway(tmp_path / "feature" / "memory", writer)
+ await gateway.ensure_initialized()
+ proposal = {
+ "base_memory_revision": 0,
+ "base_snapshot_revision": 0,
+ "from_cursor": 1,
+ "to_cursor": 1,
+ "snapshot": {"constraints": ["Keep NimbusGate private"]},
+ "changed_uts": [
+ {
+ "action": "upsert",
+ "id": "ut-nimbus-gate",
+ "memory_id": "memory-ut-nimbus-gate",
+ "priority": 90,
+ "content": "NimbusGate is the private compatibility environment.",
+ "queries": ["NimbusGate"],
+ "must_include": ["NimbusGate"],
+ "evidence_refs": ["raw-history:cursor-1-1"],
+ "source": "session-a",
+ "tags": ["alias"],
+ }
+ ],
+ "evidence_refs": ["raw-history:cursor-1-1"],
+ "semantic_statement": "The exact alias remains retrievable.",
+ }
+ await gateway.file_command("publish-pending", proposal, "proposal")
+
+ pending = await gateway.search("NimbusGate")
+ assert pending["matches"][0]["id"] == "ut-nimbus-gate"
+ assert pending["matches"][0]["build_state"] == "pending"
+
+ batch_path = tmp_path / "batch.json"
+ await gateway.call("freeze-pending", "--output", str(batch_path))
+ frozen = json.loads(batch_path.read_text(encoding="utf-8"))
+ assert "created_at" not in frozen
+ assert frozen["frozen_at"] >= frozen["items"][0]["updated_at"]
+ await gateway.call("build-pending", "--file", str(batch_path))
+ built = await gateway.search("NimbusGate")
+ assert built["matches"][0]["build_state"] == "built"
+
+
+class _FakeModel:
+ async def invoke(self, messages, **kwargs):
+ system = str(messages[0].content)
+ if "memory extraction Agent" in system:
+ value = {
+ "snapshot": {
+ "resident_memory": ["NimbusGate is private"],
+ "recent_context": [],
+ "current_state": [],
+ "completed": [],
+ "next_actions": [],
+ "constraints": ["Keep NimbusGate private"],
+ },
+ "changed_uts": [
+ {
+ "action": "upsert",
+ "id": "ut-nimbus-gate",
+ "memory_id": "memory-ut-nimbus-gate",
+ "priority": 90,
+ "content": "NimbusGate is the private compatibility environment.",
+ "queries": ["NimbusGate"],
+ "must_include": ["NimbusGate"],
+ "evidence_refs": ["model-placeholder"],
+ "source": "model-placeholder",
+ "tags": ["alias"],
+ }
+ ],
+ "semantic_statement": "NimbusGate is preserved under its exact name.",
+ }
+ else:
+ value = {"approved": True, "diagnostics": []}
+ return SimpleNamespace(
+ content=json.dumps(value),
+ usage_metadata=SimpleNamespace(input_tokens=11, output_tokens=7, cache_tokens=3),
+ )
+
+
+class _ControlledModel(_FakeModel):
+ def __init__(self, gate: asyncio.Event | None = None, failures: int = 0) -> None:
+ self.gate = gate
+ self.entered = asyncio.Event()
+ self.failures = failures
+ self.extractor_calls = 0
+
+ async def invoke(self, messages, **kwargs):
+ if "memory extraction Agent" in str(messages[0].content):
+ self.extractor_calls += 1
+ self.entered.set()
+ if self.failures:
+ self.failures -= 1
+ raise RuntimeError("synthetic extractor outage")
+ if self.gate is not None and self.extractor_calls == 1:
+ await self.gate.wait()
+ return await super().invoke(messages, **kwargs)
+
+
+class _RejectingBuilderModel(_FakeModel):
+ async def invoke(self, messages, **kwargs):
+ if "memory build Agent" in str(messages[0].content):
+ return SimpleNamespace(
+ content=json.dumps(
+ {
+ "approved": False,
+ "diagnostics": ["duplicate IDs with incompatible payloads"],
+ }
+ ),
+ usage_metadata=None,
+ )
+ return await super().invoke(messages, **kwargs)
+
+
+
+
+async def test_background_retry_rebuilds_with_full_structural_checklist(
+ tmp_path: Path,
+) -> None:
+ class RetryModel:
+ def __init__(self) -> None:
+ self.prompts: list[str] = []
+
+ async def invoke(self, messages, **kwargs):
+ self.prompts.append(str(messages[1].content))
+ content = "{}" if len(self.prompts) == 1 else '{"accepted":true}'
+ return SimpleNamespace(content=content, usage_metadata=None)
+
+ model = RetryModel()
+ runner = BackgroundAgentRunner(
+ lambda: model,
+ EvidenceWriter(tmp_path, "session-a"),
+ )
+
+ def validate(value: dict) -> None:
+ if value.get("accepted") is not True:
+ raise ValueError("accepted must be true")
+
+ result = await runner.call_json(
+ role="builder",
+ system_prompt="return JSON",
+ request={"batch": 1},
+ validate=validate,
+ )
+
+ assert result == {"accepted": True}
+ assert RETRY_CHECKLIST in model.prompts[1]
+ assert "accepted must be true" in model.prompts[1]
+ assert 'Here is the exact previous response' in model.prompts[1]
+ assert '{}' in model.prompts[1]
+
+
+def test_extractor_snapshot_limit_error_identifies_exact_item() -> None:
+ snapshot = {
+ "resident_memory": [],
+ "recent_context": [],
+ "current_state": [],
+ "completed": [],
+ "next_actions": [],
+ "constraints": ["x" * 304],
+ }
+
+ with pytest.raises(
+ ValueError,
+ match=r"snapshot\.constraints\[0\] has 304 characters; hard limit is 280",
+ ):
+ _validate_extractor({"snapshot": snapshot, "changed_uts": []})
+
+
+
+
+async def test_coordinator_runs_two_background_agents_and_publishes_auditable_state(
+ tmp_path: Path,
+) -> None:
+ coordinator = SessionCoordinator(tmp_path, "session-a", lambda: _FakeModel())
+ await coordinator.evidence.append("task-started", {"query": "Use NimbusGate"}, task_id="t1")
+ finished = await coordinator.evidence.append(
+ "task-finished", {"result": "done"}, task_id="t1"
+ )
+
+ await coordinator.request_extract(finished["cursor"])
+ await coordinator.wait_idle()
+
+ state = await coordinator.memory.projection()
+ assert state["covered_through"] == finished["cursor"]
+ assert state["snapshot_revision"] == 1
+ result = await coordinator.memory.search("NimbusGate")
+ assert result["matches"][0]["build_state"] == "built"
+ extractor = _read_jsonl(tmp_path / "agent-history" / "extractor" / "conversation.jsonl")
+ builder = _read_jsonl(tmp_path / "agent-history" / "builder" / "conversation.jsonl")
+ assert extractor[-1]["status"] == "accepted"
+ assert builder[-1]["status"] == "accepted"
+ assert extractor[-1]["usage"]["input_tokens"] == 11
+ assert (tmp_path / "audit" / "source-manifest.json").is_file()
+
+
+
+
+async def test_new_foreground_events_are_not_lost_while_extractor_is_running(
+ tmp_path: Path,
+) -> None:
+ gate = asyncio.Event()
+ model = _ControlledModel(gate)
+ coordinator = SessionCoordinator(tmp_path, "session-a", lambda: model)
+ await coordinator.evidence.append("task-started", {"query": "first"}, task_id="t1")
+ first = await coordinator.evidence.append("task-finished", {"result": "one"}, task_id="t1")
+ await coordinator.request_extract(first["cursor"])
+ await asyncio.wait_for(model.entered.wait(), timeout=5)
+
+ await coordinator.evidence.append("task-started", {"query": "second"}, task_id="t2")
+ second = await coordinator.evidence.append("task-finished", {"result": "two"}, task_id="t2")
+ await coordinator.request_extract(second["cursor"])
+ assert await coordinator.projection_for_boundary() is None
+
+ gate.set()
+ await coordinator.wait_idle()
+ projection = await coordinator.memory.projection()
+ assert projection["covered_through"] == second["cursor"]
+ assert projection["snapshot_revision"] == 2
+ assert model.extractor_calls == 2
+ eligible = await coordinator.projection_for_boundary()
+ assert eligible is not None
+ await coordinator.mark_projection_applied(eligible["snapshot_revision"])
+ assert await coordinator.projection_for_boundary() is None
+
+
+
+
+async def test_background_failure_is_audited_and_retried_on_next_task_boundary(
+ tmp_path: Path,
+) -> None:
+ failing = _ControlledModel(failures=6)
+ current = {"model": failing}
+ coordinator = SessionCoordinator(tmp_path, "session-a", lambda: current["model"])
+ await coordinator.evidence.append("task-started", {"query": "remember"}, task_id="t1")
+ finished = await coordinator.evidence.append("task-finished", {"result": "done"}, task_id="t1")
+ await coordinator.request_extract(finished["cursor"])
+ await coordinator.wait_idle()
+ extractor = _read_jsonl(tmp_path / "agent-history" / "extractor" / "conversation.jsonl")
+ assert [row["status"] for row in extractor[-7:]] == [
+ *(["rejected"] * 6),
+ "error",
+ ]
+ failed_state = json.loads(coordinator.state_path.read_text(encoding="utf-8"))
+ assert failed_state["extractor_error"]["error_type"] == "RuntimeError"
+
+ current["model"] = _ControlledModel()
+ await coordinator.request_extract(finished["cursor"])
+ await coordinator.wait_idle()
+ projection = await coordinator.memory.projection()
+ assert projection["covered_through"] == finished["cursor"]
+ recovered_state = json.loads(coordinator.state_path.read_text(encoding="utf-8"))
+ assert "extractor_error" not in recovered_state
+ assert _read_jsonl(
+ tmp_path / "agent-history" / "extractor" / "conversation.jsonl"
+ )[-1]["status"] == "accepted"
+
+
+
+
+async def test_builder_rejection_is_a_durable_fail_fast_state(tmp_path: Path) -> None:
+ coordinator = SessionCoordinator(
+ tmp_path,
+ "session-a",
+ lambda: _RejectingBuilderModel(),
+ )
+ await coordinator.evidence.append(
+ "task-started", {"query": "remember NimbusGate"}, task_id="t1"
+ )
+ finished = await coordinator.evidence.append(
+ "task-finished", {"result": "done"}, task_id="t1"
+ )
+
+ await coordinator.request_extract(finished["cursor"])
+ await coordinator.wait_idle()
+
+ state = json.loads(coordinator.state_path.read_text(encoding="utf-8"))
+ assert state["builder_error"]["error_type"] == "RuntimeError"
+ assert "duplicate IDs with incompatible payloads" in state["builder_error"]["error"]
+ builds = _read_jsonl(tmp_path / "audit" / "builds.jsonl")
+ assert builds[-1]["review"]["approved"] is False
+ pending = await coordinator.memory.search("NimbusGate")
+ assert pending["matches"][0]["build_state"] == "pending"
+
+
+
+
+async def test_adapter_cleanup_does_not_cancel_session_owned_background_agents(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import jiuwenswarm.agents.harness.common.rails.eternal_conversation.rail as rail_module
+
+ monkeypatch.setattr(rail_module, "get_agent_sessions_dir", lambda: tmp_path)
+ gate = asyncio.Event()
+ model = _ControlledModel(gate)
+ rail = EternalConversationRail()
+ rail.init(
+ SimpleNamespace(
+ system_prompt_builder=SystemPromptBuilder(language="cn"),
+ ability_manager=_AbilityManager(),
+ )
+ )
+ rail.configure_runtime(
+ enabled=True,
+ session_id="tui-session",
+ request_id="natural-1",
+ mode="agent",
+ channel="tui",
+ project_dir=str(tmp_path),
+ model=model,
+ )
+ context = SimpleNamespace(get_messages=lambda: [], set_messages=lambda _messages: None)
+ await rail.before_invoke(SimpleNamespace(context=context, inputs=SimpleNamespace(query="go")))
+ await rail.after_invoke(SimpleNamespace(inputs=SimpleNamespace(result="done")))
+ await asyncio.wait_for(model.entered.wait(), timeout=5)
+
+ await asyncio.wait_for(rail.close(), timeout=1)
+ gate.set()
+ await rail.wait_idle()
+ coordinator = rail._coordinator
+ assert coordinator is not None
+ state = await coordinator.memory.projection()
+ assert state["covered_through"] > 0
+ assert (await coordinator.memory.search("NimbusGate"))["matches"][0][
+ "build_state"
+ ] == "built"
+
+
+
+
+async def test_pending_builder_work_resumes_from_durable_state_after_restart(
+ tmp_path: Path,
+) -> None:
+ first = SessionCoordinator(tmp_path, "session-a", lambda: _FakeModel())
+ event = await first.evidence.append("task-finished", {"result": "done"}, task_id="t1")
+ proposal = {
+ "base_memory_revision": 0,
+ "base_snapshot_revision": 0,
+ "from_cursor": 1,
+ "to_cursor": event["cursor"],
+ "snapshot": {"constraints": ["Keep NimbusGate private"]},
+ "changed_uts": [
+ {
+ "action": "upsert",
+ "id": "ut-nimbus-gate",
+ "memory_id": "memory-ut-nimbus-gate",
+ "priority": 90,
+ "content": "NimbusGate is the private compatibility environment.",
+ "queries": ["NimbusGate"],
+ "must_include": ["NimbusGate"],
+ "evidence_refs": ["raw-history:cursor-1-1"],
+ "source": "session-a",
+ "tags": ["alias"],
+ }
+ ],
+ "evidence_refs": ["raw-history:cursor-1-1"],
+ "semantic_statement": "Preserve the exact alias.",
+ }
+ await first.memory.file_command("publish-pending", proposal, "restart-proposal")
+ write_json_atomic(
+ first.state_path,
+ {
+ "requested_cursor": event["cursor"],
+ "builder_error": {
+ "at": "2026-08-16T12:56:41+00:00",
+ "error_type": "FrameworkError",
+ "error": "Insufficient Balance",
+ },
+ },
+ )
+
+ restarted = SessionCoordinator(tmp_path, "session-a", lambda: _FakeModel())
+ await restarted.resume_background()
+ retry_state = json.loads(restarted.state_path.read_text(encoding="utf-8"))
+ assert "builder_error" not in retry_state
+ await restarted.wait_idle()
+ result = await restarted.memory.search("NimbusGate")
+ assert result["matches"][0]["build_state"] == "built"
+
+
+def test_registry_reuses_coordinator_for_recreated_adapter(tmp_path: Path) -> None:
+ first = get_session_coordinator(tmp_path, "session-a", lambda: _FakeModel())
+ second = get_session_coordinator(tmp_path, "session-a", lambda: _FakeModel())
+ assert second is first
+
+
+ ("value", "expected"),
+ [(True, True), (False, False), ("true", True), ("off", False), (None, False)],
+)
+
+
+def test_frontend_runtime_flag_is_explicit_and_default_off(value, expected) -> None:
+ params = {} if value is None else {"eternal_conversation_enabled": value}
+ assert JiuWenSwarmDeepAdapter._resolve_eternal_conversation_enabled(params) is expected
+
+
+ "source",
+ sorted(INTERRUPT_RESUME_SOURCES),
+)
+
+
+def test_eternal_interaction_resume_covers_all_hitl_resume_sources(source) -> None:
+ """Every HITL resume source must resume the suspended natural task.
+
+ A missed source (e.g. ask_user_interrupt) makes the adapter treat the user's
+ answer as a brand-new natural task: task-started/task-finished on a fresh
+ task_id while the interrupted task stays suspended forever, splitting one
+ natural task in the evidence chain.
+ """
+ assert JiuWenSwarmDeepAdapter._is_eternal_interaction_resume({"source": source}) is True
+
+
+def test_eternal_interaction_resume_rejects_natural_query_source() -> None:
+ assert JiuWenSwarmDeepAdapter._is_eternal_interaction_resume({"source": "query"}) is False
+ assert JiuWenSwarmDeepAdapter._is_eternal_interaction_resume({}) is False
+ assert JiuWenSwarmDeepAdapter._is_eternal_interaction_resume(None) is False
+
+
+class _AbilityManager:
+ def __init__(self) -> None:
+ self.cards: dict[str, object] = {}
+
+ def add_ability(self, card, tool):
+ self.cards[card.name] = card
+ return SimpleNamespace(added=True)
+
+ def remove_ability(self, name):
+ self.cards.pop(name, None)
+
+
+
+
+async def test_rail_is_inert_by_default_then_mounts_prompt_and_tool_per_session(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import jiuwenswarm.agents.harness.common.rails.eternal_conversation.rail as rail_module
+
+ monkeypatch.setattr(rail_module, "get_agent_sessions_dir", lambda: tmp_path)
+ builder = SystemPromptBuilder(language="cn")
+ manager = _AbilityManager()
+ agent = SimpleNamespace(system_prompt_builder=builder, ability_manager=manager)
+ rail = EternalConversationRail()
+ rail.init(agent)
+ assert manager.cards == {}
+
+ rail.configure_runtime(
+ enabled=True,
+ session_id="session-a",
+ request_id="request-1",
+ mode="agent",
+ channel="web",
+ project_dir=str(tmp_path),
+ model=_FakeModel(),
+ )
+ assert EternalConversationRail.TOOL_NAME in manager.cards
+ await rail.before_model_call(SimpleNamespace())
+ prompt = builder.build()
+ assert "search_long_term_memory" in prompt
+ assert "For every suspected conflict" in prompt
+ assert "at least two search_long_term_memory calls" in prompt
+ assert "even when the Snapshot already states the conflict" in prompt
+ assert "repeat that exact original term" in prompt
+ assert "final character MUST be ? or ?" in prompt
+ assert "Published memory records prior decisions" in prompt
+
+ rail.configure_runtime(
+ enabled=False,
+ session_id="session-a",
+ request_id="request-2",
+ mode="agent",
+ channel="web",
+ project_dir=str(tmp_path),
+ model=_FakeModel(),
+ )
+ assert manager.cards == {}
+ assert builder.get_section(EternalConversationRail.SECTION_NAME) is None
+
+ with pytest.raises(RuntimeError, match="multiple Sessions"):
+ rail.configure_runtime(
+ enabled=True,
+ session_id="session-b",
+ request_id="request-3",
+ mode="agent",
+ channel="web",
+ project_dir=str(tmp_path),
+ model=_FakeModel(),
+ )
+
+
+
+
+async def test_snapshot_replacement_waits_for_real_pre_admission_context_boundary(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import jiuwenswarm.agents.harness.common.rails.eternal_conversation.rail as rail_module
+
+ monkeypatch.setattr(rail_module, "get_agent_sessions_dir", lambda: tmp_path)
+ rail = EternalConversationRail()
+ rail.init(
+ SimpleNamespace(
+ system_prompt_builder=SystemPromptBuilder(language="cn"),
+ ability_manager=_AbilityManager(),
+ )
+ )
+ rail.configure_runtime(
+ enabled=True,
+ session_id="session-a",
+ request_id="task-new",
+ mode="agent",
+ channel="web",
+ project_dir=str(tmp_path),
+ model=_FakeModel(),
+ )
+ coordinator = rail._coordinator
+ assert coordinator is not None
+ old_finished = await coordinator.evidence.append(
+ "task-finished", {"result": "old"}, task_id="task-old"
+ )
+ await coordinator.request_extract(old_finished["cursor"])
+ await coordinator.wait_idle()
+
+ # ReactAgent initializes ModelContext only after BEFORE_INVOKE.
+ await rail.before_invoke(
+ SimpleNamespace(context=None, inputs=SimpleNamespace(query="new work"))
+ )
+ messages = ["old visible one", "old visible two"]
+
+ def set_messages(value) -> None:
+ messages[:] = value
+
+ context = SimpleNamespace(
+ get_messages=lambda: list(messages),
+ set_messages=set_messages,
+ )
+ await rail.on_user_message(
+ SimpleNamespace(
+ context=context,
+ inputs=SimpleNamespace(parts=["new work"], source="query"),
+ )
+ )
+
+ assert messages == []
+ harness = json.loads(coordinator.state_path.read_text(encoding="utf-8"))
+ assert harness["applied_snapshot_revision"] == 1
+ replaced = [
+ row
+ for row in _read_jsonl(coordinator.evidence.raw_path)
+ if row["type"] == "context-replaced"
+ ]
+ assert replaced[-1]["payload"]["replaced_messages"] == [
+ "old visible one",
+ "old visible two",
+ ]
+ assert (
+ replaced[-1]["payload"]["safe_boundary"]
+ == "before-user-message-admission"
+ )
+
+
+
+
+async def test_permission_resume_stays_inside_one_natural_task(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import jiuwenswarm.agents.harness.common.rails.eternal_conversation.rail as rail_module
+
+ monkeypatch.setattr(rail_module, "get_agent_sessions_dir", lambda: tmp_path)
+ agent = SimpleNamespace(
+ system_prompt_builder=SystemPromptBuilder(language="cn"),
+ ability_manager=_AbilityManager(),
+ )
+ rail = EternalConversationRail()
+ rail.init(agent)
+ rail.configure_runtime(
+ enabled=True,
+ session_id="session-a",
+ request_id="natural-1",
+ mode="agent",
+ channel="web",
+ project_dir=str(tmp_path),
+ model=_FakeModel(),
+ )
+ context = SimpleNamespace(get_messages=lambda: [], set_messages=lambda _messages: None)
+ await rail.before_invoke(
+ SimpleNamespace(context=context, inputs=SimpleNamespace(query="build it"))
+ )
+ await rail.after_invoke(
+ SimpleNamespace(
+ inputs=SimpleNamespace(result={"result_type": "interrupt"}),
+ )
+ )
+
+ rail.configure_runtime(
+ enabled=True,
+ session_id="session-a",
+ request_id="approval-1",
+ mode="agent",
+ channel="web",
+ project_dir=str(tmp_path),
+ model=_FakeModel(),
+ interaction_resume=True,
+ )
+ await rail.before_invoke(SimpleNamespace(context=context, inputs=SimpleNamespace(query="")))
+ await rail.after_invoke(SimpleNamespace(inputs=SimpleNamespace(result="done")))
+ await rail.wait_idle()
+
+ rows = _read_jsonl(
+ tmp_path
+ / "session-a"
+ / "eternal-conversation"
+ / "raw-history"
+ / "events.jsonl"
+ )
+ assert [row["type"] for row in rows].count("task-started") == 1
+ assert [row["type"] for row in rows].count("task-suspended") == 1
+ assert [row["type"] for row in rows].count("task-resumed") == 1
+ assert [row["type"] for row in rows].count("task-finished") == 1
+ assert {row["task_id"] for row in rows} == {"natural-1"}
diff --git a/tests/unit_tests/agentserver/rails/test_progressive_tool_inherit_flag.py b/tests/unit_tests/agentserver/rails/test_progressive_tool_inherit_flag.py
index cba0a5e311..a03528bae4 100644
--- a/tests/unit_tests/agentserver/rails/test_progressive_tool_inherit_flag.py
+++ b/tests/unit_tests/agentserver/rails/test_progressive_tool_inherit_flag.py
@@ -17,11 +17,22 @@ It reads the module via ``ast`` — NOT importing it — so it runs in CI
gates where the openjiuwen dependency may be unavailable.
Removing the flag (or flipping to True) silently re-exposes the rebind bug.
+
+The ``ast`` work runs in a throwaway interpreter. On the CI runners
+(Python 3.11.5, pytest-xdist) an in-process ``ast.parse`` of this rail
+file intermittently dies with ``SystemError: AST constructor recursion
+depth mismatch (before=141, after=157/158)`` even though the file's
+brace nesting depth is 3 — the AST constructor's recursion counter is
+process-wide and can be left corrupted by earlier parses in the same
+worker, so the failure depends on test order, not on this file. A fresh
+interpreter starts with clean state and cannot inherit that corruption.
"""
from __future__ import annotations
-import ast
+import json
+import subprocess
+import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[4]
@@ -35,29 +46,60 @@ RAIL_PATH = (
/ "progressive_tool_rail.py"
)
+# Child interpreter script: read and parse the rail file, dump the top-level
+# assignments of the requested class, and emit the reference dump of the
+# literal False. The file is read (and only read) inside the child so the
+# source never crosses a locale-dependent stdio pipe.
+_CHILD_SCRIPT = """\
+import ast, json, sys
+with open(sys.argv[1], encoding="utf-8") as fh:
+ source = fh.read()
+tree = ast.parse(source, filename=sys.argv[1])
+assigns = {}
+for node in ast.walk(tree):
+ if isinstance(node, ast.ClassDef) and node.name == sys.argv[2]:
+ for stmt in node.body:
+ if (
+ isinstance(stmt, ast.Assign)
+ and len(stmt.targets) == 1
+ and isinstance(stmt.targets[0], ast.Name)
+ ):
+ assigns[stmt.targets[0].id] = ast.dump(stmt.value)
+ break
+false_dump = ast.dump(ast.parse("False", mode="eval").body)
+print(json.dumps({"assigns": assigns, "false_dump": false_dump}))
+"""
+
-def _find_class_assignments(source: str, class_name: str) -> dict[str, ast.AST]:
- """Return ``{attr_name: value_node}`` for top-level assigns in a class."""
- tree = ast.parse(source, filename=str(RAIL_PATH))
- for node in ast.walk(tree):
- if isinstance(node, ast.ClassDef) and node.name == class_name:
- assigns: dict[str, ast.AST] = {}
- for stmt in node.body:
- if (
- isinstance(stmt, ast.Assign)
- and len(stmt.targets) == 1
- and isinstance(stmt.targets[0], ast.Name)
- ):
- assigns[stmt.targets[0].id] = stmt.value
- return assigns
- return {}
+def _find_class_assignments(class_name: str) -> tuple[dict[str, str], str]:
+ """Parse in a child interpreter; return ({attr_name: dump}, literal-False dump).
+
+ See the module docstring: an in-process ``ast.parse`` is unreliable on
+ CPython 3.11 CI workers once earlier tests corrupted its AST recursion
+ counter. The child only needs stdlib, so this stays valid in CI gates
+ without the openjiuwen dependency.
+ """
+ proc = subprocess.run(
+ [sys.executable, "-I", "-B", "-c", _CHILD_SCRIPT, str(RAIL_PATH), class_name],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=120,
+ check=False,
+ )
+ if proc.returncode != 0 or not proc.stdout.strip():
+ raise AssertionError(
+ f"child ast.parse of {RAIL_PATH} failed (rc={proc.returncode}):\n{proc.stderr}"
+ )
+ payload = json.loads(proc.stdout)
+ return payload["assigns"], payload["false_dump"]
def test_inherit_to_subagents_is_false():
"""Flag must stay False — guards against accidental deletion/flipping."""
assert RAIL_PATH.is_file(), f"rail source not found: {RAIL_PATH}"
- source = RAIL_PATH.read_text(encoding="utf-8")
- assigns = _find_class_assignments(source, "ProgressiveToolRail")
+ assigns, false_dump = _find_class_assignments("ProgressiveToolRail")
assert "inherit_to_subagents" in assigns, (
"ProgressiveToolRail must declare inherit_to_subagents = False; "
@@ -65,7 +107,6 @@ def test_inherit_to_subagents_is_false():
"(child init rebinds _deep_agent → deferred cache loses "
"subagent_wait → parent invoke_tool reports 未注册)"
)
- value = assigns["inherit_to_subagents"]
- assert ast.dump(value) == ast.dump(
- ast.parse("False", mode="eval").body
- ), "ProgressiveToolRail.inherit_to_subagents must be the literal False"
+ assert assigns["inherit_to_subagents"] == false_dump, (
+ "ProgressiveToolRail.inherit_to_subagents must be the literal False"
+ )
diff --git a/tests/unit_tests/agentserver/test_shutdown_context_session_memory.py b/tests/unit_tests/agentserver/test_shutdown_context_session_memory.py
new file mode 100644
index 0000000000..6d34f8731a
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_shutdown_context_session_memory.py
@@ -0,0 +1,62 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""CR-5: shutdown_context_session_memory 三态日志语义.
+
+区分"属性缺失(框架改名,保留 WARNING 防双记忆后端)"与"属性合法
+为 None(未配置/已关闭的幂等态,仅 debug)"与"manager 在位(关闭
+并返回 True)"。
+"""
+
+from __future__ import annotations
+
+import logging
+
+from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
+ JiuWenSwarmDeepAdapter,
+)
+
+
+class _FakeManager:
+ def __init__(self) -> None:
+ self.shutdown_calls = 0
+
+ def shutdown(self) -> None:
+ self.shutdown_calls += 1
+
+
+class _LiveRail:
+ def __init__(self) -> None:
+ self._session_memory_mgr = _FakeManager()
+
+
+class _NoneRail:
+ def __init__(self) -> None:
+ self._session_memory_mgr = None
+
+
+class _MissingRail:
+ """完全不含该属性(框架改名 / 异型 rail 场景)。"""
+
+
+def test_live_manager_is_shutdown_and_reset() -> None:
+ rail = _LiveRail()
+ manager = rail._session_memory_mgr
+ assert JiuWenSwarmDeepAdapter.shutdown_context_session_memory(rail) is True
+ assert manager.shutdown_calls == 1
+ assert rail._session_memory_mgr is None
+
+
+def test_none_attribute_is_silent_idempotent_state(caplog) -> None:
+ rail = _NoneRail()
+ with caplog.at_level(logging.WARNING):
+ assert JiuWenSwarmDeepAdapter.shutdown_context_session_memory(rail) is False
+ assert not [record for record in caplog.records if record.levelno >= logging.WARNING]
+
+
+def test_missing_attribute_keeps_guard_warning(caplog) -> None:
+ rail = _MissingRail()
+ with caplog.at_level(logging.WARNING):
+ assert JiuWenSwarmDeepAdapter.shutdown_context_session_memory(rail) is False
+ warnings = [record for record in caplog.records if record.levelno >= logging.WARNING]
+ assert len(warnings) == 1
+ assert "double memory backend" in warnings[0].getMessage()