diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..3bdc953
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,18 @@
+.venv/
+var/
+.git/
+__pycache__/
+*.pyc
+confidential/
+.modelscorp.json
+backups/
+tmp/
+docs/
+scenarios/
+lib/
+tests/
+references/
+specs/
+validation/
+*.egg-info/
+.env
diff --git a/.gitignore b/.gitignore
index 8e52ccb..3733a64 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,3 +10,5 @@ build/
.venv/
application_default_credentials.json
backups/
+confidential/
+.modelscorp.json
diff --git a/.modelscorp.json.example b/.modelscorp.json.example
new file mode 100644
index 0000000..1577889
--- /dev/null
+++ b/.modelscorp.json.example
@@ -0,0 +1,11 @@
+{
+ "endpoint_base": "YOUR_ENDPOINT_HOST",
+ "endpoint_type": "apicast-staging",
+ "models": {
+ "granite-4-0-micro": {"key": "YOUR_KEY", "model_id": "ibm-granite/granite-4.0-micro"},
+ "granite-4-0-h-tiny": {"key": "YOUR_KEY", "model_id": "ibm-granite/granite-4.0-h-tiny"},
+ "qwen3-14b": {"key": "YOUR_KEY", "model_id": "Qwen/Qwen3-14B"},
+ "gemini": {"key": "YOUR_KEY", "model_id": "gemini-2.5-pro", "endpoint_type": "apicast-production", "base_path": "/v1beta/openai"},
+ "claude": {"key": "YOUR_KEY", "model_id": "claude-sonnet-4-20250514"}
+ }
+}
diff --git a/Makefile b/Makefile
index 3b1b7ff..f4bc2bc 100644
--- a/Makefile
+++ b/Makefile
@@ -4,7 +4,7 @@ PYTHON := $(VENV)/bin/python
PYTEST := $(VENV)/bin/pytest
RUFF := $(VENV)/bin/ruff
-.PHONY: help venv install test lint lint-fix clean start build-sandbox
+.PHONY: help venv install test lint lint-fix clean start build-agent build-sandbox
help: ## Show this help
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-15s\033[0m %s\n", $$1, $$2}'
@@ -19,16 +19,19 @@ test: install ## Run tests
$(PYTEST) -v
lint: install ## Check code style
- $(RUFF) check lib/ tests/ main.py
- $(RUFF) format --check lib/ tests/ main.py
+ $(RUFF) check lib/ tests/ main.py cosim_agent/
+ $(RUFF) format --check lib/ tests/ main.py cosim_agent/
lint-fix: install ## Auto-fix lint issues
- $(RUFF) check --fix lib/ tests/ main.py
- $(RUFF) format lib/ tests/ main.py
+ $(RUFF) check --fix lib/ tests/ main.py cosim_agent/
+ $(RUFF) format lib/ tests/ main.py cosim_agent/
start: install ## Start the full stack via honcho
$(UV) run honcho start
+build-agent: ## Build the agent container image
+ podman build -f container/Dockerfile.agent -t agent-image:latest .
+
build-sandbox: ## Build the sandbox container image
podman build -f container/Dockerfile.sandbox -t cosim-sandbox:latest container/
diff --git a/README.md b/README.md
index da67cf6..0eec9fd 100644
--- a/README.md
+++ b/README.md
@@ -49,7 +49,7 @@ The agent image contains Claude Code CLI and telemetry hooks. GCP credentials ar
./scripts/build-agent-image.sh
```
-This runs `podman build -f container/Dockerfile.agent -t agent-image:latest container/` after verifying prerequisites.
+This runs `podman build -f container/Dockerfile.agent -t agent-image:latest .` after verifying prerequisites.
**What goes into the image:**
- Python 3.13-slim base
diff --git a/container/Dockerfile.agent b/container/Dockerfile.agent
index feb40bb..5347ef0 100644
--- a/container/Dockerfile.agent
+++ b/container/Dockerfile.agent
@@ -5,9 +5,13 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
&& npm install -g @anthropic-ai/claude-code @openai/codex \
&& apt-get clean && rm -rf /var/lib/apt/lists/*
+COPY cosim_agent/ /tmp/cosim-agent/cosim_agent/
+COPY cosim_agent/pyproject.toml /tmp/cosim-agent/pyproject.toml
+RUN pip install --no-cache-dir /tmp/cosim-agent && rm -rf /tmp/cosim-agent
+
RUN useradd -m -s /bin/bash agent
-COPY agent-hooks.json /home/agent/.claude/hooks.json
+COPY container/agent-hooks.json /home/agent/.claude/hooks.json
# Credentials directories (files mounted at runtime, not baked into image)
RUN mkdir -p /home/agent/.config/gcloud /home/agent/.codex
@@ -28,7 +32,7 @@ WORKDIR /home/agent/scratch
CMD ["sleep", "infinity"]
# Usage (podman — Flask+MCP run on host):
-# podman build -f container/Dockerfile.agent -t agent-image:latest container/
+# podman build -f container/Dockerfile.agent -t agent-image:latest .
# podman run -d --name agent-pm \
# -e AGENT_PERSONA_KEY=pm \
# -e MCP_SERVER_URL=host.containers.internal:5001 \
diff --git a/cosim_agent/__init__.py b/cosim_agent/__init__.py
new file mode 100644
index 0000000..a2b1ab4
--- /dev/null
+++ b/cosim_agent/__init__.py
@@ -0,0 +1,3 @@
+"""cosim-agent — Models.Corp agent harness for the cosim platform."""
+
+__version__ = "0.1.0"
diff --git a/cosim_agent/agent.py b/cosim_agent/agent.py
new file mode 100644
index 0000000..6d9b4a0
--- /dev/null
+++ b/cosim_agent/agent.py
@@ -0,0 +1,356 @@
+#!/usr/bin/env python3
+"""Models.Corp agent harness — agentic tool-calling loop using OpenAI-compatible API.
+
+Runs inside a podman container. Connects to an MCP server for tool discovery
+and execution, calls a Models.Corp LLM endpoint via the OpenAI SDK, and loops
+until the model stops requesting tools or max turns is reached.
+
+Output: JSONL to stdout (parsed by ModelscorpBackend).
+Logs: stderr.
+"""
+
+import argparse
+import json
+import os
+import sys
+import time
+
+from openai import DefaultHttpxClient, OpenAI
+
+from cosim_agent.mcp_client import MCPClient, mcp_tools_to_openai, parse_text_tool_calls
+from cosim_agent.memory import create_memory
+
+
+def log(msg: str) -> None:
+ print(msg, file=sys.stderr, flush=True)
+
+
+def emit(obj: dict) -> None:
+ print(json.dumps(obj), flush=True)
+
+
+# ── Config loading ──────────────────────────────────────────────────────
+
+
+def load_config(config_path: str) -> dict:
+ with open(config_path) as f:
+ return json.load(f)
+
+
+def build_base_url(config: dict, model: str) -> str:
+ """Build the OpenAI-compatible base URL for a given model."""
+ endpoint_base = config["endpoint_base"]
+ model_cfg = config.get("models", {}).get(model, {})
+ endpoint_type = model_cfg.get("endpoint_type", config.get("endpoint_type", "staging"))
+ base_path = model_cfg.get("base_path", "")
+ return f"https://{model}--{endpoint_type}.{endpoint_base}:443{base_path or '/v1'}"
+
+
+def get_api_key(config: dict, model: str) -> str:
+ model_cfg = config.get("models", {}).get(model, {})
+ key = model_cfg.get("key", "")
+ if not key:
+ raise ValueError(f"No API key configured for model '{model}' in config")
+ return key
+
+
+def get_model_id(config: dict, model: str) -> str:
+ """Get the model ID to send in API requests (may differ from the URL slug)."""
+ model_cfg = config.get("models", {}).get(model, {})
+ return model_cfg.get("model_id", model)
+
+
+# ── Agent loop ──────────────────────────────────────────────────────────
+
+
+def run_agent(
+ prompt: str,
+ system_prompt: str,
+ mcp_url: str,
+ model: str,
+ max_turns: int,
+ config: dict,
+ allowed_tools: list[str] | None = None,
+ memory_config: dict | None = None,
+ fallback_channel: str = "",
+) -> None:
+ base_url = build_base_url(config, model)
+ api_key = get_api_key(config, model)
+ model_id = get_model_id(config, model)
+
+ log(f"Model slug: {model}")
+ log(f"Model ID: {model_id}")
+ log(f"Base URL: {base_url}")
+ log(f"Max turns: {max_turns}")
+
+ client = OpenAI(
+ base_url=base_url,
+ api_key=api_key,
+ http_client=DefaultHttpxClient(verify=False),
+ )
+
+ mcp = MCPClient(mcp_url)
+ try:
+ log("Initializing MCP session ...")
+ mcp.initialize()
+
+ log("Fetching MCP tools ...")
+ mcp_tools = mcp.list_tools()
+ if allowed_tools:
+ mcp_tools = [t for t in mcp_tools if t["name"] in allowed_tools]
+ log(f"Filtered to {len(mcp_tools)} allowed tools")
+ openai_tools = mcp_tools_to_openai(mcp_tools)
+ log(f"Discovered {len(openai_tools)} tools")
+
+ mem_cfg = memory_config or {"strategy": "none"}
+ memory = create_memory(mem_cfg, system_prompt, llm_client=client, llm_model=model_id)
+ memory.load()
+ log(f"Memory config: {mem_cfg}")
+ messages = memory.get_messages(prompt)
+
+ total_input_tokens = 0
+ total_output_tokens = 0
+ last_text = ""
+ turns = 0
+ turn_start_idx = len(messages) - 1 # include the user prompt in saved messages
+ posted_message = False
+
+ while turns < max_turns:
+ turns += 1
+ log(f"Turn {turns}/{max_turns} ...")
+
+ kwargs: dict = {
+ "model": model_id,
+ "messages": messages,
+ }
+ if openai_tools:
+ kwargs["tools"] = openai_tools
+
+ try:
+ response = client.chat.completions.create(**kwargs)
+ except Exception as e:
+ error_str = str(e)
+ if "429" in error_str or "rate" in error_str.lower():
+ wait = min(2**turns, 60)
+ log(f"Rate limited, waiting {wait}s ...")
+ time.sleep(wait)
+ turns -= 1
+ continue
+ raise
+
+ choice = response.choices[0]
+ message = choice.message
+
+ if response.usage:
+ total_input_tokens += response.usage.prompt_tokens or 0
+ total_output_tokens += response.usage.completion_tokens or 0
+
+ assistant_msg: dict = {"role": "assistant"}
+ if message.content:
+ assistant_msg["content"] = message.content
+ last_text = message.content
+
+ if message.tool_calls:
+ assistant_msg["tool_calls"] = [
+ {
+ "id": tc.id,
+ "type": "function",
+ "function": {
+ "name": tc.function.name,
+ "arguments": tc.function.arguments,
+ },
+ }
+ for tc in message.tool_calls
+ ]
+
+ messages.append(assistant_msg)
+
+ native_calls = message.tool_calls or []
+ text_calls = []
+ if not native_calls and message.content:
+ text_calls = parse_text_tool_calls(message.content)
+ if text_calls:
+ log(f" Parsed {len(text_calls)} tool call(s) from text")
+ assistant_msg["tool_calls"] = [
+ {
+ "id": tc["id"],
+ "type": "function",
+ "function": {"name": tc["name"], "arguments": tc["arguments"]},
+ }
+ for tc in text_calls
+ ]
+
+ tool_call_names = []
+ has_tool_calls = bool(native_calls or text_calls)
+
+ if native_calls:
+ for tc in native_calls:
+ name = tc.function.name
+ tool_call_names.append(name)
+ try:
+ args = json.loads(tc.function.arguments)
+ except (json.JSONDecodeError, TypeError):
+ args = {}
+
+ log(f" Tool: {name}({json.dumps(args, ensure_ascii=False)[:200]})")
+
+ try:
+ result = mcp.call_tool(name, args)
+ except Exception as e:
+ result = f"Error calling tool {name}: {e}"
+ log(f" Tool error: {e}")
+
+ messages.append(
+ {
+ "role": "tool",
+ "tool_call_id": tc.id,
+ "content": result,
+ }
+ )
+
+ elif text_calls:
+ for tc in text_calls:
+ name = tc["name"]
+ tool_call_names.append(name)
+ try:
+ args = json.loads(tc["arguments"])
+ except (json.JSONDecodeError, TypeError):
+ args = {}
+
+ log(f" Tool: {name}({json.dumps(args, ensure_ascii=False)[:200]})")
+
+ try:
+ result = mcp.call_tool(name, args)
+ except Exception as e:
+ result = f"Error calling tool {name}: {e}"
+ log(f" Tool error: {e}")
+
+ messages.append(
+ {
+ "role": "tool",
+ "tool_call_id": tc["id"],
+ "content": result,
+ }
+ )
+
+ if "post_message" in tool_call_names:
+ posted_message = True
+
+ emit(
+ {
+ "type": "turn",
+ "turn": turns,
+ "content": message.content or "",
+ "tool_calls": tool_call_names,
+ }
+ )
+
+ if not has_tool_calls:
+ log("Model finished (no more tool calls)")
+ break
+
+ if "signal_done" in tool_call_names:
+ log("Agent signaled done — stopping loop")
+ break
+
+ if fallback_channel and last_text and not posted_message:
+ log(f"Fallback: model produced text but never called post_message — auto-posting to {fallback_channel}")
+ try:
+ mcp.call_tool("post_message", {"channel": fallback_channel, "content": last_text})
+ except Exception as e:
+ log(f"Fallback post_message failed: {e}")
+
+ new_messages = messages[turn_start_idx:]
+ if new_messages:
+ memory.add_messages(new_messages)
+ memory.save()
+
+ emit(
+ {
+ "type": "result",
+ "response_text": last_text,
+ "turns": turns,
+ "input_tokens": total_input_tokens,
+ "output_tokens": total_output_tokens,
+ }
+ )
+
+ finally:
+ mcp.close()
+
+
+# ── CLI ─────────────────────────────────────────────────────────────────
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description="Models.Corp agent harness")
+ parser.add_argument("--prompt", required=True, help="Turn prompt")
+ parser.add_argument("--system-prompt-file", required=True, help="Path to system prompt file")
+ parser.add_argument("--mcp-url", required=True, help="MCP Streamable HTTP endpoint URL")
+ parser.add_argument("--model", required=True, help="Model slug (e.g. granite-4-0-micro)")
+ parser.add_argument("--max-turns", type=int, default=50, help="Max agentic turns")
+ parser.add_argument("--config", required=True, help="Path to .modelscorp.json config")
+ parser.add_argument("--allowed-tools", default="", help="Comma-separated list of allowed tool names (empty=all)")
+ parser.add_argument(
+ "--memory-config",
+ default="",
+ help="JSON blob of memory config (strategy, session_file, max_messages, etc.)",
+ )
+ parser.add_argument("--memory-strategy", default="none", help="(legacy) Conversation memory strategy")
+ parser.add_argument("--session-file", default="", help="(legacy) Path to JSONL session history file")
+ parser.add_argument("--memory-max-messages", type=int, default=50, help="(legacy) Max messages in FIFO window")
+ parser.add_argument(
+ "--fallback-channel",
+ default="",
+ help="If the model produces text but never calls post_message, auto-post to this channel",
+ )
+ args = parser.parse_args()
+
+ with open(args.system_prompt_file) as f:
+ system_prompt = f.read()
+
+ config = load_config(args.config)
+ allowed_tools = [t.strip() for t in args.allowed_tools.split(",") if t.strip()] or None
+
+ if args.memory_config:
+ mem_cfg = json.loads(args.memory_config)
+ else:
+ mem_cfg = {
+ "strategy": args.memory_strategy,
+ "session_file": args.session_file,
+ "max_messages": args.memory_max_messages,
+ }
+
+ session_file = mem_cfg.get("session_file", "")
+ if session_file:
+ os.makedirs(os.path.dirname(session_file), exist_ok=True)
+
+ try:
+ run_agent(
+ prompt=args.prompt,
+ system_prompt=system_prompt,
+ mcp_url=args.mcp_url,
+ model=args.model,
+ max_turns=args.max_turns,
+ config=config,
+ allowed_tools=allowed_tools,
+ memory_config=mem_cfg,
+ fallback_channel=args.fallback_channel,
+ )
+ except Exception as e:
+ log(f"FATAL: {e}")
+ emit(
+ {
+ "type": "result",
+ "response_text": "",
+ "turns": 0,
+ "input_tokens": 0,
+ "output_tokens": 0,
+ "error": str(e),
+ }
+ )
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/cosim_agent/mcp_client.py b/cosim_agent/mcp_client.py
new file mode 100644
index 0000000..39f1618
--- /dev/null
+++ b/cosim_agent/mcp_client.py
@@ -0,0 +1,126 @@
+"""MCP client and tool-format helpers for the Models.Corp agent harness."""
+
+from __future__ import annotations
+
+import json
+import re
+import uuid
+
+import httpx
+
+
+class MCPClient:
+ """Minimal MCP client using JSON-RPC over HTTP POST."""
+
+ def __init__(self, url: str, timeout: float = 30.0):
+ self._url = url
+ self._timeout = timeout
+ self._session_id: str | None = None
+ self._req_id = 0
+ self._client = httpx.Client(timeout=timeout, verify=False)
+
+ def _next_id(self) -> int:
+ self._req_id += 1
+ return self._req_id
+
+ def _post(self, method: str, params: dict | None = None) -> dict:
+ body: dict = {
+ "jsonrpc": "2.0",
+ "method": method,
+ "id": self._next_id(),
+ }
+ if params:
+ body["params"] = params
+
+ headers: dict[str, str] = {
+ "Content-Type": "application/json",
+ "Accept": "application/json, text/event-stream",
+ }
+ if self._session_id:
+ headers["mcp-session-id"] = self._session_id
+
+ resp = self._client.post(self._url, json=body, headers=headers)
+ resp.raise_for_status()
+
+ if not self._session_id:
+ sid = resp.headers.get("mcp-session-id")
+ if sid:
+ self._session_id = sid
+
+ return resp.json()
+
+ def initialize(self) -> dict:
+ result = self._post(
+ "initialize",
+ {
+ "protocolVersion": "2025-03-26",
+ "capabilities": {},
+ "clientInfo": {"name": "modelscorp-agent", "version": "1.0"},
+ },
+ )
+ self._post("notifications/initialized")
+ return result
+
+ def list_tools(self) -> list[dict]:
+ result = self._post("tools/list")
+ return result.get("result", {}).get("tools", [])
+
+ def call_tool(self, name: str, arguments: dict) -> str:
+ result = self._post("tools/call", {"name": name, "arguments": arguments})
+ tool_result = result.get("result", {})
+ content = tool_result.get("content", [])
+ parts = []
+ for item in content:
+ if isinstance(item, dict) and item.get("type") == "text":
+ parts.append(item.get("text", ""))
+ elif isinstance(item, str):
+ parts.append(item)
+ return "\n".join(parts) if parts else json.dumps(tool_result)
+
+ def close(self):
+ self._client.close()
+
+
+def mcp_tools_to_openai(mcp_tools: list[dict]) -> list[dict]:
+ """Convert MCP tool definitions to OpenAI function-calling format."""
+ openai_tools = []
+ for tool in mcp_tools:
+ schema = tool.get("inputSchema", {"type": "object", "properties": {}})
+ openai_tools.append(
+ {
+ "type": "function",
+ "function": {
+ "name": tool["name"],
+ "description": tool.get("description", ""),
+ "parameters": schema,
+ },
+ }
+ )
+ return openai_tools
+
+
+_TOOL_CALL_RE = re.compile(
+ r"\s*(\{.*?\})\s*",
+ re.DOTALL,
+)
+
+
+def parse_text_tool_calls(text: str) -> list[dict]:
+ """Extract tool calls from tags in model text output."""
+ calls = []
+ for match in _TOOL_CALL_RE.finditer(text):
+ try:
+ parsed = json.loads(match.group(1))
+ raw_args = parsed.get("arguments", {})
+ if isinstance(raw_args, str):
+ raw_args = json.loads(raw_args)
+ calls.append(
+ {
+ "id": f"call_{uuid.uuid4().hex[:12]}",
+ "name": parsed.get("name", ""),
+ "arguments": json.dumps(raw_args),
+ }
+ )
+ except (json.JSONDecodeError, KeyError):
+ continue
+ return calls
diff --git a/cosim_agent/memory/__init__.py b/cosim_agent/memory/__init__.py
new file mode 100644
index 0000000..dec9712
--- /dev/null
+++ b/cosim_agent/memory/__init__.py
@@ -0,0 +1,72 @@
+"""Pluggable conversation memory for the Models.Corp agent harness.
+
+Strategies control how prior conversation history is managed across turns.
+Full history is always preserved on disk; the strategy only controls what
+subset is sent to the LLM API.
+"""
+
+from __future__ import annotations
+
+from cosim_agent.memory.base import ConversationMemory
+from cosim_agent.memory.decay import DecayMemory
+from cosim_agent.memory.entity import EntityMemory
+from cosim_agent.memory.episodic import EpisodicMemory
+from cosim_agent.memory.fifo import FIFOMemory
+from cosim_agent.memory.none import NoMemory
+from cosim_agent.memory.reflexion import ReflexionMemory
+from cosim_agent.memory.summary import SummaryMemory
+from cosim_agent.memory.summary_buffer import SummaryBufferMemory
+
+__all__ = [
+ "ConversationMemory",
+ "NoMemory",
+ "FIFOMemory",
+ "SummaryMemory",
+ "SummaryBufferMemory",
+ "DecayMemory",
+ "EntityMemory",
+ "EpisodicMemory",
+ "ReflexionMemory",
+ "create_memory",
+]
+
+_STRATEGIES: dict[str, type[ConversationMemory]] = {
+ "none": NoMemory,
+ "fifo": FIFOMemory,
+ "summary": SummaryMemory,
+ "summary-buffer": SummaryBufferMemory,
+ "decay": DecayMemory,
+ "entity": EntityMemory,
+ "episodic": EpisodicMemory,
+ "reflexion": ReflexionMemory,
+}
+
+
+def create_memory(
+ config: dict,
+ system_prompt: str,
+ llm_client=None,
+ llm_model: str = "",
+) -> ConversationMemory:
+ """Factory — create a memory instance from a config dict.
+
+ Config keys:
+ strategy: str — strategy name ("none", "fifo", "summary", "summary-buffer")
+ session_file: str — path to JSONL session file
+ max_messages: int — FIFO window size (default 50)
+ ... future keys passed through as kwargs to the strategy
+
+ The llm_client and llm_model parameters are passed through to strategies
+ that need LLM access for summarization (summary, summary-buffer).
+ """
+ strategy = config.get("strategy", "none")
+ session_file = config.get("session_file", "")
+ cls = _STRATEGIES.get(strategy)
+ if cls is None:
+ raise ValueError(f"Unknown memory strategy '{strategy}'. Available: {list(_STRATEGIES)}")
+ kwargs = {k: v for k, v in config.items() if k not in ("strategy", "session_file")}
+ if llm_client is not None:
+ kwargs["llm_client"] = llm_client
+ if llm_model:
+ kwargs["llm_model"] = llm_model
+ return cls(session_file=session_file, system_prompt=system_prompt, **kwargs)
diff --git a/cosim_agent/memory/base.py b/cosim_agent/memory/base.py
new file mode 100644
index 0000000..6a4a43e
--- /dev/null
+++ b/cosim_agent/memory/base.py
@@ -0,0 +1,54 @@
+"""Base class for conversation memory strategies."""
+
+from __future__ import annotations
+
+import time
+from abc import ABC, abstractmethod
+
+_API_FIELDS = {"role", "content", "tool_calls", "tool_call_id", "name"}
+
+
+class ConversationMemory(ABC):
+ """Base class for conversation memory strategies."""
+
+ def __init__(self, session_file: str, system_prompt: str, **kwargs):
+ self._session_file = session_file
+ self._system_prompt = system_prompt
+ self._turn_counter = 0
+
+ @abstractmethod
+ def load(self) -> None:
+ """Load prior history from disk."""
+
+ @abstractmethod
+ def get_messages(self, new_user_message: str) -> list[dict]:
+ """Return the messages array for the API call."""
+
+ @abstractmethod
+ def add_messages(self, messages: list[dict]) -> None:
+ """Append this turn's messages (assistant + tool results) to history."""
+
+ @abstractmethod
+ def save(self) -> None:
+ """Persist history to disk."""
+
+ def _add_meta(self, msg: dict, **extra) -> dict:
+ """Attach _meta to a message for storage. Returns the same dict, mutated."""
+ meta = msg.get("_meta", {})
+ meta.setdefault("ts", time.time())
+ meta.setdefault("turn", self._turn_counter)
+ meta.setdefault("pinned", False)
+ meta.update(extra)
+ msg["_meta"] = meta
+ return msg
+
+ @staticmethod
+ def _normalize_for_api(messages: list[dict]) -> list[dict]:
+ """Strip _meta and non-standard fields before sending to the LLM API."""
+ normalized = []
+ for msg in messages:
+ clean = {k: v for k, v in msg.items() if k in _API_FIELDS and v is not None}
+ if "content" not in clean and "tool_calls" not in clean:
+ clean["content"] = ""
+ normalized.append(clean)
+ return normalized
diff --git a/cosim_agent/memory/decay.py b/cosim_agent/memory/decay.py
new file mode 100644
index 0000000..b080183
--- /dev/null
+++ b/cosim_agent/memory/decay.py
@@ -0,0 +1,80 @@
+"""DecayMemory — score-based selection using exponential decay."""
+
+from __future__ import annotations
+
+import math
+import time
+
+from cosim_agent.memory.fifo import FIFOMemory
+
+
+class DecayMemory(FIFOMemory):
+ """Replaces strict FIFO positional selection with score-based selection.
+
+ Scoring formula: score = importance * exp(-lambda * age_hours)
+ where lambda = ln(2) / decay_halflife_hours.
+
+ Pinned messages bypass scoring and are always included. Selected
+ messages are re-sorted chronologically for coherent context.
+
+ Config keys (in addition to FIFOMemory keys):
+ decay_halflife_hours: float — half-life for decay (default 4.0)
+ """
+
+ def __init__(self, session_file: str, system_prompt: str, **kwargs):
+ super().__init__(session_file, system_prompt, **kwargs)
+ self._decay_halflife: float = kwargs.get("decay_halflife_hours", 4.0)
+ self._decay_lambda: float = math.log(2) / self._decay_halflife if self._decay_halflife > 0 else 0.0
+
+ def _score_unit(self, unit: list[dict], now: float) -> float:
+ ts = max(msg.get("_meta", {}).get("ts", now) for msg in unit)
+ age_hours = (now - ts) / 3600.0
+ importance = max(msg.get("_meta", {}).get("importance", 1.0) for msg in unit)
+ return importance * math.exp(-self._decay_lambda * age_hours)
+
+ def get_messages(self, new_user_message: str) -> list[dict]:
+ if self._clear_tool_results:
+ eligible = self._clear_old_tool_pairs(self._history)
+ else:
+ eligible = self._strip_tool_traffic(self._history)
+
+ units = self._group_into_units(eligible)
+ now = time.time()
+
+ if self._compiled_pins:
+ pinned_units: list[list[dict]] = []
+ scorable: list[tuple[int, list[dict]]] = []
+ for i, unit in enumerate(units):
+ if any(self._is_pinned(msg) for msg in unit):
+ pinned_units.append(unit)
+ else:
+ scorable.append((i, unit))
+ else:
+ pinned_units = []
+ scorable = list(enumerate(units))
+
+ scored = [(idx, unit, self._score_unit(unit, now)) for idx, unit in scorable]
+ scored.sort(key=lambda x: x[2], reverse=True)
+
+ selected: list[tuple[int, list[dict]]] = []
+ count = 0
+ for idx, unit, _score in scored:
+ unit_size = len(unit)
+ if selected and count + unit_size > self._max_messages:
+ break
+ selected.append((idx, unit))
+ count += unit_size
+
+ selected.sort(key=lambda x: x[0])
+
+ pinned_msgs = [msg for unit in pinned_units for msg in unit]
+ selected_msgs = [msg for _, unit in selected for msg in unit]
+
+ assembled = [
+ {"role": "system", "content": self._system_prompt},
+ *pinned_msgs,
+ *selected_msgs,
+ {"role": "user", "content": new_user_message},
+ ]
+
+ return self._normalize_for_api(assembled)
diff --git a/cosim_agent/memory/entity.py b/cosim_agent/memory/entity.py
new file mode 100644
index 0000000..1c2dbbb
--- /dev/null
+++ b/cosim_agent/memory/entity.py
@@ -0,0 +1,94 @@
+"""EntityMemory — LLM entity extraction and injection."""
+
+from __future__ import annotations
+
+import json
+import os
+
+from cosim_agent.memory.fifo import FIFOMemory
+from cosim_agent.memory.summary import format_messages_for_summary
+
+_EXTRACT_SYSTEM = (
+ "Extract entities (people, projects, systems, tools) mentioned in the conversation. "
+ "Return a JSON object mapping entity names to one-sentence summaries. "
+ "Only include entities with meaningful information. Return empty {} if none found."
+)
+
+
+class EntityMemory(FIFOMemory):
+ """FIFO window with LLM-extracted entity summaries injected into context.
+
+ After each turn, extracts entities via an LLM call and maintains a
+ persistent entity store. Entity summaries are injected as a system
+ message after the main system prompt.
+
+ Config keys (in addition to FIFOMemory keys):
+ llm_client: OpenAI — client instance for entity extraction
+ llm_model: str — model ID for extraction calls
+ max_entity_tokens: int — max_tokens for extraction (default 300)
+ """
+
+ def __init__(self, session_file: str, system_prompt: str, **kwargs):
+ super().__init__(session_file, system_prompt, **kwargs)
+ self._llm_client = kwargs.get("llm_client")
+ self._llm_model: str = kwargs.get("llm_model", "")
+ self._max_entity_tokens: int = kwargs.get("max_entity_tokens", 300)
+ self._entities: dict[str, str] = {}
+ self._entities_file: str = self._derive_entities_file()
+
+ def _derive_entities_file(self) -> str:
+ if not self._session_file:
+ return ""
+ base, _ = os.path.splitext(self._session_file)
+ return f"{base}_entities.json"
+
+ def load(self) -> None:
+ super().load()
+ if self._entities_file and os.path.isfile(self._entities_file):
+ try:
+ with open(self._entities_file) as f:
+ self._entities = json.load(f)
+ except (json.JSONDecodeError, OSError):
+ pass
+
+ def _extract_entities(self, text: str) -> dict[str, str] | None:
+ if not text.strip():
+ return None
+ try:
+ response = self._llm_client.chat.completions.create(
+ model=self._llm_model,
+ messages=[
+ {"role": "system", "content": _EXTRACT_SYSTEM},
+ {"role": "user", "content": text},
+ ],
+ max_tokens=self._max_entity_tokens,
+ )
+ raw = response.choices[0].message.content
+ return json.loads(raw)
+ except Exception:
+ return None
+
+ def add_messages(self, messages: list[dict]) -> None:
+ super().add_messages(messages)
+ if not self._llm_client:
+ return
+ text = format_messages_for_summary(messages)
+ extracted = self._extract_entities(text)
+ if extracted:
+ self._entities.update(extracted)
+
+ def get_messages(self, new_user_message: str) -> list[dict]:
+ result = super().get_messages(new_user_message)
+ if not self._entities:
+ return result
+ lines = [f"{name}: {summary}" for name, summary in sorted(self._entities.items())]
+ entity_msg = {"role": "system", "content": "[Known entities]\n" + "\n".join(lines)}
+ result.insert(1, entity_msg)
+ return result
+
+ def save(self) -> None:
+ super().save()
+ if self._entities_file and self._entities:
+ os.makedirs(os.path.dirname(self._entities_file), exist_ok=True)
+ with open(self._entities_file, "w") as f:
+ json.dump(self._entities, f, ensure_ascii=False)
diff --git a/cosim_agent/memory/episodic.py b/cosim_agent/memory/episodic.py
new file mode 100644
index 0000000..51c60d9
--- /dev/null
+++ b/cosim_agent/memory/episodic.py
@@ -0,0 +1,109 @@
+"""EpisodicMemory — FIFO window with periodic LLM reflections."""
+
+from __future__ import annotations
+
+import json
+import os
+
+from cosim_agent.memory.fifo import FIFOMemory
+from cosim_agent.memory.summary import format_messages_for_summary
+
+_REFLECT_SYSTEM = (
+ "Generate a high-level reflection about the conversation so far. "
+ "Identify key themes, patterns, unresolved questions, and important decisions. "
+ "Be concise — one paragraph."
+)
+
+
+class EpisodicMemory(FIFOMemory):
+ """FIFO window with periodic LLM-generated reflections.
+
+ Every ``reflection_interval`` turns, generates a high-level reflection
+ via an LLM call. Reflections are injected as a system message after the
+ main system prompt.
+
+ Config keys (in addition to FIFOMemory keys):
+ llm_client: OpenAI — client instance for reflection calls
+ llm_model: str — model ID for reflection calls
+ reflection_interval: int — turns between reflections (default 10)
+ max_reflection_tokens: int — max_tokens for reflection (default 300)
+ max_reflections: int — max stored reflections (default 5)
+ """
+
+ def __init__(self, session_file: str, system_prompt: str, **kwargs):
+ super().__init__(session_file, system_prompt, **kwargs)
+ self._llm_client = kwargs.get("llm_client")
+ self._llm_model: str = kwargs.get("llm_model", "")
+ self._reflection_interval: int = kwargs.get("reflection_interval", 10)
+ self._max_reflection_tokens: int = kwargs.get("max_reflection_tokens", 300)
+ self._max_reflections: int = kwargs.get("max_reflections", 5)
+ self._reflections: list[dict] = []
+ self._reflections_file: str = self._derive_reflections_file()
+
+ def _derive_reflections_file(self) -> str:
+ if not self._session_file:
+ return ""
+ base, _ = os.path.splitext(self._session_file)
+ return f"{base}_reflections.json"
+
+ def load(self) -> None:
+ super().load()
+ if self._reflections_file and os.path.isfile(self._reflections_file):
+ try:
+ with open(self._reflections_file) as f:
+ self._reflections = json.load(f)
+ except (json.JSONDecodeError, OSError):
+ pass
+
+ def _generate_reflection(self) -> str | None:
+ text = format_messages_for_summary(self._history[-20:])
+ if not text.strip():
+ return None
+
+ prior = ""
+ if self._reflections:
+ prior = "\n".join(f"- {r['content']}" for r in self._reflections)
+
+ user_content = f"Conversation summary so far:\n{text}"
+ if prior:
+ user_content += f"\n\nExisting reflections:\n{prior}"
+ user_content += "\n\nGenerate a new reflection:"
+
+ try:
+ response = self._llm_client.chat.completions.create(
+ model=self._llm_model,
+ messages=[
+ {"role": "system", "content": _REFLECT_SYSTEM},
+ {"role": "user", "content": user_content},
+ ],
+ max_tokens=self._max_reflection_tokens,
+ )
+ return response.choices[0].message.content
+ except Exception:
+ return None
+
+ def add_messages(self, messages: list[dict]) -> None:
+ super().add_messages(messages)
+ if not self._llm_client:
+ return
+ if self._turn_counter > 0 and self._turn_counter % self._reflection_interval == 0:
+ content = self._generate_reflection()
+ if content:
+ self._reflections.append({"turn": self._turn_counter, "content": content})
+ self._reflections = self._reflections[-self._max_reflections :]
+
+ def get_messages(self, new_user_message: str) -> list[dict]:
+ result = super().get_messages(new_user_message)
+ if not self._reflections:
+ return result
+ lines = [f"- {r['content']}" for r in self._reflections]
+ reflect_msg = {"role": "system", "content": "[Reflections on conversation]\n" + "\n".join(lines)}
+ result.insert(1, reflect_msg)
+ return result
+
+ def save(self) -> None:
+ super().save()
+ if self._reflections_file and self._reflections:
+ os.makedirs(os.path.dirname(self._reflections_file), exist_ok=True)
+ with open(self._reflections_file, "w") as f:
+ json.dump(self._reflections, f, ensure_ascii=False)
diff --git a/cosim_agent/memory/fifo.py b/cosim_agent/memory/fifo.py
new file mode 100644
index 0000000..8b375fd
--- /dev/null
+++ b/cosim_agent/memory/fifo.py
@@ -0,0 +1,218 @@
+"""FIFOMemory — sliding window of the last N messages."""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+
+from cosim_agent.memory.base import ConversationMemory
+
+
+class FIFOMemory(ConversationMemory):
+ """Pinned system prompt + sliding window of the last N messages.
+
+ Full history (including tool calls/results and _meta) is saved to disk
+ as JSONL. Only a filtered subset of the most recent messages is sent
+ to the API.
+
+ Config keys (via kwargs):
+ max_messages: int — window size (default 50)
+ pin_patterns: list[str] — substring/regex patterns; matching messages
+ are pinned and survive beyond the FIFO window.
+ Only applies to standalone text messages — tool traffic
+ (tool results and assistant tool-call messages) is never pinned.
+ clear_tool_results: bool — if true, include tool messages in context
+ but scrub old pairs (default false: strip all tool messages)
+ clear_tool_results_after: int — turn threshold for clearing old pairs
+ (default 3)
+ """
+
+ def __init__(self, session_file: str, system_prompt: str, **kwargs):
+ super().__init__(session_file, system_prompt, **kwargs)
+ self._max_messages: int = kwargs.get("max_messages", 50)
+ self._pin_patterns: list[str] = kwargs.get("pin_patterns") or []
+ self._clear_tool_results: bool = kwargs.get("clear_tool_results", False)
+ self._clear_tool_results_after: int = kwargs.get("clear_tool_results_after", 3)
+ self._history: list[dict] = []
+ self._compiled_pins: list[re.Pattern] = [re.compile(p) for p in self._pin_patterns]
+
+ def load(self) -> None:
+ if not self._session_file or not os.path.isfile(self._session_file):
+ return
+ with open(self._session_file) as f:
+ for line in f:
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ self._history.append(json.loads(line))
+ except json.JSONDecodeError:
+ continue
+ if self._history:
+ last_turn = max(m.get("_meta", {}).get("turn", 0) for m in self._history)
+ self._turn_counter = last_turn
+
+ def _is_pinned(self, msg: dict) -> bool:
+ """Check if a message should be pinned.
+
+ Tool traffic (tool results and assistant+tool_calls) is never pinned
+ to avoid splitting tool-call groups.
+ """
+ role = msg.get("role", "")
+ if role == "tool":
+ return False
+ if role == "assistant" and "tool_calls" in msg:
+ return False
+ if msg.get("_meta", {}).get("pinned"):
+ return True
+ content = msg.get("content", "")
+ if not content or not self._compiled_pins:
+ return False
+ return any(p.search(content) for p in self._compiled_pins)
+
+ def _strip_tool_traffic(self, messages: list[dict]) -> list[dict]:
+ """Remove all tool messages and orphaned tool_calls (default mode)."""
+ filtered = []
+ for msg in messages:
+ role = msg.get("role", "")
+ if role == "tool":
+ continue
+ if role == "assistant" and "tool_calls" in msg:
+ if not msg.get("content"):
+ continue
+ msg = {k: v for k, v in msg.items() if k != "tool_calls"}
+ filtered.append(msg)
+ return filtered
+
+ def _clear_old_tool_pairs(self, messages: list[dict]) -> list[dict]:
+ """Keep all messages but scrub tool-call/result pairs older than threshold."""
+ current_turn = self._turn_counter
+ threshold = current_turn - self._clear_tool_results_after
+ result = []
+ for msg in messages:
+ role = msg.get("role", "")
+ turn = msg.get("_meta", {}).get("turn", 0)
+
+ if role == "tool":
+ if turn <= threshold:
+ continue
+ result.append(msg)
+ elif role == "assistant" and "tool_calls" in msg:
+ if turn <= threshold:
+ if msg.get("content"):
+ result.append({k: v for k, v in msg.items() if k != "tool_calls"})
+ continue
+ result.append(msg)
+ else:
+ result.append(msg)
+ return result
+
+ @staticmethod
+ def _group_into_units(messages: list[dict]) -> list[list[dict]]:
+ """Group messages into atomic units for window slicing.
+
+ An assistant message with tool_calls plus its consecutive tool results
+ forms one unit. Everything else is a single-message unit. This ensures
+ tool-call groups are never split by the FIFO window boundary.
+ """
+ units: list[list[dict]] = []
+ i = 0
+ while i < len(messages):
+ msg = messages[i]
+ if msg.get("role") == "assistant" and "tool_calls" in msg:
+ group = [msg]
+ call_ids = {tc.get("id", "") for tc in msg.get("tool_calls", []) if tc.get("id")}
+ j = i + 1
+ while j < len(messages):
+ next_msg = messages[j]
+ if next_msg.get("role") == "tool" and next_msg.get("tool_call_id", "") in call_ids:
+ group.append(next_msg)
+ j += 1
+ else:
+ break
+ units.append(group)
+ i = j
+ else:
+ units.append([msg])
+ i += 1
+ return units
+
+ @staticmethod
+ def _take_trailing_units(units: list[list[dict]], max_messages: int) -> list[list[dict]]:
+ """Take trailing units totaling at most max_messages individual messages.
+
+ Always includes at least the last unit even if it exceeds max_messages
+ on its own.
+ """
+ if not units:
+ return []
+ result: list[list[dict]] = []
+ count = 0
+ for unit in reversed(units):
+ unit_size = len(unit)
+ if result and count + unit_size > max_messages:
+ break
+ result.append(unit)
+ count += unit_size
+ result.reverse()
+ return result
+
+ def get_messages(self, new_user_message: str) -> list[dict]:
+ if self._clear_tool_results:
+ eligible = self._clear_old_tool_pairs(self._history)
+ else:
+ eligible = self._strip_tool_traffic(self._history)
+
+ units = self._group_into_units(eligible)
+
+ if self._compiled_pins:
+ pinned_idxs: set[int] = set()
+ pinned_units: list[list[dict]] = []
+ for i, unit in enumerate(units):
+ if any(self._is_pinned(msg) for msg in unit):
+ pinned_units.append(unit)
+ pinned_idxs.add(i)
+
+ window_candidates = [u for i, u in enumerate(units) if i not in pinned_idxs]
+ window_units = self._take_trailing_units(window_candidates, self._max_messages)
+
+ window_msg_ids = {id(msg) for unit in window_units for msg in unit}
+ unique_pinned = [u for u in pinned_units if not all(id(msg) in window_msg_ids for msg in u)]
+
+ pinned_msgs = [msg for unit in unique_pinned for msg in unit]
+ window_msgs = [msg for unit in window_units for msg in unit]
+
+ assembled = [
+ {"role": "system", "content": self._system_prompt},
+ *pinned_msgs,
+ *window_msgs,
+ {"role": "user", "content": new_user_message},
+ ]
+ else:
+ window_units = self._take_trailing_units(units, self._max_messages)
+ window_msgs = [msg for unit in window_units for msg in unit]
+
+ assembled = [
+ {"role": "system", "content": self._system_prompt},
+ *window_msgs,
+ {"role": "user", "content": new_user_message},
+ ]
+
+ return self._normalize_for_api(assembled)
+
+ def add_messages(self, messages: list[dict]) -> None:
+ self._turn_counter += 1
+ for msg in messages:
+ self._add_meta(msg)
+ if self._is_pinned(msg):
+ msg["_meta"]["pinned"] = True
+ self._history.append(msg)
+
+ def save(self) -> None:
+ if not self._session_file:
+ return
+ os.makedirs(os.path.dirname(self._session_file), exist_ok=True)
+ with open(self._session_file, "w") as f:
+ for msg in self._history:
+ f.write(json.dumps(msg, ensure_ascii=False) + "\n")
diff --git a/cosim_agent/memory/none.py b/cosim_agent/memory/none.py
new file mode 100644
index 0000000..4b89eb5
--- /dev/null
+++ b/cosim_agent/memory/none.py
@@ -0,0 +1,24 @@
+"""NoMemory — stateless pass-through (each turn starts fresh)."""
+
+from cosim_agent.memory.base import ConversationMemory
+
+
+class NoMemory(ConversationMemory):
+ """Stateless pass-through — each turn starts fresh."""
+
+ def load(self) -> None:
+ pass
+
+ def get_messages(self, new_user_message: str) -> list[dict]:
+ return self._normalize_for_api(
+ [
+ {"role": "system", "content": self._system_prompt},
+ {"role": "user", "content": new_user_message},
+ ]
+ )
+
+ def add_messages(self, messages: list[dict]) -> None:
+ pass
+
+ def save(self) -> None:
+ pass
diff --git a/cosim_agent/memory/reflexion.py b/cosim_agent/memory/reflexion.py
new file mode 100644
index 0000000..e4c5245
--- /dev/null
+++ b/cosim_agent/memory/reflexion.py
@@ -0,0 +1,96 @@
+"""ReflexionMemory — per-turn LLM self-critique."""
+
+from __future__ import annotations
+
+import json
+import os
+
+from cosim_agent.memory.fifo import FIFOMemory
+from cosim_agent.memory.summary import format_messages_for_summary
+
+_CRITIQUE_SYSTEM = (
+ "You are a self-evaluation assistant. Critique the agent's last response. "
+ "Was it helpful? Did it miss anything? Was the tool usage appropriate? "
+ "Be specific and concise — 2-3 sentences."
+)
+
+
+class ReflexionMemory(FIFOMemory):
+ """FIFO window with per-turn LLM self-critique.
+
+ After each turn, generates a self-critique via an LLM call. The last
+ ``max_reflections`` critiques are injected as a system message after
+ the main system prompt.
+
+ Config keys (in addition to FIFOMemory keys):
+ llm_client: OpenAI — client instance for critique calls
+ llm_model: str — model ID for critique calls
+ max_reflections: int — how many past critiques to keep (default 3)
+ max_critique_tokens: int — max_tokens for critique (default 200)
+ """
+
+ def __init__(self, session_file: str, system_prompt: str, **kwargs):
+ super().__init__(session_file, system_prompt, **kwargs)
+ self._llm_client = kwargs.get("llm_client")
+ self._llm_model: str = kwargs.get("llm_model", "")
+ self._max_reflections: int = kwargs.get("max_reflections", 3)
+ self._max_critique_tokens: int = kwargs.get("max_critique_tokens", 200)
+ self._critiques: list[dict] = []
+ self._critiques_file: str = self._derive_critiques_file()
+
+ def _derive_critiques_file(self) -> str:
+ if not self._session_file:
+ return ""
+ base, _ = os.path.splitext(self._session_file)
+ return f"{base}_critiques.json"
+
+ def load(self) -> None:
+ super().load()
+ if self._critiques_file and os.path.isfile(self._critiques_file):
+ try:
+ with open(self._critiques_file) as f:
+ self._critiques = json.load(f)
+ except (json.JSONDecodeError, OSError):
+ pass
+
+ def _generate_critique(self, messages: list[dict]) -> str | None:
+ text = format_messages_for_summary(messages)
+ if not text.strip():
+ return None
+ try:
+ response = self._llm_client.chat.completions.create(
+ model=self._llm_model,
+ messages=[
+ {"role": "system", "content": _CRITIQUE_SYSTEM},
+ {"role": "user", "content": text},
+ ],
+ max_tokens=self._max_critique_tokens,
+ )
+ return response.choices[0].message.content
+ except Exception:
+ return None
+
+ def add_messages(self, messages: list[dict]) -> None:
+ super().add_messages(messages)
+ if not self._llm_client:
+ return
+ content = self._generate_critique(messages)
+ if content:
+ self._critiques.append({"turn": self._turn_counter, "content": content})
+ self._critiques = self._critiques[-self._max_reflections :]
+
+ def get_messages(self, new_user_message: str) -> list[dict]:
+ result = super().get_messages(new_user_message)
+ if not self._critiques:
+ return result
+ lines = [f"- Turn {c['turn']}: {c['content']}" for c in self._critiques]
+ critique_msg = {"role": "system", "content": "[Self-critique from previous turns]\n" + "\n".join(lines)}
+ result.insert(1, critique_msg)
+ return result
+
+ def save(self) -> None:
+ super().save()
+ if self._critiques_file and self._critiques:
+ os.makedirs(os.path.dirname(self._critiques_file), exist_ok=True)
+ with open(self._critiques_file, "w") as f:
+ json.dump(self._critiques, f, ensure_ascii=False)
diff --git a/cosim_agent/memory/summary.py b/cosim_agent/memory/summary.py
new file mode 100644
index 0000000..7ed8e24
--- /dev/null
+++ b/cosim_agent/memory/summary.py
@@ -0,0 +1,192 @@
+"""SummaryMemory — LLM-generated running summary of conversation history."""
+
+from __future__ import annotations
+
+import json
+import os
+
+from cosim_agent.memory.base import ConversationMemory
+
+_SUMMARIZE_SYSTEM = (
+ "Progressively summarize the lines of conversation provided, "
+ "adding onto the previous summary returning a new summary."
+)
+
+_FALLBACK_WINDOW = 10
+
+
+def format_messages_for_summary(messages: list[dict]) -> str:
+ """Convert message dicts to readable text for summarization.
+
+ Includes tool results (truncated) and tool-call names so that
+ tool-heavy conversations retain recall after eviction.
+ """
+ lines = []
+ for msg in messages:
+ role = msg.get("role", "unknown")
+ content = msg.get("content", "")
+
+ if role == "tool":
+ if not content:
+ continue
+ truncated = content[:500] if len(content) > 500 else content
+ lines.append(f"[tool result] {truncated}")
+ continue
+
+ if role == "assistant" and "tool_calls" in msg:
+ tool_names = []
+ for tc in msg.get("tool_calls", []):
+ fn = tc.get("function", {})
+ if isinstance(fn, dict):
+ tool_names.append(fn.get("name", "?"))
+ call_info = f" [called: {', '.join(tool_names)}]" if tool_names else ""
+ if content:
+ lines.append(f"assistant: {content}{call_info}")
+ elif tool_names:
+ lines.append(f"assistant:{call_info}")
+ continue
+
+ if not content:
+ continue
+ lines.append(f"{role}: {content}")
+ return "\n".join(lines)
+
+
+def call_summarize(
+ client,
+ model: str,
+ messages_text: str,
+ existing_summary: str,
+ max_tokens: int,
+) -> str | None:
+ """Call the LLM to generate or update a summary.
+
+ Returns the summary string on success, None on any failure.
+ """
+ if not messages_text.strip():
+ return existing_summary or None
+
+ if existing_summary:
+ user_content = (
+ f"Current summary:\n{existing_summary}\n\nNew lines of conversation:\n{messages_text}\n\nNew summary:"
+ )
+ else:
+ user_content = f"Summarize:\n\n{messages_text}"
+
+ try:
+ response = client.chat.completions.create(
+ model=model,
+ messages=[
+ {"role": "system", "content": _SUMMARIZE_SYSTEM},
+ {"role": "user", "content": user_content},
+ ],
+ max_tokens=max_tokens,
+ )
+ return response.choices[0].message.content
+ except Exception:
+ return None
+
+
+class SummaryMemory(ConversationMemory):
+ """Full-history summarization via LLM.
+
+ After each turn, calls the LLM to update a running summary. The API
+ context contains only [system, summary, user] — no raw history.
+
+ Raw JSONL history is preserved on disk as the source of truth.
+ The summary is stored alongside it as a separate JSON file.
+
+ Config keys (via kwargs):
+ llm_client: OpenAI — client instance for summarization calls
+ llm_model: str — model ID for summarization calls
+ max_summary_tokens: int — max_tokens for summarization (default 500)
+ """
+
+ def __init__(self, session_file: str, system_prompt: str, **kwargs):
+ super().__init__(session_file, system_prompt, **kwargs)
+ self._llm_client = kwargs.get("llm_client")
+ self._llm_model: str = kwargs.get("llm_model", "")
+ self._max_summary_tokens: int = kwargs.get("max_summary_tokens", 500)
+ self._history: list[dict] = []
+ self._summary: str = ""
+ self._summary_file: str = self._derive_summary_file()
+
+ def _derive_summary_file(self) -> str:
+ if not self._session_file:
+ return ""
+ base, _ = os.path.splitext(self._session_file)
+ return f"{base}_summary.json"
+
+ def load(self) -> None:
+ if self._session_file and os.path.isfile(self._session_file):
+ with open(self._session_file) as f:
+ for line in f:
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ self._history.append(json.loads(line))
+ except json.JSONDecodeError:
+ continue
+ if self._history:
+ self._turn_counter = max(m.get("_meta", {}).get("turn", 0) for m in self._history)
+
+ if self._summary_file and os.path.isfile(self._summary_file):
+ try:
+ with open(self._summary_file) as f:
+ data = json.load(f)
+ self._summary = data.get("summary", "")
+ except (json.JSONDecodeError, OSError):
+ pass
+
+ def get_messages(self, new_user_message: str) -> list[dict]:
+ assembled: list[dict] = [{"role": "system", "content": self._system_prompt}]
+
+ if self._summary:
+ assembled.append(
+ {
+ "role": "assistant",
+ "content": f"[Summary of our conversation so far]\n{self._summary}",
+ }
+ )
+ elif self._history:
+ text_msgs = [
+ m
+ for m in self._history
+ if m.get("role") in ("user", "assistant") and m.get("content") and "tool_calls" not in m
+ ]
+ for msg in text_msgs[-_FALLBACK_WINDOW:]:
+ assembled.append({"role": msg["role"], "content": msg["content"]})
+
+ assembled.append({"role": "user", "content": new_user_message})
+ return self._normalize_for_api(assembled)
+
+ def add_messages(self, messages: list[dict]) -> None:
+ self._turn_counter += 1
+ for msg in messages:
+ self._add_meta(msg)
+ self._history.append(msg)
+
+ if self._llm_client:
+ text = format_messages_for_summary(messages)
+ result = call_summarize(
+ self._llm_client,
+ self._llm_model,
+ text,
+ self._summary,
+ self._max_summary_tokens,
+ )
+ if result is not None:
+ self._summary = result
+
+ def save(self) -> None:
+ if not self._session_file:
+ return
+ os.makedirs(os.path.dirname(self._session_file), exist_ok=True)
+ with open(self._session_file, "w") as f:
+ for msg in self._history:
+ f.write(json.dumps(msg, ensure_ascii=False) + "\n")
+
+ if self._summary_file:
+ with open(self._summary_file, "w") as f:
+ json.dump({"summary": self._summary}, f, ensure_ascii=False)
diff --git a/cosim_agent/memory/summary_buffer.py b/cosim_agent/memory/summary_buffer.py
new file mode 100644
index 0000000..0b9b6c2
--- /dev/null
+++ b/cosim_agent/memory/summary_buffer.py
@@ -0,0 +1,167 @@
+"""SummaryBufferMemory — FIFO window + LLM summary for evicted messages."""
+
+from __future__ import annotations
+
+import json
+import os
+
+from cosim_agent.memory.fifo import FIFOMemory
+from cosim_agent.memory.summary import call_summarize, format_messages_for_summary
+
+
+class SummaryBufferMemory(FIFOMemory):
+ """FIFO window for recent messages, LLM summary for evicted ones.
+
+ Inherits pinning, tool-clearing, and atomic tool-group windowing from
+ FIFOMemory. When the filtered message count exceeds max_messages, evicted
+ messages are incrementally summarized via an LLM call.
+
+ Output structure:
+ [system, ...pinned, summary_msg, ...recent_window, user_prompt]
+
+ Config keys (in addition to FIFOMemory keys):
+ llm_client: OpenAI — client instance for summarization calls
+ llm_model: str — model ID for summarization calls
+ max_summary_tokens: int — max_tokens for summarization (default 500)
+ """
+
+ def __init__(self, session_file: str, system_prompt: str, **kwargs):
+ super().__init__(session_file, system_prompt, **kwargs)
+ self._llm_client = kwargs.get("llm_client")
+ self._llm_model: str = kwargs.get("llm_model", "")
+ self._max_summary_tokens: int = kwargs.get("max_summary_tokens", 500)
+ self._summary: str = ""
+ self._summary_file: str = self._derive_summary_file()
+ self._summarized_count: int = 0
+
+ def _derive_summary_file(self) -> str:
+ if not self._session_file:
+ return ""
+ base, _ = os.path.splitext(self._session_file)
+ return f"{base}_summary.json"
+
+ def load(self) -> None:
+ super().load()
+
+ if self._summary_file and os.path.isfile(self._summary_file):
+ try:
+ with open(self._summary_file) as f:
+ data = json.load(f)
+ self._summary = data.get("summary", "")
+ self._summarized_count = data.get("summarized_count", 0)
+ except (json.JSONDecodeError, OSError):
+ pass
+
+ def _get_filtered(self) -> list[dict]:
+ """Return the filtered message list (tool-stripped or tool-cleared)."""
+ if self._clear_tool_results:
+ return self._clear_old_tool_pairs(self._history)
+ return self._strip_tool_traffic(self._history)
+
+ def get_messages(self, new_user_message: str) -> list[dict]:
+ filtered = self._get_filtered()
+ units = self._group_into_units(filtered)
+
+ if self._compiled_pins:
+ pinned_idxs: set[int] = set()
+ pinned_units: list[list[dict]] = []
+ for i, unit in enumerate(units):
+ if any(self._is_pinned(msg) for msg in unit):
+ pinned_units.append(unit)
+ pinned_idxs.add(i)
+
+ window_candidates = [u for i, u in enumerate(units) if i not in pinned_idxs]
+ window_units = self._take_trailing_units(window_candidates, self._max_messages)
+
+ window_msg_ids = {id(msg) for unit in window_units for msg in unit}
+ unique_pinned = [u for u in pinned_units if not all(id(msg) in window_msg_ids for msg in u)]
+
+ pinned_msgs = [msg for unit in unique_pinned for msg in unit]
+ window_msgs = [msg for unit in window_units for msg in unit]
+ else:
+ pinned_msgs = []
+ window_units = self._take_trailing_units(units, self._max_messages)
+ window_msgs = [msg for unit in window_units for msg in unit]
+
+ assembled: list[dict] = [
+ {"role": "system", "content": self._system_prompt},
+ *pinned_msgs,
+ ]
+
+ if self._summary:
+ assembled.append(
+ {
+ "role": "assistant",
+ "content": f"[Summary of earlier conversation]\n{self._summary}",
+ }
+ )
+
+ assembled.extend(window_msgs)
+ assembled.append({"role": "user", "content": new_user_message})
+
+ return self._normalize_for_api(assembled)
+
+ def _compute_evicted_messages(self) -> tuple[list[dict], int]:
+ """Determine which non-pinned messages are evicted from the window.
+
+ Uses the same unit-based selection and pinning logic as get_messages()
+ so the summary covers exactly the messages that are dropped from context.
+
+ Returns (evicted_messages, total_evicted_count).
+ """
+ filtered = self._get_filtered()
+ units = self._group_into_units(filtered)
+
+ if self._compiled_pins:
+ non_pinned_units = [u for u in units if not any(self._is_pinned(msg) for msg in u)]
+ else:
+ non_pinned_units = list(units)
+
+ window_units = self._take_trailing_units(non_pinned_units, self._max_messages)
+ n_window = len(window_units)
+
+ if n_window >= len(non_pinned_units):
+ return [], 0
+
+ evicted_units = non_pinned_units[: len(non_pinned_units) - n_window]
+ evicted_msgs = [msg for unit in evicted_units for msg in unit]
+ return evicted_msgs, len(evicted_msgs)
+
+ def add_messages(self, messages: list[dict]) -> None:
+ super().add_messages(messages)
+
+ if not self._llm_client:
+ return
+
+ evicted_msgs, evicted_count = self._compute_evicted_messages()
+
+ if evicted_count <= self._summarized_count:
+ return
+
+ new_evictions = evicted_msgs[self._summarized_count :]
+ text = format_messages_for_summary(new_evictions)
+ result = call_summarize(
+ self._llm_client,
+ self._llm_model,
+ text,
+ self._summary,
+ self._max_summary_tokens,
+ )
+ if result is not None:
+ self._summary = result
+ self._summarized_count = evicted_count
+
+ def save(self) -> None:
+ super().save()
+
+ if self._summary_file and (self._summary or self._summarized_count):
+ os.makedirs(os.path.dirname(self._summary_file), exist_ok=True)
+ with open(self._summary_file, "w") as f:
+ json.dump(
+ {
+ "summary": self._summary,
+ "summarized_count": self._summarized_count,
+ },
+ f,
+ ensure_ascii=False,
+ )
diff --git a/cosim_agent/pyproject.toml b/cosim_agent/pyproject.toml
new file mode 100644
index 0000000..cdcbb12
--- /dev/null
+++ b/cosim_agent/pyproject.toml
@@ -0,0 +1,12 @@
+[project]
+name = "cosim-agent"
+version = "0.1.0"
+description = "Models.Corp agent harness for the cosim platform"
+requires-python = ">=3.13"
+dependencies = ["openai", "httpx"]
+
+[project.scripts]
+cosim-agent = "cosim_agent.agent:main"
+
+[tool.setuptools.packages.find]
+include = ["cosim_agent*"]
diff --git a/docs/memory-handling-methods-plan-and-testing.md b/docs/memory-handling-methods-plan-and-testing.md
new file mode 100644
index 0000000..693332a
--- /dev/null
+++ b/docs/memory-handling-methods-plan-and-testing.md
@@ -0,0 +1,690 @@
+# Memory Handling Methods — Implementation Plan & Testing
+
+## Current State
+
+Memory lives in `container/conversation_memory.py` with two strategies:
+- `none` (NoMemory) — stateless, each turn starts fresh
+- `fifo` (FIFOMemory) — sliding window of last N messages, persisted as JSONL
+
+The strategy is selected via `--memory-strategy` CLI arg in `modelscorp_agent.py`.
+
+**Current default behavior:**
+- `modelscorp_agent.py` CLI default: `--memory-strategy none` (line 425)
+- `ModelscorpBackend.build_exec_command()` overrides to `fifo` only when `use_sessions=True` AND a `session_id` is provided (line 343-351 in `agent_backends.py`)
+- Claude and Codex backends handle sessions natively (Claude `--resume`, Codex thread resume) — the `conversation_memory.py` module only applies to Models.Corp agents
+
+No per-agent memory config exists in `scenario.yaml` yet.
+
+Key files:
+- `container/conversation_memory.py` — strategy implementations (runs inside container)
+- `container/modelscorp_agent.py` — agent loop that calls `create_memory()`
+- `lib/agent_backends.py` — passes `--memory-strategy` to the container
+- `lib/scenario_loader.py` — loads persona config from scenario.yaml
+- `lib/session.py` — session save/load (must preserve memory config)
+- `lib/container_orchestrator.py` — hire/fire agent paths (must preserve memory config)
+
+---
+
+## Architecture: Composable Base + Mixins
+
+Rather than 15 independent strategies, implement as composable layers:
+
+```
+┌─────────────────────────────────────┐
+│ Token Budget Guard │ ← outer wrapper, triggers compaction
+├─────────────────────────────────────┤
+│ Enrichment Mixins │
+│ ┌───────────┐ │
+│ │ Entity │ │ ← inject extra context (entity summaries,
+│ │ Tracking │ │ reflections) into the selected set
+│ └───────────┘ │
+├─────────────────────────────────────┤
+│ Outbound Normalization │ ← strip _meta, enforce API schema
+├─────────────────────────────────────┤
+│ Base Strategy (one of) — owns │
+│ the full history and selects │
+│ which messages go to the LLM. │
+│ Integrates: │
+│ • pinning (pre-selection) │
+│ • tool clearing (post-selection) │
+│ • decay scoring (selection) │
+│ fifo | summary | summary-buffer │
+│ episodic | rag | reflexion │
+├─────────────────────────────────────┤
+│ Persistence Layer │
+│ JSONL file (current) | SQLite │
+│ (always stores ALL messages — │
+│ including tool calls/results, │
+│ with _meta for timestamps etc.) │
+└─────────────────────────────────────┘
+```
+
+**Important architectural constraints:**
+
+1. **Pinning, tool clearing, and decay scoring are NOT separate filters.** They are
+ integrated into the base strategy's selection logic, because they affect *which*
+ messages survive selection. A filter running after FIFO slicing would never see
+ messages that were already evicted. Pinning and decay affect how the window is
+ chosen; tool clearing transforms the chosen messages before output. See the
+ Phase 1 sections below for specifics.
+
+2. **The persistence layer always stores the full, unfiltered history** — including
+ tool calls and tool results. Current `FIFOMemory.add_messages()` strips tool
+ messages before storing; this must change so that strategies like tool result
+ clearing and episodic memory have access to the raw record. The *selection* step
+ (what goes to the LLM) is where filtering happens, not the *storage* step.
+
+3. **`_meta` must never reach the LLM API.** Stored messages include a `_meta` field
+ for timestamps, pin flags, importance scores, etc. The outbound normalization step
+ strips `_meta` (and any other non-standard fields) from every message before
+ `get_messages()` returns them. This is mandatory — OpenAI-compatible APIs reject
+ unknown fields in chat messages. The normalization is a method on the base class
+ (`ConversationMemory._normalize_for_api(messages)`) so all strategies inherit it.
+
+4. **Tool clearing must preserve valid message ordering.** OpenAI-compatible chat APIs
+ require tool result messages to immediately follow their paired assistant tool_calls
+ message. Clearing must always drop or keep tool-call/result pairs together as a unit
+ — never drop one and keep the other. See Phase 1d for the exact rules.
+
+### Config surface (scenario.yaml)
+
+```yaml
+characters:
+ rocky:
+ # ... existing fields ...
+ memory:
+ strategy: "summary-buffer" # base strategy
+ max_messages: 50 # FIFO/buffer window size
+ max_summary_tokens: 500 # summary budget
+ pin_patterns: ["Scenario Director"] # never evict messages matching these senders
+ clear_tool_results: true # strip old tool call/result pairs
+ decay_halflife_hours: 4.0 # forgetting curve halflife
+ entity_tracking: false # extract and track entities
+```
+
+### Default behavior rules
+
+There are two distinct defaults:
+
+1. **Factory default** (no config at all): `none` (NoMemory). A Models.Corp agent
+ invoked without `--memory-config` or `--memory-strategy` is stateless. This
+ preserves backward compatibility and is the correct behavior for one-shot or
+ test invocations.
+
+2. **Orchestrator default** (sessions enabled, no per-agent memory config in
+ scenario.yaml): `{"strategy": "fifo", "max_messages": 50}`. When `use_sessions=True`
+ and a `session_id` is assigned, `ModelscorpBackend` injects this default config
+ so that agents get conversational continuity without requiring explicit config.
+
+3. **Explicit per-agent config** (scenario.yaml `memory:` block): overrides both
+ defaults. The orchestrator passes the config verbatim; the factory constructs
+ whatever is specified.
+
+The rule: **explicit config > orchestrator session default > factory stateless default.**
+
+### Wiring changes
+
+1. `scenario_loader.py` — load `memory` dict from character config, store in persona dict
+2. `lib/session.py` — include `memory` in roster save (`_get_roster()` line 108-119)
+ and restore (`load_session()` line 326-334). Both currently enumerate a fixed set
+ of persona fields; `memory`, `allowed_tools`, and `fallback_channel` must be added.
+3. `lib/container_orchestrator.py` — include `memory` in the persona dict constructed
+ during `add_agent` (hire) at line 852-859. Currently copies `name`, `display_name`,
+ `team_description`, `character_file`, `agent_type`, `model` — must also copy
+ `memory`, `allowed_tools`, `fallback_channel`.
+4. `agent_backends.py` — the `ModelscorpBackend` needs access to per-agent memory
+ config, but `build_exec_command()` currently has no `memory_config` parameter
+ (and neither does the `AgentBackend` protocol). Two options:
+ - **Option A: `set_memory_config(persona_key, config)` method** — mirrors the
+ existing `set_allowed_tools()` pattern. Called during pool setup and hire flows.
+ `build_exec_command()` reads from `self._memory_configs[persona_key]`.
+ - **Option B: add `memory_config: dict` param to `build_exec_command()`** — passed
+ directly from the orchestrator, which reads it from the persona dict.
+ Option A is preferred because it matches the existing `set_allowed_tools()` pattern
+ and avoids changing the protocol signature (Claude/Codex backends ignore it).
+ The backend serializes the config as `--memory-config '{...}'` JSON on the command
+ line. When `use_sessions=True` and no explicit config is set, it injects the
+ orchestrator default (`fifo`/50). The orchestrator call site
+ (`container_orchestrator.py` line 632) needs to call `set_memory_config()` during
+ pool setup alongside the existing `set_allowed_tools()` call.
+5. `modelscorp_agent.py` — accept `--memory-config` JSON, pass to `create_memory()`.
+ Keep `--memory-strategy` and `--memory-max-messages` as deprecated fallbacks that
+ convert to config dict internally.
+6. `conversation_memory.py` — factory `create_memory()` accepts a config dict. New
+ signature: `create_memory(config: dict, session_file: str, system_prompt: str,
+ llm_client=None, llm_model: str = "") -> ConversationMemory`. The `llm_client`
+ and `llm_model` params are only required for strategies that need LLM calls
+ (summary, entity, episodic, reflexion). Passed from `modelscorp_agent.py`'s
+ existing `OpenAI` client instance and model ID — no new client construction needed.
+
+---
+
+## Implementation Phases
+
+### Phase 0: Extract agent harness into an installable package
+
+Currently `modelscorp_agent.py` and `conversation_memory.py` live in `container/`
+and are COPYed as loose files into the agent container image. This is fragile:
+- No way to import them from host-side code (tests, utilities)
+- No dependency management — `openai` and `httpx` are pip-installed separately
+ in the Dockerfile
+- Adding new modules (memory strategies, entity extractors) means adding more
+ COPY lines and ensuring the import graph works inside the container
+- Can't run tests against them without path hacks
+
+**Extract into `cosim_agent/` package at the project root:**
+
+```
+cosim_agent/
+ __init__.py
+ agent.py ← current modelscorp_agent.py (the agent loop + CLI)
+ memory/
+ __init__.py ← create_memory() factory, ConversationMemory base class
+ fifo.py ← FIFOMemory
+ none.py ← NoMemory
+ summary.py ← (Phase 1e) SummaryMemory
+ summary_buffer.py ← (Phase 1f) SummaryBufferMemory
+ ... ← future strategies get their own modules
+ mcp_client.py ← MCPClient class (extracted from agent.py)
+```
+
+**Package configuration** — add a second `[project]` section or make it a
+sub-package of the existing project. Simplest approach: add `cosim_agent` to
+`pyproject.toml`'s `[tool.setuptools.packages.find]`:
+
+```toml
+[tool.setuptools.packages.find]
+include = ["lib*", "cosim_agent*"]
+```
+
+The package's dependencies (`openai`, `httpx`) are already in the top-level
+`pyproject.toml` deps. No separate `pyproject.toml` needed.
+
+**Dockerfile changes:**
+
+```dockerfile
+# Before (loose file copies):
+COPY modelscorp_agent.py /home/agent/modelscorp_agent.py
+COPY conversation_memory.py /home/agent/conversation_memory.py
+
+# After (pip install from project root):
+COPY cosim_agent/ /tmp/cosim_agent/
+COPY pyproject.toml /tmp/pyproject.toml
+RUN pip install --no-cache-dir /tmp/ && rm -rf /tmp/cosim_agent /tmp/pyproject.toml
+```
+
+Alternatively, to avoid copying the full project into the build context, create a
+minimal `cosim_agent/pyproject.toml` that only declares the agent package:
+
+```toml
+[project]
+name = "cosim-agent"
+version = "0.1.0"
+dependencies = ["openai", "httpx"]
+
+[tool.setuptools.packages.find]
+include = ["cosim_agent*"]
+```
+
+Then the Dockerfile becomes:
+```dockerfile
+COPY cosim_agent/ /tmp/cosim_agent/cosim_agent/
+COPY cosim_agent/pyproject.toml /tmp/cosim_agent/pyproject.toml
+RUN pip install --no-cache-dir /tmp/cosim_agent && rm -rf /tmp/cosim_agent
+```
+
+**Entry point** — add a console script so the agent can be invoked as
+`cosim-agent` instead of `python /home/agent/modelscorp_agent.py`:
+
+```toml
+[project.scripts]
+cosim-agent = "cosim_agent.agent:main"
+```
+
+**Backend command change** — `ModelscorpBackend.build_exec_command()` changes from:
+```python
+cmd = ["podman", "exec", container_name, "python", "/home/agent/modelscorp_agent.py", ...]
+```
+to:
+```python
+cmd = ["podman", "exec", container_name, "cosim-agent", ...]
+```
+
+**Import path changes:**
+- `from conversation_memory import create_memory` → `from cosim_agent.memory import create_memory`
+- Internal imports within the package use relative imports
+
+**Makefile `build-agent` target** — the build context must include `cosim_agent/`
+and its `pyproject.toml`. Either change the build context to the project root:
+```makefile
+build-agent:
+ podman build -f container/Dockerfile.agent -t agent-image:latest .
+```
+Or use a multi-context build / copy the package into `container/` as a build step.
+
+**Testing benefit** — once `cosim_agent` is a proper package, host-side tests can
+simply `import cosim_agent.memory` and test strategies directly without container
+builds. The `tests/test_conversation_memory.py` tests all run on the host.
+
+**Lint** — add `cosim_agent/` to the ruff targets in the Makefile:
+```makefile
+lint:
+ ruff check lib/ cosim_agent/ tests/ main.py
+ ruff format --check lib/ cosim_agent/ tests/ main.py
+```
+
+### Phase 1: Foundation (composable architecture + 3 base strategies)
+
+**1a. Refactor config plumbing**
+- Add `memory` dict to scenario.yaml character schema
+- Load through `scenario_loader.py` into persona dict
+- Pass as `--memory-config '{...}'` JSON blob instead of individual flags
+- Backward compat: if `--memory-strategy` is passed (old style), convert to config dict
+
+**1b. Persistence layer: store everything + outbound normalization**
+- Change `FIFOMemory.add_messages()` to store ALL messages including tool calls and
+ tool results. Currently it strips them (lines 96-103 of `conversation_memory.py`).
+ The raw JSONL becomes the source of truth for the full conversation.
+- **Persist the user turn prompt.** Currently `modelscorp_agent.py` sets
+ `turn_start_idx = len(messages)` after `memory.get_messages(prompt)` at line 246,
+ then only saves `messages[turn_start_idx:]` at line 395. This excludes the user
+ prompt message that `get_messages()` appended. Fix: either save
+ `messages[turn_start_idx - 1:]` (to include the user message), or better, add a
+ `memory.add_user_message(prompt)` call before the agent loop that explicitly
+ persists the user turn. This ensures the JSONL contains the complete conversation
+ (user prompts + assistant responses + tool interactions), not just the model's
+ output.
+- The `get_messages()` method (selection step) is where filtering happens — each
+ strategy decides what to send to the LLM. Current FIFO behavior (stripping tool
+ messages from API context) moves from `add_messages()` to `get_messages()`.
+- Add a `_meta` field to stored messages for timestamps, importance scores, pin flags,
+ and turn numbers. Stored in JSONL alongside the message:
+ `{"role": "...", "content": "...", "_meta": {"turn": 3, "ts": 1716000000, "pinned": false}}`
+- Old session files without `_meta` load fine — missing meta treated as defaults.
+- **Outbound normalization (mandatory).** Add `_normalize_for_api(messages)` to the
+ `ConversationMemory` base class. Called as the final step of every `get_messages()`
+ implementation. Strips `_meta` and any other non-standard fields from each message
+ dict, returning only fields valid for the OpenAI chat completions API (`role`,
+ `content`, `tool_calls`, `tool_call_id`, `name`). This prevents API rejections
+ from backends that validate message schema strictly.
+- `modelscorp_agent.py` currently passes `messages` directly to
+ `client.chat.completions.create()` at line 257. After this change, the messages
+ returned by `get_messages()` are already normalized — no change needed in the
+ agent loop.
+
+**1c. Pinned messages**
+- NOT a post-selection filter. Pinning is part of the base strategy's selection logic.
+- When `pin_patterns` is configured, `add_messages()` marks matching messages with
+ `_meta.pinned = true` at storage time.
+- **Match criteria — content-based only.** Current stored messages have only `role`
+ and `content` fields (see `conversation_memory.py` line 86). There is no `sender`
+ or `source` field — sender names only appear embedded in message content (e.g.,
+ the turn prompt includes "- Human (Scenario Director): ..."). Therefore pinning
+ matches against `content` via substring or regex, not against a structured sender
+ field. If a structured `_meta.source` field is added later (Phase 1b could include
+ this), pinning can additionally match on it, but content matching is the v1
+ mechanism.
+- Config example: `pin_patterns: ["Scenario Director", "CRITICAL"]` — any message
+ whose content contains either substring is pinned.
+- In `get_messages()`, the strategy collects pinned messages FIRST (from the full
+ history), then fills the remaining budget with the normal selection (FIFO tail,
+ summary, etc.). Pinned messages are inserted in chronological order after the
+ system prompt and before the recent window.
+- Output: `[system, ...pinned, ...recent_window, user_prompt]`
+- Pinned messages count against the token budget (if a budget guard is active).
+
+**1d. Tool result clearing**
+- Applied during `get_messages()` as a post-selection transformation — it modifies
+ the selected messages, not the stored history.
+- Requires the persistence layer to store tool messages (Phase 1b).
+- **Interaction with FIFO tool stripping:** By default, FIFO's `get_messages()` strips
+ all tool messages from the API context (the behavior moved from `add_messages()` in
+ Phase 1b). When `clear_tool_results: true` is configured, this changes: FIFO
+ *includes* tool messages in the selected window instead of stripping them, and the
+ clearing step then scrubs old ones. This means `clear_tool_results` is a mode switch
+ that changes FIFO's selection behavior:
+ - `clear_tool_results: false` (default) → strip all tool messages from context
+ (current behavior, backward compatible)
+ - `clear_tool_results: true` → include tool messages but scrub old pairs
+- **Pair-wise clearing rule.** OpenAI-compatible APIs require tool result messages
+ to immediately follow their paired assistant `tool_calls` message. Clearing always
+ operates on complete pairs (assistant-with-tool_calls + all its tool results):
+ - **Old pairs** (older than `clear_tool_results_after` turns): drop the entire pair
+ — both the assistant tool_calls message and all its tool result messages. If the
+ assistant message also contains text `content`, keep only the text content and
+ remove the `tool_calls` field.
+ - **Recent pairs** (within threshold): keep verbatim.
+ - Never drop a tool result while keeping its paired assistant call, or vice versa.
+- Config: `clear_tool_results: true`, `clear_tool_results_after: 3` (turns)
+
+**1e. Summary strategy**
+- `SummaryMemory` — after each turn, call the LLM to update a running summary
+- Receives the `OpenAI` client and model ID from the harness via the factory
+ (`create_memory(config, ..., llm_client=client, llm_model=model_id)`). No new
+ client construction — reuses the same client and endpoint the agent uses for
+ its main completions.
+- Summary stored alongside raw JSONL as a separate file (`sessions/{id}_summary.txt`).
+ Raw JSONL is the source of truth; summary is derived and can be regenerated.
+- Config: `max_summary_tokens` controls summary length
+- If the LLM summarization call fails (network error, rate limit), falls back to
+ truncated FIFO behavior for that turn and retries summarization next turn.
+
+**1f. Summary + Buffer Hybrid**
+- `SummaryBufferMemory` — FIFO window for recent messages, LLM summary for evicted ones
+- When buffer exceeds `max_messages`, evicted messages are summarized and prepended
+- Uses the same LLM client plumbing as SummaryMemory (Phase 1e)
+- Returns: `[system, ...pinned, summary_msg, ...recent_buffer, user_prompt]`
+- Pinned messages (if configured) appear before the summary, since they represent
+ high-priority context that should not be summarized away
+
+### Phase 2: Advanced strategies
+
+**2a. Forgetting Curves**
+- Integrated into the base strategy's selection logic (NOT a post-selection mixin).
+ Like pinning, decay affects *which* messages are selected from the full history,
+ so it must run before the window is chosen — not after.
+- Uses `_meta.ts` (timestamp) and `_meta.access_count` from stored messages.
+- Replaces strict FIFO ordering with score-based selection:
+ `score = importance * exp(-lambda * age_hours)` where
+ `lambda = ln(2) / decay_halflife_hours`.
+- Selection: from the full history, score all messages, select the top N by score
+ (instead of the last N by position). Pinned messages bypass scoring.
+- This is implemented as a `DecayScoredMemory` base strategy (or as a config option
+ on FIFO: `decay_halflife_hours` switches FIFO from positional to scored selection).
+- Config: `decay_halflife_hours: 4.0`
+
+**2b. Entity Memory**
+- `EntityTracker` mixin — after each turn, extract entities via LLM call
+- Store entity summaries in a separate JSON file (`sessions/{id}_entities.json`)
+- Inject relevant entity summaries into context alongside conversation history
+- Config: `entity_tracking: true`
+
+**2c. Episodic + Semantic**
+- `EpisodicMemory` — stores all messages with timestamps and importance scores
+- Retrieval: weighted combination of recency, importance, and relevance (cosine sim on text)
+- Periodic reflection: every N turns, LLM generates high-level "reflections" stored separately
+- Config: `reflection_interval: 10` (turns between reflections)
+
+**2d. Reflexion**
+- `ReflexionMemory` — after each turn, LLM generates self-critique
+- Store last N reflections, inject into next turn's prompt
+- Config: `max_reflections: 3`
+
+### Phase 3: Infrastructure-dependent strategies
+
+**3a. RAG / Embedding Retrieval**
+- Requires an embedding endpoint (check if Models.Corp serves one)
+- Simple file-based vector store using numpy (no external DB)
+- `RAGMemory` — embed all messages, retrieve top-K by cosine similarity at query time
+- Fallback: if no embedding endpoint, use BM25 (keyword matching) as a pure-Python alternative
+- Config: `rag_top_k: 10`
+
+**3b. Token Budget Guard**
+- Wraps any base strategy
+- Counts tokens (tiktoken for OpenAI-compatible, or char-based heuristic for others)
+- When context exceeds threshold, triggers the base strategy's compaction
+- Config: `max_context_tokens: 4000, compaction_threshold: 0.85`
+
+**3c. Hierarchical Memory**
+- Multi-tier storage: working (current turn), short-term (last few turns), long-term (summarized)
+- Automatic promotion/demotion between tiers based on age and access patterns
+- Config: `tiers: {short_term: 10, long_term: 50}`
+
+---
+
+## Testing Strategy
+
+### Unit tests (`tests/test_conversation_memory.py`)
+
+Each strategy and mixin gets isolated unit tests. No LLM calls — mock the OpenAI client for strategies that need summarization.
+
+#### Test fixtures
+
+```python
+SAMPLE_MESSAGES = [
+ {"role": "user", "content": "What's the status of the deployment?"},
+ {"role": "assistant", "content": "Checking the logs now..."},
+ {"role": "assistant", "content": "", "tool_calls": [{"id": "1", "type": "function", "function": {"name": "get_messages", "arguments": "{}"}}]},
+ {"role": "tool", "tool_call_id": "1", "content": "3 messages in #general..."},
+ {"role": "assistant", "content": "The deployment looks healthy."},
+ {"role": "user", "content": "Great, create a ticket for the follow-up."},
+ {"role": "assistant", "content": "", "tool_calls": [{"id": "2", "type": "function", "function": {"name": "create_ticket", "arguments": "{}"}}]},
+ {"role": "tool", "tool_call_id": "2", "content": "TK-abc123 created"},
+ {"role": "assistant", "content": "Created ticket TK-abc123."},
+]
+
+SYSTEM_PROMPT = "You are Rocky. You're a member of a small team."
+```
+
+#### NoMemory tests
+- `test_no_memory_returns_system_and_user_only` — verify only [system, user] returned
+- `test_no_memory_add_messages_is_noop` — verify messages are discarded
+- `test_no_memory_save_load_is_noop` — verify no file I/O
+
+#### FIFOMemory tests
+- `test_fifo_returns_window` — add 20 messages, verify only last N returned by `get_messages()`
+- `test_fifo_preserves_system_prompt` — system prompt always at position 0
+- `test_fifo_user_prompt_always_last` — new user message always at end
+- `test_fifo_persists_to_jsonl` — save, create new instance, load, verify state
+- `test_fifo_stores_all_messages` — verify `add_messages()` stores tool calls and tool results in JSONL (Phase 1b change)
+- `test_fifo_filters_tool_messages_in_selection` — verify `get_messages()` strips tool messages from API context (filtering moved from storage to selection)
+- `test_fifo_handles_empty_session_file` — graceful handling of missing/empty file
+- `test_fifo_max_messages_boundary` — exactly N messages, N+1 messages, 0 messages
+- `test_fifo_old_session_file_compat` — session files without `_meta` fields load correctly
+- `test_fifo_persists_user_message` — verify the user turn prompt is stored in JSONL (Phase 1b fix)
+
+#### SummaryMemory tests
+- `test_summary_calls_llm_for_compression` — mock OpenAI client, verify summarization prompt sent
+- `test_summary_replaces_history_with_summary` — after summarization, only summary + recent messages in context
+- `test_summary_preserves_raw_on_disk` — raw JSONL still contains all messages
+- `test_summary_handles_llm_failure` — falls back to FIFO if summarization call fails
+- `test_summary_max_tokens_respected` — summary stays within configured token budget
+
+#### SummaryBufferMemory tests
+- `test_hybrid_keeps_recent_verbatim` — messages within window are returned as-is
+- `test_hybrid_summarizes_evicted` — messages outside window are summarized
+- `test_hybrid_summary_prepended` — summary message appears after system prompt, before buffer
+- `test_hybrid_boundary` — exactly at max_messages, no summarization triggered
+- `test_hybrid_incremental_summary` — new evictions update existing summary, don't regenerate from scratch
+
+#### Pinned messages tests
+- `test_pinned_marked_at_storage_time` — `add_messages()` sets `_meta.pinned=true` on matching messages
+- `test_pinned_survives_beyond_fifo_window` — add 30 messages with window=10, pinned message from turn 1 still in `get_messages()` output
+- `test_pinned_by_content_substring` — pin by content substring (e.g., "Scenario Director" appearing in message content)
+- `test_pinned_by_content_regex` — pin by content regex pattern match
+- `test_pinned_ordering` — pinned messages appear after system prompt, before recent window, in chronological order
+- `test_pinned_coexists_with_fifo` — output is `[system, ...pinned, ...recent_window, user_prompt]`
+- `test_pinned_token_budget_interaction` — pinned messages count against token budget
+- `test_pinned_not_duplicated` — a pinned message that is also in the recent FIFO window appears only once
+- `test_pinned_no_meta_in_output` — pinned messages returned by `get_messages()` have `_meta` stripped
+
+#### Tool result clearing tests
+- `test_clearing_requires_full_persistence` — verify raw JSONL contains tool messages (Phase 1b prerequisite)
+- `test_clearing_enables_tool_messages_in_context` — with `clear_tool_results: true`, FIFO includes tool messages (unlike default stripping behavior)
+- `test_clearing_drops_old_pairs` — old tool-call/result pairs (beyond threshold) are dropped as a unit
+- `test_clearing_keeps_text_from_mixed_assistant` — assistant message with both text and `tool_calls` keeps text, drops `tool_calls` field
+- `test_clearing_preserves_recent_pairs` — tool pairs within `clear_tool_results_after` threshold kept verbatim
+- `test_clearing_valid_message_ordering` — output never has a tool result without its preceding assistant tool_calls (validates API compatibility)
+- `test_clearing_handles_orphaned_tool_results` — graceful with tool results whose paired call is missing (drop the orphan)
+- `test_clearing_token_reduction` — verify measurable token reduction (>20%) on a tool-heavy conversation
+- `test_clearing_false_strips_all_tool_messages` — with `clear_tool_results: false` (default), all tool messages are stripped (backward compat)
+- `test_clearing_no_meta_in_output` — cleared messages returned by `get_messages()` have `_meta` stripped
+
+#### Forgetting curves tests
+- `test_decay_scores_recent_higher` — recent messages get higher scores
+- `test_decay_selects_top_scored` — selection picks top N by score from full history, not last N by position
+- `test_decay_access_reinforces` — accessed messages get score boost via `_meta.access_count`
+- `test_decay_halflife_configurable` — different halflife values produce different selection sets
+- `test_decay_pinned_bypass` — pinned messages always included regardless of score
+- `test_decay_interleaved_old_new` — can select a mix of old high-scored and new messages (unlike FIFO which only selects contiguous tail)
+- `test_decay_no_meta_in_output` — selected messages have `_meta` stripped
+
+#### EntityMemory tests
+- `test_entity_extraction` — mock LLM extracts entities from conversation
+- `test_entity_summaries_injected` — relevant entity summaries appear in context
+- `test_entity_summaries_updated` — new information about an entity updates its summary
+- `test_entity_persistence` — entity store persists across turns
+- `test_entity_extraction_failure` — graceful fallback if LLM extraction fails
+
+#### EpisodicMemory tests
+- `test_episodic_stores_with_timestamps` — each message gets a timestamp
+- `test_episodic_retrieval_weighted` — retrieval uses recency + importance + relevance
+- `test_episodic_reflection_generated` — after N turns, reflection is generated
+- `test_episodic_reflections_injected` — reflections appear in context
+- `test_episodic_importance_scoring` — important messages scored higher
+
+#### ReflexionMemory tests
+- `test_reflexion_generates_critique` — mock LLM generates self-critique after turn
+- `test_reflexion_injects_past_reflections` — last N reflections in context
+- `test_reflexion_window_truncates` — only last max_reflections kept
+- `test_reflexion_failure_graceful` — if critique generation fails, turn proceeds normally
+
+#### RAGMemory tests
+- `test_rag_embeds_messages` — messages are embedded and stored
+- `test_rag_retrieves_relevant` — top-K most similar messages returned
+- `test_rag_bm25_fallback` — if no embedding endpoint, falls back to keyword matching
+- `test_rag_persistence` — vector store persists to disk
+- `test_rag_deduplication` — same message not stored twice
+
+#### TokenBudgetGuard tests
+- `test_budget_triggers_compaction` — when context exceeds threshold, compaction called
+- `test_budget_no_compaction_under_threshold` — under threshold, no compaction
+- `test_budget_char_heuristic` — character-based token estimation works
+- `test_budget_tiktoken` — tiktoken counting works when available
+
+#### Outbound normalization tests
+- `test_normalize_strips_meta` — `_normalize_for_api()` removes `_meta` from all messages
+- `test_normalize_preserves_standard_fields` — `role`, `content`, `tool_calls`, `tool_call_id`, `name` survive normalization
+- `test_normalize_strips_unknown_fields` — any field not in the OpenAI schema is removed
+- `test_normalize_handles_missing_fields` — messages without optional fields (no `content`, no `tool_calls`) normalize cleanly
+- `test_normalize_called_by_all_strategies` — verify `get_messages()` output from every strategy contains no `_meta` fields (parametrized across all strategy types)
+
+#### Factory tests
+- `test_create_memory_empty_config` — `{}` returns NoMemory (factory default)
+- `test_create_memory_fifo` — `{"strategy": "fifo"}` returns FIFOMemory
+- `test_create_memory_with_pin_patterns` — config with `pin_patterns` returns strategy with pinning enabled
+- `test_create_memory_unknown_strategy_raises` — unknown strategy name raises ValueError
+- `test_create_memory_from_legacy_args` — old `--memory-strategy fifo` still works
+- `test_create_memory_llm_client_required_for_summary` — `{"strategy": "summary"}` without `llm_client` raises ValueError
+- `test_create_memory_llm_client_optional_for_fifo` — `{"strategy": "fifo"}` works without `llm_client`
+- `test_orchestrator_default_when_sessions_enabled` — verify `ModelscorpBackend` injects `{"strategy": "fifo", "max_messages": 50}` when `use_sessions=True` and persona has no explicit memory config
+- `test_explicit_config_overrides_orchestrator_default` — persona with `memory: {"strategy": "summary-buffer"}` is not overridden by the orchestrator session default
+
+### Integration tests (live model, controlled scenario)
+
+These run against a real (or mocked) MCP server and LLM endpoint. Slower, run separately.
+
+#### Test harness setup
+
+Create a minimal test scenario with 2 agents:
+- Agent A: posts messages to a channel
+- Agent B: uses the memory strategy under test
+
+Script drives N turns of conversation, then verifies Agent B's behavior.
+
+#### Integration test cases
+
+**Memory persistence across turns:**
+1. Run agent for 5 turns with `fifo` strategy
+2. Kill and restart agent process
+3. Verify agent recalls messages from turns 1-5
+
+**Summary quality:**
+1. Run agent for 20 turns with `summary-buffer` strategy (window=5)
+2. Ask agent "what was discussed in the first few messages?"
+3. Verify response references early content (via summary, not raw messages)
+
+**Tool result clearing effectiveness:**
+1. Run agent for 10 turns with heavy tool use
+2. Measure token count of context with and without tool result clearing
+3. Verify >30% token reduction with clearing enabled
+
+**Forgetting curve behavior:**
+1. Run agent for 20 turns
+2. Ask about a message from turn 1 (should be faded)
+3. Ask about a message from turn 18 (should be vivid)
+4. Verify responses reflect recency weighting
+
+**Entity tracking accuracy:**
+1. Discuss 3 distinct entities across 10 turns
+2. Verify entity store contains all 3 with accurate summaries
+3. Ask agent about entity from turn 2 — verify it recalls via entity memory
+
+**Pinned message survival:**
+1. Configure pin for "Scenario Director" messages
+2. Run 30 turns with a Scenario Director message at turn 1
+3. Verify the pinned message is still in context at turn 30
+
+### Comparative benchmarking
+
+Run the same 20-turn conversation script against all strategies and measure:
+
+| Metric | How to measure |
+|--------|---------------|
+| Token usage per turn | Sum `input_tokens` from harness output |
+| Total cost | Sum across all turns |
+| Recall accuracy | Ask 5 factual questions about earlier turns, score 0-5 |
+| Latency per turn | Wall clock time from harness output |
+| Context size growth | Track message array length per turn |
+| Persistence size | Measure session file size on disk |
+
+Output as a comparison table per strategy. Run on at least 2 models (one strong like Qwen 3-14B, one weak like Granite Micro) to see how model capability interacts with strategy.
+
+### Regression tests
+
+After any memory strategy change, verify:
+- [ ] `NoMemory` still works (stateless agents unaffected)
+- [ ] `FIFOMemory` API-context behavior unchanged for agents with no explicit memory config (same messages sent to LLM; persistence size/content will change due to storing tool messages)
+- [ ] Session files from old format (no `_meta`, no tool messages) load correctly
+- [ ] Agent loop completes without error for each strategy
+- [ ] `signal_done` still detected correctly (memory doesn't interfere with loop control)
+- [ ] Fallback channel still fires when needed
+- [ ] Memory config absent in scenario.yaml defaults to current behavior
+- [ ] Session save/load preserves `memory` config in roster (round-trip test)
+- [ ] Hire/fire (add_agent) preserves `memory` config on the new persona
+- [ ] `--memory-strategy fifo` (legacy CLI) still works and behaves identically
+- [ ] Factory default (no config) returns NoMemory, orchestrator default (sessions enabled) returns FIFO
+- [ ] No `_meta` fields in any messages returned by `get_messages()` (outbound normalization)
+- [ ] Tool clearing never produces orphaned tool results (valid message ordering)
+
+---
+
+## Implementation Order (recommended)
+
+```
+Phase 0: Extract cosim_agent/ package (prerequisite — enables testing + clean imports)
+Phase 1a: Config plumbing refactor (prerequisite for everything)
+Phase 1b: Persistence: store all messages (prerequisite for 1c, 1d, and Phase 2+)
+Phase 1c: Pinned messages (high value, enables eval scenarios)
+Phase 1d: Tool result clearing (high value, reduces token waste)
+Phase 1e: SummaryMemory + LLM client plumbing (unlocks long conversations)
+Phase 1f: SummaryBufferMemory (best general-purpose strategy)
+Phase 2a: ForgettingCurves (improves FIFO eviction quality)
+Phase 2b: EntityMemory (useful for multi-agent tracking)
+Phase 2c: EpisodicMemory + reflections (Generative Agents-style)
+Phase 2d: ReflexionMemory (self-improvement loop)
+Phase 3a: RAGMemory (needs embedding endpoint)
+Phase 3b: TokenBudgetGuard (wraps any strategy)
+Phase 3c: HierarchicalMemory (most complex, do last)
+```
+
+Each phase should be independently deployable — a new strategy or mixin can be added, tested, and configured per-agent without affecting agents using other strategies.
+
+---
+
+## Risk & Constraints
+
+- **LLM calls for memory management add cost.** Summary, entity, episodic, and reflexion strategies all require extra LLM calls per turn. For Models.Corp models behind a rate limiter, this could be a bottleneck. Mitigation: summarize every N turns instead of every turn, use a cheap/fast model for summarization.
+- **LLM client plumbing for memory strategies.** `create_memory()` currently takes only `(strategy, session_file, system_prompt, **kwargs)`. Strategies that need LLM calls (summary, entity, episodic, reflexion) require access to the OpenAI client and model ID. The factory signature must be extended to accept `llm_client` and `llm_model` as optional params. These come from the same client instance that `modelscorp_agent.py` already constructs for the main completion calls — no new client construction or credential handling needed. Strategies that don't need LLM calls (fifo, none) ignore these params.
+- **Weak models can't self-manage memory.** MemGPT-style paging is excluded because Granite Micro can't reliably call memory management functions. All memory logic must live in the harness, not in the model's reasoning.
+- **Session save/load and hire/fire must preserve memory config.** Three code paths construct persona dicts with fixed field lists:
+ - `lib/session.py:_get_roster()` (lines 108-119) — serializes persona to JSON for save
+ - `lib/session.py:load_session()` (lines 326-334) — reconstructs persona dict from saved JSON
+ - `lib/container_orchestrator.py` add_agent handler (lines 852-859) — constructs persona dict for hired agents
+ All three must include `memory`, `allowed_tools`, and `fallback_channel`. A future-proof approach: instead of enumerating fields, copy the full persona dict and only override/validate specific keys. But at minimum, the three new fields must be added to all three locations in Phase 1a.
+- **`_meta` leaking to API calls will cause hard failures.** If `_normalize_for_api()` is not called (or is bypassed), `_meta` fields will reach `client.chat.completions.create()` and some backends will reject the request with a schema validation error. This is the highest-risk failure mode of the `_meta` approach. Mitigation: the normalization method lives on the base class and is called as the final step of `get_messages()` in the base class implementation (template method pattern), so subclasses cannot accidentally skip it. Unit tests parametrized across all strategies verify no `_meta` in output.
+- **Tool message ordering violations cause silent model confusion or hard API errors.** If clearing drops an assistant tool_calls message but keeps its tool results, or vice versa, the API may reject the request or the model may hallucinate. The pair-wise clearing rule (Phase 1d) prevents this, but any future code that manipulates tool messages must respect it. A validation assert in `_normalize_for_api()` can catch violations in development.
+- **Persistence layer change is a breaking behavioral change.** Phase 1b changes `FIFOMemory.add_messages()` to store tool messages that were previously stripped. This increases session file size but is required for tool result clearing and other strategies. Old session files (without tool messages) remain loadable — they just have less data available for clearing/replay.
+- **Session file format changes.** New strategies may need richer metadata than raw JSONL. The `_meta` field on stored messages provides forward-compatible extensibility — old files without `_meta` load fine with defaults. Use a versioned header in session files so old files can be migrated or read by new code.
+- **Container image size.** Adding numpy (for RAG vector math) or tiktoken increases the image. Keep dependencies optional — import with try/except and fall back gracefully.
+- **Testing LLM-dependent strategies.** Summary quality is nondeterministic. Integration tests should use fuzzy matching (keyword presence, not exact string comparison) and run multiple times to check stability.
diff --git a/docs/memory-handling-methods.md b/docs/memory-handling-methods.md
new file mode 100644
index 0000000..0356a33
--- /dev/null
+++ b/docs/memory-handling-methods.md
@@ -0,0 +1,403 @@
+# Memory Handling Methods for LLM Agent Systems
+
+A survey of memory strategies used in LLM agent systems, with notes on relevance to multi-agent chat architectures where agents communicate via tool calls (MCP).
+
+---
+
+## 1. Sliding Window / FIFO
+
+Retains only the most recent K messages in a first-in-first-out queue. Oldest messages are dropped when the window is full. No summarization or compression — data is simply discarded.
+
+**Mechanics:** Fixed-size buffer. New message arrives, oldest evicted if at capacity.
+
+**Pros:**
+- Trivially simple, predictable token usage
+- No LLM calls for memory management
+- Zero latency overhead
+
+**Cons:**
+- Complete loss of early context
+- No way to reference anything outside the window
+- Performance degrades on tasks requiring long-range recall
+
+**Used by:** LangChain `ConversationBufferWindowMemory`, MemGPT (innermost message buffer), most chat UIs implicitly.
+
+**Multi-agent relevance:** Simple baseline for per-agent message history, but agents lose awareness of early coordination decisions. Insufficient alone for systems where agents must track agreements made many turns ago.
+
+**Status in cosim:** Implemented as `FIFOMemory` in `container/conversation_memory.py`.
+
+---
+
+## 2. Summary / Compression
+
+Uses an LLM to compress the full conversation history into a running summary. The summary replaces raw messages in the context window.
+
+**Mechanics:** After each turn (or batch of turns), the LLM is prompted to update a running summary incorporating new information. Only the summary is injected into the prompt, not the raw history. The summary grows sublinearly compared to raw history.
+
+**Pros:**
+- Dramatically reduces token usage for long conversations
+- Retains gist of entire history
+- Bounded context growth regardless of conversation length
+
+**Cons:**
+- Lossy — details, exact quotes, and nuance are lost
+- Summaries can drift or misrepresent over time (semantic drift)
+- Requires additional LLM calls, adding latency and cost per turn
+
+**Used by:** LangChain `ConversationSummaryMemory`, Claude Code's compaction system (triggers at ~95% of 200K window), Anthropic's compaction API.
+
+**Multi-agent relevance:** Each agent could maintain its own summary, but summaries diverge across agents, leading to inconsistent shared understanding. Useful for reducing per-agent context cost in systems with many concurrent agents.
+
+---
+
+## 3. Summary + Buffer Hybrid
+
+Combines a running summary of older messages with a raw buffer of the most recent K messages (or tokens up to a `max_token_limit`). Preserves full fidelity for recent context while retaining the gist of older exchanges.
+
+**Mechanics:** Monitors the token count of the raw buffer. When it exceeds the limit, the oldest messages are summarized by an LLM and the summary replaces them. Recent messages remain verbatim.
+
+**Pros:**
+- Best of both worlds — recent detail plus long-range gist
+- Configurable boundary between summarized and raw regions
+- Most practical balance of cost and recall quality
+
+**Cons:**
+- Still lossy for older messages
+- Boundary between "summarized" and "raw" is arbitrary
+- Summary quality depends on the LLM used for compression
+
+**Used by:** LangChain `ConversationSummaryBufferMemory`, Claude Code (preserves 5 most recently accessed files alongside compressed summary), Hermes Agent framework (structured summary template).
+
+**Multi-agent relevance:** Strong candidate for per-agent memory. Each agent keeps full fidelity on recent messages (including messages from other agents via tool calls) while maintaining a summary of earlier coordination.
+
+---
+
+## 4. RAG / Embedding-Based Retrieval
+
+Stores past interactions (or extracted facts) as vector embeddings in a database. At inference time, the current query is embedded and the most semantically similar memories are retrieved and injected into the prompt.
+
+**Mechanics:** Each message or extracted fact is embedded and stored in a vector database (ChromaDB, Pinecone, pgvector). At query time, the current context is embedded and cosine similarity identifies the top-K relevant memories. Retrieved memories are inserted into the prompt.
+
+**Pros:**
+- Scales to very large memory stores
+- Only contextually relevant memories consume tokens
+- Works across sessions
+- No information is ever truly "lost"
+
+**Cons:**
+- Retrieval quality is a bottleneck — conversational turns are interdependent, so cosine similarity on isolated chunks often misses contextually important episodes
+- Temporal queries ("what happened last Monday") retrieve poorly
+- Requires embedding infrastructure
+- Does not learn from interactions (each query is independent)
+
+**Used by:** CrewAI short-term memory (ChromaDB), Mem0 (multi-signal retrieval: semantic similarity + BM25 + entity matching), MongoDB + LangGraph for cross-session memory.
+
+**Multi-agent relevance:** Enables shared memory stores where all agents can query a common vector database. However, agents may retrieve different subsets for the same event, leading to inconsistent recall. Works well as a "collective memory" when paired with access controls.
+
+---
+
+## 5. Entity Memory
+
+Extracts and tracks named entities (people, places, organizations, concepts) mentioned in conversation, maintaining an evolving summary for each entity.
+
+**Mechanics:** An LLM with a dedicated prompt extracts proper nouns from each turn. For each extracted entity, a separate LLM call generates or updates a summary stored in an entity store (in-memory, Redis, or SQLite). At inference, entities relevant to the current query are retrieved and their summaries injected into the prompt.
+
+**Pros:**
+- Tracks specific entities across long conversations
+- Provides structured, queryable knowledge about key participants and topics
+- Natural fit for systems with many named objects (tickets, repos, people)
+
+**Cons:**
+- Relies heavily on LLM extraction quality (may miss implicit entities or hallucinate)
+- Per-turn LLM calls for extraction and summarization add cost
+- Entity disambiguation is fragile (e.g., "the project" vs. "Project Alpha")
+
+**Used by:** LangChain `ConversationEntityMemory`, Mem0's entity linking.
+
+**Multi-agent relevance:** Highly relevant. In multi-agent chat, agents need to track who said what, who is responsible for what, and which entities (tickets, documents, repos) are being discussed. Entity memory could serve as a shared registry of known entities across agents.
+
+---
+
+## 6. Knowledge Graph Memory
+
+Stores memory as a graph of entities (nodes) and their relationships (edges), enabling multi-hop reasoning and structured relationship queries.
+
+**Mechanics:** An LLM extracts (subject, predicate, object) triples from conversation and writes them to a graph store. Retrieval traverses the graph from query-relevant entities, following edges to find related facts. Systems like Graphiti (by Zep AI) add temporal awareness for incremental real-time updates.
+
+**Pros:**
+- Explicitly models relationships between entities
+- Supports multi-hop reasoning ("who reports to the person who created this ticket?")
+- Temporal-aware graphs can track how relationships change over time
+
+**Cons:**
+- Schema design is challenging
+- Graph construction requires reliable triple extraction (LLM-dependent, error-prone)
+- Benchmarks show accuracy differences between graph-based and vector-based approaches are often not statistically significant, while vector-based is more efficient
+- Storage overhead and "memory bloat" are concerns
+
+**Used by:** LangChain `ConversationKGMemory`, Graphiti (Neo4j-backed, by Zep AI), MAGMA, G-Memory.
+
+**Multi-agent relevance:** The "shared blackboard" pattern — a knowledge graph serves as collective memory accessible to all agents. Each agent reads/writes to the graph. Strong for organizations where relationship structure matters (org charts, dependency tracking, ticket assignment chains).
+
+---
+
+## 7. Episodic vs. Semantic Memory
+
+Inspired by cognitive science. Episodic memory stores specific experiences as ordered sequences (what happened, when, where). Semantic memory stores generalized facts and knowledge abstracted from episodes.
+
+**Mechanics:** In Generative Agents (Park et al., 2023), every observation enters an episodic "memory stream" with a timestamp and importance score. Retrieval uses a weighted combination:
+
+```
+score = alpha_recency * recency + alpha_importance * importance + alpha_relevance * relevance
+```
+
+Recency uses exponential decay (0.995/hour). Periodically, the agent synthesizes episodes into higher-level "reflections" (semantic memory). The CoALA framework formalizes this taxonomy, adding procedural memory (skills stored as code, as in Voyager's skill library).
+
+**Pros:**
+- Mirrors human cognition — intuitive and well-studied
+- Episodic memory preserves narrative context and temporal flow (useful for audit trails)
+- Semantic memory provides compact, generalized knowledge
+- Ablation studies showed removing reflection eliminated emergent coordination behaviors
+
+**Cons:**
+- The consolidation step (episodes → semantic knowledge) requires periodic LLM-driven summarization, which is fragile
+- Maintaining consistent scoring weights is challenging
+- Procedural memory is domain-specific and hard to generalize
+
+**Used by:** Generative Agents (Park et al., UIST 2023), Voyager (procedural/skill memory), CoALA framework, HiMem, Letta/MemGPT.
+
+**Multi-agent relevance:** Directly applicable. Each agent in a multi-agent simulation should have its own episodic stream, with shared semantic reflections surfaced to the group. The Generative Agents architecture was specifically designed for multi-agent simulation.
+
+---
+
+## 8. MemGPT / Virtual Context Management (Paging)
+
+Treats the LLM context window as RAM and external storage as disk, using OS-inspired virtual memory paging. The LLM itself manages what data is paged in and out via function calls.
+
+**Mechanics:** Two-tier architecture:
+- **Main context** (in-window): system instructions, working context "scratchpad," FIFO message queue
+- **External context**: Recall Storage (searchable database of all past messages) and Archival Storage (vector-indexed long-term store)
+
+The LLM autonomously decides what to keep, evict, or retrieve by calling memory management functions (`archival_memory_search`, `core_memory_append`, etc.). When token usage approaches a threshold, the system inserts an internal alert and the LLM decides what to compress or page out.
+
+**Pros:**
+- Provides the illusion of unbounded memory within a fixed context window
+- Self-directed — the LLM manages its own memory
+- Model and provider agnostic
+
+**Cons:**
+- Relies on the LLM making good memory management decisions (unreliable for smaller models)
+- Each paging operation requires inference, adding latency and cost
+- Complex to implement correctly
+
+**Used by:** MemGPT (Packer et al., 2023), Letta framework (production MemGPT).
+
+**Multi-agent relevance:** Each agent could run its own MemGPT-style memory manager. The archival storage could be shared across agents. The self-directed approach reduces the need for centralized memory management but makes coordination harder (each agent pages independently). Requires models capable of reliable function calling — not suitable for smaller models that struggle with tool use.
+
+---
+
+## 9. Reflexion / Self-Reflection Memory
+
+Agents verbally reflect on task failures and store reflective text in an episodic memory buffer to improve performance on subsequent attempts. A form of "verbal reinforcement learning."
+
+**Mechanics:** Three components:
+- **Actor:** generates actions
+- **Evaluator:** scores outcomes
+- **Self-Reflection Model:** generates natural language feedback on failures
+
+After each trial, the reflection is stored in a memory buffer (truncated to last 3 reflections). On the next attempt, past reflections are injected into the prompt, providing a "semantic gradient" for improvement. No weight updates — learning is purely through prompt augmentation.
+
+**Pros:**
+- Enables rapid improvement without fine-tuning
+- Achieves 91% pass@1 on HumanEval (vs. 80% for GPT-4 baseline)
+- Simple to implement — just store and inject text
+
+**Cons:**
+- Relies on accurate self-evaluation (hard for complex tasks)
+- Limited to a sliding window of reflections (typically 3)
+- Does not generalize across tasks — reflections are task-specific
+- The frozen base model never actually learns
+
+**Used by:** Reflexion (Shinn et al., NeurIPS 2023).
+
+**Multi-agent relevance:** Agents could reflect on coordination failures ("I should have checked the #engineering channel before committing"). Shared reflections could serve as organizational learning. However, the current formulation is single-agent and task-specific.
+
+---
+
+## 10. Scratchpad / Working Memory
+
+A designated region of the context window where the agent maintains structured notes, intermediate reasoning state, or task progress — distinct from conversation history.
+
+**Mechanics:** A mutable section of the prompt that the agent reads and writes to via tool calls or structured output. MemGPT's "working context" partition is the canonical example. HiAgent chunks working memory by subgoals, summarizing action-observation pairs once subgoals complete (reducing context usage from 100% to 65% while doubling success rates).
+
+**Pros:**
+- Provides structured, persistent state within or alongside the context window
+- Reduces redundancy in conversation history
+- Agent controls what is retained vs. discarded
+
+**Cons:**
+- Requires the agent to reliably maintain the scratchpad (LLMs can forget to update it)
+- Scratchpad content competes for tokens with other context
+- Quality depends on the model's ability to self-organize
+
+**Used by:** MemGPT/Letta (working context partition), Claude Code (structured note-taking, to-do lists), HiAgent, common in code-generation agents (plan files).
+
+**Multi-agent relevance:** Each agent can maintain its own scratchpad tracking its current task, assigned tickets, and coordination state. A shared scratchpad (e.g., a shared document or wiki page) could serve as a lightweight coordination mechanism.
+
+---
+
+## 11. Hierarchical Memory (Short/Mid/Long-Term Tiers)
+
+Organizes memory into multiple tiers of increasing abstraction and decreasing access frequency, mirroring cognitive models (Atkinson-Shiffrin) and OS memory hierarchies.
+
+**Mechanics:** H-MEM (2025) uses four layers:
+1. **Domain Layer** — broadest abstractions
+2. **Category Layer** — topic groupings
+3. **Memory Trace Layer** — individual memories
+4. **Episode Layer** — finest-grained raw experiences
+
+Each memory vector includes positional indices pointing to related sub-memories in adjacent layers. HiMem uses topic-aware segmentation to construct Episode Memory, then consolidates stable facts into dense Note Memory.
+
+**Pros:**
+- Different types of information stored at appropriate granularities
+- Efficient retrieval (traverse from abstract to specific)
+- Reduces context pollution
+
+**Cons:**
+- Complex to implement and maintain
+- Schema/tier design requires upfront decisions
+- Recent work shows simple retrieval can outperform complex hierarchies on some benchmarks
+
+**Used by:** H-MEM (2025), HiMem (2026), CrewAI unified Memory (hierarchical scope tree), MemGPT's two-tier system.
+
+**Multi-agent relevance:** Natural fit for organizations. Individual agents get personal short-term memory; teams share mid-term departmental memory; the organization shares long-term institutional knowledge.
+
+---
+
+## 12. Forgetting Curves / Decay
+
+Applies time-based decay functions to memory importance, inspired by the Ebbinghaus forgetting curve. Memories that are not accessed or reinforced gradually lose priority and may be pruned.
+
+**Mechanics:** Memory strength decreases based on time elapsed and is reinforced by access. Generative Agents use exponential decay (factor 0.995 per hour) for the recency component of retrieval scoring. "Active forgetting" (deliberately pruning irrelevant or stale memories) outperforms naive "add-all" approaches, which suffer from "catastrophic interference" where accumulated stale/incorrect memories degrade performance.
+
+**Pros:**
+- Prevents memory bloat
+- Naturally prioritizes recent and frequently-accessed information
+- More human-like memory behavior
+
+**Cons:**
+- Risk of forgetting critically important but infrequently accessed information
+- Decay parameters require tuning
+- Hard to recover from premature forgetting
+
+**Used by:** MemoryBank (Ebbinghaus-inspired), Generative Agents (recency decay), Nemori (Free-Energy Principle-based calibration loops).
+
+**Multi-agent relevance:** Different agents might need different decay rates — a support agent needs to remember recent customer issues; a strategic agent needs to remember decisions from weeks ago. Shared memories should decay more slowly than individual working notes.
+
+---
+
+## 13. Pinned / Priority Messages
+
+Certain high-priority information is persistently kept in the active context window and never evicted, regardless of memory pressure. Analogous to "pinning" pages in OS virtual memory.
+
+**Mechanics:** In MemGPT/Letta, the system prompt and "core memory" partitions are static — never paged out. Claude Code's compaction protects "head messages" (system prompt + first exchange) and preserves the 5 most recently accessed files. Priority can be assigned by importance scoring or by explicit user/system designation.
+
+**Pros:**
+- Guarantees critical information (identity, goals, key constraints) is always available
+- Prevents catastrophic forgetting of mission-critical context
+
+**Cons:**
+- Pinned content permanently consumes token budget
+- Over-pinning leads to context starvation for dynamic content
+- No formal framework for deciding what to pin
+
+**Used by:** MemGPT/Letta (core memory partition), Claude Code (protected head messages), most agent frameworks implicitly pin system prompts.
+
+**Multi-agent relevance:** Each agent's persona prompt and role definition should be pinned. Shared organizational rules, current sprint goals, or active incident details could be pinned across all agents' contexts.
+
+---
+
+## 14. Token-Budget-Aware Management
+
+Explicitly allocates the available token budget across competing concerns (system prompt, retrieved memories, conversation history, tool results) and triggers compression/eviction based on usage thresholds.
+
+**Mechanics:** Claude Code triggers auto-compaction at ~95% of 200K tokens. LangChain's `ConversationSummaryBufferMemory` monitors token counts and triggers summarization when `max_token_limit` is exceeded. Research shows 23% performance degradation when context utilization exceeds 85% of maximum. The "lost-in-the-middle" problem (Liu et al., 2024) shows 30%+ accuracy drops for information placed in the middle of the context window.
+
+**Pros:**
+- Prevents context overflow
+- Optimizes cost/performance tradeoff
+- Addresses the structural "lost-in-the-middle" problem
+
+**Cons:**
+- Token budgeting is a zero-sum game (more retrieved documents = less conversation history)
+- LLMs often fail to follow given token budgets, especially small ones ("Token Elasticity" phenomenon)
+- Requires empirical tuning of thresholds per model
+
+**Used by:** Claude Code (95% threshold), Anthropic compaction API, TALE framework.
+
+**Multi-agent relevance:** In systems with many concurrent agents, token budget management directly affects infrastructure cost. Agents that use tools heavily (generating large tool outputs) need more aggressive compression than agents that primarily read.
+
+---
+
+## 15. Novel / Emerging Approaches (2024–2026)
+
+### A-MEM (Agentic Memory)
+Zettelkasten-inspired self-organizing memory. Each memory unit (note) is enriched with LLM-generated keywords, tags, contextual descriptions, and dynamically constructed links to related memories. New experiences retroactively refine existing notes. Scales to 1M memories with retrieval time increasing only from 0.31μs to 3.70μs. Doubles performance on complex multi-hop reasoning vs. baselines.
+
+### Subagent Isolation / Multi-Agent Context Splitting
+Instead of compressing one agent's context, split work across multiple agents with isolated context windows. Anthropic reports 90% improvement in task completion with multi-agent vs. single-agent architectures. Each subagent gets a fresh context window, eliminating the compression problem entirely at the cost of coordination overhead.
+
+### Tool Result Clearing
+Lightweight compaction that clears raw tool call results from deep in the message history, since the agent rarely needs to re-read them. No LLM calls needed — cheapest form of compaction.
+
+### MemMachine (2026)
+Ground-truth-preserving memory that stores raw conversational episodes rather than LLM-extracted facts. Achieves ~80% reduction in token usage vs. competing systems by reserving LLM calls only for summarization/abstraction.
+
+### Reflective Memory Management (RMM)
+Constructs memory at adaptive granularities (utterance, turn, session, or topic level) and refines retrieval using feedback from response citations, applying online reinforcement learning to rerank memory relevance.
+
+### Portable Agent Memory (2025)
+A protocol for provenance-verified memory transfer across heterogeneous LLM agents, enabling agents to share memories with verifiable lineage. Addresses the "memory silo" problem in multi-agent systems.
+
+### Nemori
+Autonomously segments conversational streams into semantically aligned episodes and continually updates semantic knowledge via active prediction-calibration loops based on the Free-Energy Principle from neuroscience.
+
+### SSGM (Stability and Safety Governed Memory)
+Addresses risks of evolving memory including silent cross-user contamination of shared stores, memory-induced sycophancy, and self-reinforcing error loops (confirmation bias).
+
+---
+
+## Applicability to cosim
+
+Currently implemented: `none` (stateless) and `fifo` (sliding window). Both in `container/conversation_memory.py` with a pluggable `_STRATEGIES` registry.
+
+The most promising strategies for cosim's multi-agent architecture, in rough priority order:
+
+| Strategy | Complexity | Value | Notes |
+|----------|-----------|-------|-------|
+| Summary + Buffer Hybrid | Medium | High | Best next step — extend FIFO with summary of evicted messages |
+| Pinned Messages | Low | High | Pin persona prompt + Scenario Director instructions in FIFO window |
+| Tool Result Clearing | Low | Medium | Strip tool results from old turns before they enter the FIFO window |
+| Entity Memory | Medium | Medium | Track agents, channels, tickets, docs mentioned across turns |
+| Forgetting Curves | Low | Medium | Weight recent messages higher during FIFO eviction |
+| Episodic + Semantic | High | High | Full Generative Agents-style architecture — high value but complex |
+| MemGPT-style Paging | High | Medium | Requires models capable of reliable self-directed memory management — not suitable for smaller Models.Corp models |
+
+Key constraint: cosim uses multiple LLM backends (Claude, Codex, Granite, Qwen, Llama, Gemini) with varying capabilities. Any memory strategy must work without relying on the model itself to manage memory (rules out MemGPT-style self-directed paging for weaker models). The memory management logic should live in the harness (`modelscorp_agent.py`), not in the model's own reasoning.
+
+---
+
+## References
+
+- Park et al., "Generative Agents: Interactive Simulacra of Human Behavior" (UIST 2023)
+- Packer et al., "MemGPT: Towards LLMs as Operating Systems" (2023)
+- Shinn et al., "Reflexion: Language Agents with Verbal Reinforcement Learning" (NeurIPS 2023)
+- Liu et al., "Lost in the Middle: How Language Models Use Long Contexts" (2024)
+- LangChain memory module documentation
+- CrewAI memory documentation
+- Anthropic, "Effective Context Engineering for AI Agents" (2025)
+- A-MEM: "Agentic Memory for LLM Agents" (NeurIPS 2025)
+- H-MEM: Hierarchical memory architecture (2025)
+- HiMem: Hierarchical episodic + note memory (2026)
+- MemMachine: Ground-truth-preserving memory (2026)
+- Portable Agent Memory protocol (2025)
diff --git a/docs/models-corp-plan.md b/docs/models-corp-plan.md
new file mode 100644
index 0000000..8330cf5
--- /dev/null
+++ b/docs/models-corp-plan.md
@@ -0,0 +1,116 @@
+# Plan: Models.Corp Backend via Custom Python Agent Harness
+
+## Context
+
+The cosim platform currently supports two agent backends — Claude Code CLI and Codex CLI — both running inside podman containers. We want to add a third backend that uses Red Hat's internal **Models.Corp** platform, which exposes OpenAI-compatible `/v1/chat/completions` endpoints for models like Granite 4.0, Qwen3-14B, Gemini, and Claude (proxied via Vertex AI).
+
+Since Models.Corp is a REST API (no CLI tool), we'll write a lightweight Python agent harness that implements the agentic tool-calling loop. This runs inside the same podman containers, using the OpenAI Python SDK for LLM calls and raw JSON-RPC HTTP for MCP tool interaction.
+
+Models.Corp uses **per-model API keys**, so the credential config maps each model to its key and endpoint.
+
+## Files to Create
+
+### 1. `container/modelscorp_agent.py` — Agent loop script (~250 lines)
+
+Runs inside the container. Implements:
+
+- **CLI args**: `--prompt`, `--system-prompt-file`, `--mcp-url`, `--model`, `--max-turns`, `--config`
+- **MCP client** (raw JSON-RPC over HTTP POST to Streamable HTTP endpoint):
+ - `initialize` → get session ID from `mcp-session-id` header
+ - `tools/list` → discover available tools, convert to OpenAI function format
+ - `tools/call` → execute tool calls from LLM responses
+- **Agent loop**:
+ 1. Read system prompt + config
+ 2. Initialize MCP session, fetch tools
+ 3. Convert MCP tools → OpenAI `tools` parameter (JSON Schema mapping is 1:1)
+ 4. Call `client.chat.completions.create()` with messages + tools
+ 5. If response has `tool_calls`: execute each via MCP, append assistant message + tool results to messages, loop back to step 4
+ 6. If no tool_calls or max turns reached: output final result
+ 7. Handle `signal_done` tool calls normally (execute via MCP so orchestrator detects it)
+- **JSONL output** (one JSON object per line to stdout):
+ - `{"type": "turn", "turn": N, "content": "...", "tool_calls": [...]}` — per-turn trace
+ - `{"type": "result", "response_text": "...", "turns": N, "input_tokens": N, "output_tokens": N}` — final summary
+- **Error handling**: Retry on 429 (rate limit) with exponential backoff, fail on auth errors, log to stderr
+
+### 2. `.modelscorp.json.example` — Example credential config
+
+```json
+{
+ "endpoint_base": "YOUR_ENDPOINT_HOST",
+ "endpoint_type": "staging",
+ "models": {
+ "granite-4-0-micro": {"key": "YOUR_KEY_HERE"},
+ "granite-4-0-h-tiny": {"key": "YOUR_KEY_HERE"},
+ "qwen3-14b": {"key": "YOUR_KEY_HERE"},
+ "gemini": {"key": "YOUR_KEY_HERE", "endpoint_type": "production", "base_path": "/v1beta/openai"},
+ "claude": {"key": "YOUR_KEY_HERE"}
+ }
+}
+```
+
+URL construction: `https://{model}--{endpoint_type}.{endpoint_base}:443{base_path}/v1`
+(default `base_path` is empty, so path becomes `/v1`; some models may override the path)
+
+## Files to Modify
+
+### 3. `lib/agent_backends.py` — Add `ModelscorpBackend` class
+
+Add a new class following the same `AgentBackend` protocol as `ClaudeBackend` and `CodexBackend`:
+
+- **`build_exec_command()`**: `podman exec python /home/agent/modelscorp_agent.py --prompt --system-prompt-file /home/agent/system-prompt.md --mcp-url http://{mcp_host}:{mcp_port}/agents-http/{key}/mcp --model --max-turns --config /home/agent/.modelscorp.json`
+- **`parse_output()`**: Parse JSONL looking for `type: "result"` line → extract `response_text`, `turns`, token counts
+- **`generate_config_files()`**: Create system-prompt.md (reuse Claude's approach). Read `.modelscorp.json` from project root and stage it as a config file.
+- **`get_volume_mounts()`**: Mount system-prompt.md and modelscorp config as read-only
+- **`get_credential_sources()`**: Return empty list (credentials are in the config file, mounted as a volume)
+
+Update `get_backend()` factory to handle `agent_type == "modelscorp"`.
+
+### 4. `lib/agent_runner.py` — Add model mappings
+
+Add `_MODELSCORP_MODELS` dict mapping shorthands to Models.Corp model slugs:
+```python
+_MODELSCORP_MODELS = {
+ "granite-micro": "granite-4-0-micro",
+ "granite-tiny": "granite-4-0-h-tiny",
+ "granite-small": "granite-4-0-h-small",
+ "qwen3": "qwen3-14b",
+ "gemini": "gemini",
+ "claude": "claude",
+}
+```
+
+Update `get_model_id()` to handle `agent_type == "modelscorp"`.
+
+### 5. `lib/container_orchestrator.py` — No env var changes needed
+
+Credentials are passed via the config file (volume mount), not env vars. No changes to `_FORWARD_ENV_VARS`.
+
+### 6. `container/Dockerfile.agent` — Install Python dependencies
+
+Add `pip install openai` (httpx comes as a transitive dependency). Copy the agent script:
+```dockerfile
+RUN pip install --no-cache-dir openai
+COPY modelscorp_agent.py /home/agent/modelscorp_agent.py
+```
+
+### 7. `lib/cli.py` — Add "modelscorp" to agent type choices
+
+Update `--default-agent-type` choices from `["claude", "codex"]` to `["claude", "codex", "modelscorp"]`.
+
+### 8. `.gitignore` — Add `.modelscorp.json`
+
+Ensure the credentials file is never committed.
+
+## Architecture Notes
+
+- **MCP transport**: Uses the same Streamable HTTP endpoint as Codex (`/agents-http/{key}/mcp`), speaking JSON-RPC 2.0 over HTTP POST. No new MCP server changes needed.
+- **Tool calling**: Relies on model support for OpenAI-style function calling. Granite 4.0, Qwen3, Claude, and Gemini all support this. Models without tool calling support will get a clear error from the harness.
+- **No sessions for MVP**: Skip session resume support initially. The orchestrator handles this gracefully (falls back to fresh prompts).
+- **Container reuse**: Same long-running container pattern — `sleep infinity` with `podman exec` per turn.
+
+## Verification
+
+1. **Unit test the harness standalone**: Run `modelscorp_agent.py` outside a container against a Models.Corp endpoint with a simple prompt and no MCP tools to verify LLM communication works
+2. **Test MCP integration**: Run with `--mcp-url` pointed at the running MCP server, verify tool discovery and execution
+3. **End-to-end**: Configure a scenario with `agent_type: "modelscorp"` and `model: "granite-micro"` for one character, start the full stack (Flask + MCP + orchestrator), send a message, verify the agent responds through the simulation
+4. **Mixed backends**: Run a scenario with claude, codex, and modelscorp agents in different tiers to verify they coexist
diff --git a/lib/agent_backends.py b/lib/agent_backends.py
index 9cfa9b6..1d98441 100644
--- a/lib/agent_backends.py
+++ b/lib/agent_backends.py
@@ -21,6 +21,7 @@ def build_exec_command(
max_turns: int,
allowed_tools_str: str,
use_sessions: bool = False,
+ fallback_channel: str = "",
) -> list[str]: ...
def parse_output(self, stdout: str) -> tuple[str, str, dict]:
@@ -61,6 +62,7 @@ def build_exec_command(
max_turns: int,
allowed_tools_str: str,
use_sessions: bool = False,
+ fallback_channel: str = "",
) -> list[str]:
cmd = ["podman", "exec", container_name, "claude"]
@@ -75,13 +77,19 @@ def build_exec_command(
cmd += ["--session-id", session_id]
cmd += [
- "--mcp-config", "/home/agent/.mcp-config.json",
- "--allowedTools", allowed_tools_str,
- "--output-format", "stream-json",
+ "--mcp-config",
+ "/home/agent/.mcp-config.json",
+ "--allowedTools",
+ allowed_tools_str,
+ "--output-format",
+ "stream-json",
"--verbose",
- "--model", model_id,
- "--max-turns", str(max_turns),
- "--permission-mode", "dontAsk",
+ "--model",
+ model_id,
+ "--max-turns",
+ str(max_turns),
+ "--permission-mode",
+ "dontAsk",
]
return cmd
@@ -127,9 +135,7 @@ def parse_output(self, stdout: str) -> tuple[str, str, dict]:
summary_parts.append(f"${cost:.4f}")
if summary_parts:
thinking_text = (
- (thinking_text + "\n\n---\n" + ", ".join(summary_parts))
- if thinking_text
- else ", ".join(summary_parts)
+ (thinking_text + "\n\n---\n" + ", ".join(summary_parts)) if thinking_text else ", ".join(summary_parts)
)
return response_text, thinking_text, metadata
@@ -190,6 +196,7 @@ def build_exec_command(
max_turns: int,
allowed_tools_str: str,
use_sessions: bool = False,
+ fallback_channel: str = "",
) -> list[str]:
cmd = ["podman", "exec", container_name, "codex", "exec"]
@@ -200,7 +207,8 @@ def build_exec_command(
"--json",
"--skip-git-repo-check",
"--dangerously-bypass-approvals-and-sandbox",
- "-m", model_id,
+ "-m",
+ model_id,
]
if not use_sessions:
@@ -261,7 +269,7 @@ def generate_config_files(
mcp_port: int,
tmp_dir: Path,
) -> dict[str, Path]:
- escaped = system_prompt.replace('\\', '\\\\').replace('"', '\\"')
+ escaped = system_prompt.replace("\\", "\\\\").replace('"', '\\"')
lines = [
f'instructions = """\n{escaped}\n"""',
"",
@@ -285,8 +293,142 @@ def get_credential_sources(self) -> list[tuple[str, str]]:
return []
+class ModelscorpBackend:
+ """Models.Corp backend — custom Python agent harness with OpenAI-compatible API."""
+
+ def __init__(self) -> None:
+ self._mcp_urls: dict[str, str] = {}
+ self._allowed_tools: dict[str, list[str]] = {}
+ self._memory_configs: dict[str, dict] = {}
+
+ def set_allowed_tools(self, persona_key: str, tools: list[str]) -> None:
+ self._allowed_tools[persona_key] = tools
+
+ def set_memory_config(self, persona_key: str, config: dict) -> None:
+ self._memory_configs[persona_key] = config
+
+ def build_exec_command(
+ self,
+ container_name: str,
+ turn_prompt: str,
+ *,
+ resuming: bool = False,
+ session_id: str | None = None,
+ model_id: str,
+ max_turns: int,
+ allowed_tools_str: str,
+ use_sessions: bool = False,
+ fallback_channel: str = "",
+ ) -> list[str]:
+ persona_key = container_name.removeprefix("agent-")
+ mcp_url = self._mcp_urls.get(persona_key, "")
+ cmd = [
+ "podman",
+ "exec",
+ container_name,
+ "cosim-agent",
+ "--prompt",
+ turn_prompt,
+ "--system-prompt-file",
+ "/home/agent/system-prompt.md",
+ "--mcp-url",
+ mcp_url,
+ "--model",
+ model_id,
+ "--max-turns",
+ str(max_turns),
+ "--config",
+ "/home/agent/.modelscorp.json",
+ ]
+ agent_tools = self._allowed_tools.get(persona_key)
+ if agent_tools:
+ cmd += ["--allowed-tools", ",".join(agent_tools)]
+ if use_sessions and session_id:
+ mem_cfg = self._memory_configs.get(persona_key) or {"strategy": "fifo", "max_messages": 50}
+ mem_cfg_with_session = {**mem_cfg, "session_file": f"/home/agent/sessions/{session_id}.jsonl"}
+ cmd += ["--memory-config", json.dumps(mem_cfg_with_session)]
+ if fallback_channel:
+ cmd += ["--fallback-channel", fallback_channel]
+ return cmd
+
+ def parse_output(self, stdout: str) -> tuple[str, str, dict]:
+ response_text = ""
+ metadata: dict = {}
+
+ if not stdout.strip():
+ return response_text, "", metadata
+
+ for line in stdout.strip().split("\n"):
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ obj = json.loads(line)
+ except (json.JSONDecodeError, ValueError):
+ continue
+ if obj.get("type") == "result":
+ response_text = obj.get("response_text", "")
+ metadata["num_turns"] = obj.get("turns", 0)
+ metadata["usage"] = {
+ "input_tokens": obj.get("input_tokens", 0),
+ "output_tokens": obj.get("output_tokens", 0),
+ }
+ if obj.get("error"):
+ metadata["error"] = obj["error"]
+
+ summary_parts = []
+ if metadata.get("num_turns"):
+ summary_parts.append(f"{metadata['num_turns']} turn(s)")
+ out_tokens = metadata.get("usage", {}).get("output_tokens", 0)
+ if out_tokens:
+ summary_parts.append(f"{out_tokens} output tokens")
+ thinking_text = ", ".join(summary_parts) if summary_parts else ""
+
+ return response_text, thinking_text, metadata
+
+ def generate_config_files(
+ self,
+ persona_key: str,
+ system_prompt: str,
+ mcp_host: str,
+ mcp_port: int,
+ tmp_dir: Path,
+ ) -> dict[str, Path]:
+ prompt_path = tmp_dir / f"system-prompt-{persona_key}.md"
+ prompt_path.write_text(system_prompt)
+
+ project_config = Path(__file__).parent.parent / ".modelscorp.json"
+ if project_config.is_file():
+ staged = tmp_dir / f"modelscorp-config-{persona_key}.json"
+ staged.write_text(project_config.read_text())
+ else:
+ staged = tmp_dir / f"modelscorp-config-{persona_key}.json"
+ staged.write_text("{}")
+
+ mcp_url = f"http://{mcp_host}:{mcp_port}/agents-http/{persona_key}/mcp"
+ self._mcp_urls[persona_key] = mcp_url
+
+ return {
+ "system_prompt": prompt_path,
+ "modelscorp_config": staged,
+ }
+
+ def get_volume_mounts(self, config_files: dict[str, Path]) -> list[str]:
+ mounts: list[str] = []
+ if "system_prompt" in config_files:
+ mounts += ["-v", f"{config_files['system_prompt'].resolve()}:/home/agent/system-prompt.md:ro,Z"]
+ if "modelscorp_config" in config_files:
+ mounts += ["-v", f"{config_files['modelscorp_config'].resolve()}:/home/agent/.modelscorp.json:ro,Z"]
+ return mounts
+
+ def get_credential_sources(self) -> list[tuple[str, str]]:
+ return []
+
+
def get_backend(agent_type: str) -> AgentBackend:
"""Factory for agent backends."""
if agent_type == "codex":
return CodexBackend()
+ if agent_type == "modelscorp":
+ return ModelscorpBackend()
return ClaudeBackend()
diff --git a/lib/agent_runner.py b/lib/agent_runner.py
index a7e5921..aabe562 100644
--- a/lib/agent_runner.py
+++ b/lib/agent_runner.py
@@ -30,11 +30,23 @@ def get_model_display_name(model_shorthand: str) -> str:
"gpt-5.5": "gpt-5.5",
}
+_MODELSCORP_MODELS = {
+ "granite-micro": "granite-4-0-micro",
+ "granite-tiny": "granite-4-0-h-tiny",
+ "granite-small": "granite-4-0-h-small",
+ "qwen3": "qwen3-14b",
+ "llama-70b": "llama-3-3-70b-instruct-fp8-dynamic",
+ "gemini": "gemini",
+ "claude": "claude",
+}
+
def get_model_id(model_shorthand: str, agent_type: str = "claude") -> str:
"""Convert model shorthand to full model ID."""
if agent_type == "codex":
return _CODEX_MODELS.get(model_shorthand, model_shorthand)
+ if agent_type == "modelscorp":
+ return _MODELSCORP_MODELS.get(model_shorthand, model_shorthand)
return _CLAUDE_MODELS.get(model_shorthand, model_shorthand)
diff --git a/lib/cli.py b/lib/cli.py
index 3baa21d..6ab677a 100644
--- a/lib/cli.py
+++ b/lib/cli.py
@@ -62,7 +62,7 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
"--default-agent-type",
type=str,
default="claude",
- choices=["claude", "codex"],
+ choices=["claude", "codex", "modelscorp"],
help="Default agent CLI backend when not specified per-character (default: claude)",
)
chat_parser.add_argument(
@@ -142,10 +142,10 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
)
chat_parser.add_argument(
"--use-sessions",
- action="store_true",
- default=False,
- help="Persist Claude Code sessions across agent turns (agents resume "
- "prior context instead of rebuilding full prompts)",
+ action=argparse.BooleanOptionalAction,
+ default=True,
+ help="Persist agent sessions across turns (Claude resumes, Codex "
+ "resumes threads, Models.Corp uses FIFO memory). Disable with --no-use-sessions.",
)
# ── job-runner subcommand ──────────────────────────────────────────
diff --git a/lib/container_orchestrator.py b/lib/container_orchestrator.py
index 40a8156..379c92b 100644
--- a/lib/container_orchestrator.py
+++ b/lib/container_orchestrator.py
@@ -18,7 +18,7 @@
import requests as sync_requests
-from lib.agent_backends import ClaudeBackend, CodexBackend, get_backend
+from lib.agent_backends import ClaudeBackend, CodexBackend, ModelscorpBackend, get_backend
from lib.agent_runner import format_duration, get_model_id
from lib.chat_client import ChatClient
from lib.personas import (
@@ -308,7 +308,7 @@ async def _preflight_checks(container_image: str) -> None:
raise RuntimeError(
f"Container image '{container_image}' not found.\n"
f" Build it first: ./scripts/build-agent-image.sh\n"
- f" Or manually: podman build -t {container_image} -f container/Dockerfile.agent container/"
+ f" Or manually: podman build -t {container_image} -f container/Dockerfile.agent ."
)
print(f" image: {container_image}")
@@ -362,14 +362,16 @@ def __init__(
# Resolve per-agent backend
settings = get_settings()
- self._backends: dict[str, ClaudeBackend | CodexBackend] = {}
+ self._backends: dict[str, ClaudeBackend | CodexBackend | ModelscorpBackend] = {}
for key, persona in self._personas.items():
- agent_type = (
- persona.get("agent_type")
- or settings.get("default_agent_type")
- or default_agent_type
- )
- self._backends[key] = get_backend(agent_type)
+ agent_type = persona.get("agent_type") or settings.get("default_agent_type") or default_agent_type
+ backend = get_backend(agent_type)
+ if isinstance(backend, ModelscorpBackend):
+ if persona.get("allowed_tools"):
+ backend.set_allowed_tools(key, persona["allowed_tools"])
+ if persona.get("memory"):
+ backend.set_memory_config(key, persona["memory"])
+ self._backends[key] = backend
async def start(self, build_system_prompt_fn, on_progress=None) -> None:
"""Validate prerequisites, generate configs, and launch long-running containers.
@@ -407,11 +409,20 @@ async def start(self, build_system_prompt_fn, on_progress=None) -> None:
backend = self._backends[key]
prompt_content = build_system_prompt_fn(key)
self._backend_configs[key] = backend.generate_config_files(
- key, prompt_content, self._mcp_host, self._mcp_port, TMP_DIR,
+ key,
+ prompt_content,
+ self._mcp_host,
+ self._mcp_port,
+ TMP_DIR,
)
# Initialize log file
- agent_type = "codex" if isinstance(backend, CodexBackend) else "claude"
+ if isinstance(backend, CodexBackend):
+ agent_type = "codex"
+ elif isinstance(backend, ModelscorpBackend):
+ agent_type = "modelscorp"
+ else:
+ agent_type = "claude"
effective_model = persona.get("model") or self._default_model
effective_model_id = get_model_id(effective_model, agent_type)
log_file = self._log_dir / f"{display_name.replace('/', '_').replace(' ', '_')}.log"
@@ -429,6 +440,11 @@ async def start(self, build_system_prompt_fn, on_progress=None) -> None:
# Create per-agent lock
self._agent_locks[key] = asyncio.Lock()
+ # Pre-assign session IDs for backends that support conversation memory
+ if self._use_sessions and key not in self._session_ids:
+ if isinstance(backend, (ClaudeBackend, ModelscorpBackend)):
+ self._session_ids[key] = str(_uuid.uuid4())
+
print(f" ready ({i}/{total})")
if on_progress:
@@ -447,7 +463,10 @@ async def _launch_container(self, persona_key: str) -> None:
# Cleanup leftover container from previous session
rm_proc = await asyncio.create_subprocess_exec(
- "podman", "rm", "-f", container_name,
+ "podman",
+ "rm",
+ "-f",
+ container_name,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
@@ -458,11 +477,17 @@ async def _launch_container(self, persona_key: str) -> None:
# Launch long-running container (CMD from Dockerfile: sleep infinity)
cmd = [
- "podman", "run", "-d",
- "--name", container_name,
- "-e", f"AGENT_PERSONA_KEY={persona_key}",
- "-e", f"MCP_SERVER_URL={self._mcp_host}:{self._mcp_port}",
- "-e", "GCE_METADATA_HOST=127.0.0.1",
+ "podman",
+ "run",
+ "-d",
+ "--name",
+ container_name,
+ "-e",
+ f"AGENT_PERSONA_KEY={persona_key}",
+ "-e",
+ f"MCP_SERVER_URL={self._mcp_host}:{self._mcp_port}",
+ "-e",
+ "GCE_METADATA_HOST=127.0.0.1",
*self._env_flags,
*volume_flags,
self._container_image,
@@ -479,8 +504,12 @@ async def _launch_container(self, persona_key: str) -> None:
# Verify container is running
check_proc = await asyncio.create_subprocess_exec(
- "podman", "container", "inspect", container_name,
- "--format", "{{.State.Status}}",
+ "podman",
+ "container",
+ "inspect",
+ container_name,
+ "--format",
+ "{{.State.Status}}",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
@@ -496,14 +525,22 @@ async def _launch_container(self, persona_key: str) -> None:
if self._gcp_creds_path and isinstance(backend, ClaudeBackend):
creds_dest = f"{container_name}:/home/agent/.config/gcloud/application_default_credentials.json"
cp_proc = await asyncio.create_subprocess_exec(
- "podman", "cp", self._gcp_creds_path, creds_dest,
+ "podman",
+ "cp",
+ self._gcp_creds_path,
+ creds_dest,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
await cp_proc.communicate()
chown_proc = await asyncio.create_subprocess_exec(
- "podman", "exec", "--user", "root", container_name,
- "chown", "agent:agent",
+ "podman",
+ "exec",
+ "--user",
+ "root",
+ container_name,
+ "chown",
+ "agent:agent",
"/home/agent/.config/gcloud/application_default_credentials.json",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
@@ -514,7 +551,10 @@ async def _launch_container(self, persona_key: str) -> None:
staged = TMP_DIR / f"cred-{persona_key}-{Path(src_path).name}"
shutil.copy2(src_path, staged)
cp_proc = await asyncio.create_subprocess_exec(
- "podman", "cp", str(staged), f"{container_name}:{dest_path}",
+ "podman",
+ "cp",
+ str(staged),
+ f"{container_name}:{dest_path}",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
@@ -523,8 +563,15 @@ async def _launch_container(self, persona_key: str) -> None:
# Fix ownership for codex home directory
if isinstance(backend, CodexBackend):
chown_proc = await asyncio.create_subprocess_exec(
- "podman", "exec", "--user", "root", container_name,
- "chown", "-R", "agent:agent", "/home/agent/.codex/",
+ "podman",
+ "exec",
+ "--user",
+ "root",
+ container_name,
+ "chown",
+ "-R",
+ "agent:agent",
+ "/home/agent/.codex/",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
@@ -569,16 +616,23 @@ async def _run_agent_inner(self, persona_key: str, turn_prompt: str) -> dict:
resuming = self._use_sessions and persona_key in self._session_started
- # For Claude: pre-assign session UUID; for Codex: captured from output
- if self._use_sessions and persona_key not in self._session_ids:
- if isinstance(backend, ClaudeBackend):
- self._session_ids[persona_key] = str(_uuid.uuid4())
-
# Resolve per-agent model
- agent_type = "codex" if isinstance(backend, CodexBackend) else "claude"
+ if isinstance(backend, CodexBackend):
+ agent_type = "codex"
+ elif isinstance(backend, ModelscorpBackend):
+ agent_type = "modelscorp"
+ else:
+ agent_type = "claude"
effective_model = persona.get("model") or self._default_model
effective_model_id = get_model_id(effective_model, agent_type)
+ fallback_ch = ""
+ if persona.get("fallback_channel") or agent_type == "modelscorp":
+ import re as _re
+
+ m = _re.search(r"new activity in (#\S+)", turn_prompt)
+ fallback_ch = m.group(1).rstrip(".,") if m else persona.get("fallback_channel", "")
+
cmd = backend.build_exec_command(
container_name=container_name,
turn_prompt=turn_prompt,
@@ -588,6 +642,7 @@ async def _run_agent_inner(self, persona_key: str, turn_prompt: str) -> dict:
max_turns=self._max_turns,
allowed_tools_str=self._allowed_tools_str,
use_sessions=self._use_sessions,
+ fallback_channel=fallback_ch,
)
# Log the actual command for debugging
@@ -804,6 +859,9 @@ async def _process_single_command(client, pool, personas, scenario_name, cmd):
"character_file": npc_data.get("character_file", ""),
"agent_type": npc_data.get("agent_type"),
"model": npc_data.get("model"),
+ "allowed_tools": npc_data.get("allowed_tools"),
+ "fallback_channel": npc_data.get("fallback_channel", ""),
+ "memory": npc_data.get("memory"),
}
PERSONAS[agent_key] = persona
DEFAULT_MEMBERSHIPS[agent_key] = set(npc_data.get("channels", ["#general"]))
@@ -816,18 +874,26 @@ async def _process_single_command(client, pool, personas, scenario_name, cmd):
# Resolve backend for new agent
from lib.scenario_loader import get_settings
+
agent_type = (
- persona.get("agent_type")
- or get_settings().get("default_agent_type")
- or pool._default_agent_type
+ persona.get("agent_type") or get_settings().get("default_agent_type") or pool._default_agent_type
)
backend = get_backend(agent_type)
+ if isinstance(backend, ModelscorpBackend):
+ if persona.get("allowed_tools"):
+ backend.set_allowed_tools(agent_key, persona["allowed_tools"])
+ if persona.get("memory"):
+ backend.set_memory_config(agent_key, persona["memory"])
pool._backends[agent_key] = backend
# Generate config files via backend
prompt_content = build_v3_system_prompt(agent_key)
pool._backend_configs[agent_key] = backend.generate_config_files(
- agent_key, prompt_content, pool._mcp_host, pool._mcp_port, TMP_DIR,
+ agent_key,
+ prompt_content,
+ pool._mcp_host,
+ pool._mcp_port,
+ TMP_DIR,
)
# Register MCP endpoints for the new agent on the MCP server
@@ -848,9 +914,23 @@ async def _process_single_command(client, pool, personas, scenario_name, cmd):
print(f" Warning: failed to register MCP endpoints for {agent_key}: {e}")
# Launch long-running container and create lock
- await pool._launch_container(agent_key)
+ try:
+ await pool._launch_container(agent_key)
+ except Exception as e:
+ print(f" Failed to launch container for {agent_key}: {e}")
+ pool._personas.pop(agent_key, None)
+ pool._backends.pop(agent_key, None)
+ pool._backend_configs.pop(agent_key, None)
+ PERSONAS.pop(agent_key, None)
+ DEFAULT_MEMBERSHIPS.pop(agent_key, None)
+ return list(pool._personas.values()), False
pool._agent_locks[agent_key] = asyncio.Lock()
+ # Assign session ID (mirrors pool.start() logic)
+ if pool._use_sessions and agent_key not in pool._session_ids:
+ if isinstance(backend, (ClaudeBackend, ModelscorpBackend)):
+ pool._session_ids[agent_key] = str(_uuid.uuid4())
+
personas = list(pool._personas.values())
client.post_message("System", f"{persona['display_name']} has joined the team!", channel="#system")
print(f" Agent added: {persona['display_name']}")
@@ -1166,9 +1246,29 @@ async def _run_agent(pk, trigger_ch_set):
# Reset agent statuses after tier
agents_status = _build_agent_status(personas, pool)
- client.send_heartbeat(
- "responding", scenario_name, agents_status, "Processing messages...", check_commands=False
- )
+
+ # Process add_agent commands between tiers so newly hired
+ # agents are in the pool before the next wave starts.
+ while True:
+ cmd_resp = client.send_heartbeat("responding", scenario_name, agents_status, "Processing messages...")
+ cmd_action = cmd_resp.get("action")
+ if cmd_action == "add_agent":
+ print(f" Inter-tier add_agent: {cmd_resp.get('key')}")
+ personas, _ = await _process_single_command(client, pool, personas, scenario_name, cmd_resp)
+ persona_map = {p["name"]: p for p in personas}
+ agents_status = _build_agent_status(personas, pool)
+ else:
+ if cmd_action and cmd_action not in ("add_agent",):
+ # Re-queue non-add commands for later
+ try:
+ sync_requests.post(
+ f"{client.base_url}/api/orchestrator/command",
+ json=cmd_resp,
+ timeout=5,
+ )
+ except Exception:
+ pass
+ break
# Update per-agent last_seen to current high-water mark
all_latest = client.get_messages()
@@ -1502,6 +1602,34 @@ def on_progress_restart(i, tot, key, display_name, state):
personas, restart = await _process_pending_commands(client, pool, personas, scenario_name)
if restart:
continue
+
+ # Catch-up: newly added agents may have unread messages in
+ # their channels (posted by judges during a prior cycle).
+ # Trigger a response loop so they actually respond.
+ catch_up_channels = set()
+ memberships = _get_channel_memberships(client)
+ all_messages = client.get_messages()
+ msg_channels = {m.get("channel") for m in all_messages}
+ for pk in pool._personas:
+ if agent_last_seen.get(pk, 0) == 0:
+ for ch, members in memberships.items():
+ if pk in members and ch in msg_channels:
+ catch_up_channels.add(ch)
+ if catch_up_channels:
+ print(f"\n Catch-up: triggering newly added agents in {sorted(catch_up_channels)}")
+ active_channels = await _run_loop(
+ client,
+ pool,
+ personas,
+ catch_up_channels,
+ max_waves,
+ scenario_name,
+ max_concurrent,
+ agent_last_seen,
+ )
+ latest = client.get_messages()
+ if latest:
+ last_seen_id = latest[-1]["id"]
continue
new_messages = client.get_messages(since=last_seen_id)
@@ -1550,8 +1678,7 @@ def on_progress_restart(i, tot, key, display_name, state):
try:
blog_posts = client.get_blog_posts()
new_blog_replies = [
- p for p in blog_posts
- if p.get("last_reply_at") and p["last_reply_at"] > last_blog_check_ts
+ p for p in blog_posts if p.get("last_reply_at") and p["last_reply_at"] > last_blog_check_ts
]
if new_blog_replies:
last_blog_check_ts = max(p["last_reply_at"] for p in new_blog_replies)
@@ -1567,25 +1694,19 @@ def on_progress_restart(i, tot, key, display_name, state):
try:
tickets = client.list_tickets()
new_ticket_activity = [
- t for t in tickets
- if t.get("updated_at") and t["updated_at"] > last_ticket_check_ts
+ t for t in tickets if t.get("updated_at") and t["updated_at"] > last_ticket_check_ts
]
if new_ticket_activity:
last_ticket_check_ts = max(t["updated_at"] for t in new_ticket_activity)
print(f"\nTicket activity detected on {len(new_ticket_activity)} ticket(s)")
- hints.append(
- "Tickets have been updated. Use get_my_tickets() or list_tickets() to check."
- )
+ hints.append("Tickets have been updated. Use get_my_tickets() or list_tickets() to check.")
except Exception as e:
print(f"Ticket activity check failed: {e}")
# Document creates/updates
try:
docs = client.list_docs()
- new_doc_activity = [
- d for d in docs
- if d.get("updated_at") and d["updated_at"] > last_doc_check_ts
- ]
+ new_doc_activity = [d for d in docs if d.get("updated_at") and d["updated_at"] > last_doc_check_ts]
if new_doc_activity:
last_doc_check_ts = max(d["updated_at"] for d in new_doc_activity)
print(f"\nDocument activity detected on {len(new_doc_activity)} doc(s)")
@@ -1599,15 +1720,12 @@ def on_progress_restart(i, tot, key, display_name, state):
try:
emails = client.get_emails()
new_email_activity = [
- e for e in emails
- if e.get("timestamp") and e["timestamp"] > last_email_check_ts
+ e for e in emails if e.get("timestamp") and e["timestamp"] > last_email_check_ts
]
if new_email_activity:
last_email_check_ts = max(e["timestamp"] for e in new_email_activity)
print(f"\nNew email(s) detected: {len(new_email_activity)}")
- hints.append(
- "New company emails have arrived. Use get_emails() to read them."
- )
+ hints.append("New company emails have arrived. Use get_emails() to read them.")
except Exception as e:
print(f"Email activity check failed: {e}")
@@ -1615,15 +1733,12 @@ def on_progress_restart(i, tot, key, display_name, state):
try:
memo_threads = client.get_memo_threads()
new_memo_activity = [
- t for t in memo_threads
- if t.get("last_post_at") and t["last_post_at"] > last_memo_check_ts
+ t for t in memo_threads if t.get("last_post_at") and t["last_post_at"] > last_memo_check_ts
]
if new_memo_activity:
last_memo_check_ts = max(t["last_post_at"] for t in new_memo_activity)
print(f"\nMemo activity detected on {len(new_memo_activity)} thread(s)")
- hints.append(
- "There are new memo replies. Use list_memos() and get_memo_thread() to check."
- )
+ hints.append("There are new memo replies. Use list_memos() and get_memo_thread() to check.")
except Exception as e:
print(f"Memo activity check failed: {e}")
diff --git a/lib/mcp_server.py b/lib/mcp_server.py
index 0884190..0563255 100644
--- a/lib/mcp_server.py
+++ b/lib/mcp_server.py
@@ -127,6 +127,10 @@ def _register_communication_tools(
# Auto-add director channel (created dynamically by Flask, not in scenario YAML)
my_channels.add(f"#director-{agent_key}")
+ def _normalize_channel(channel: str) -> str:
+ """Ensure channel name starts with #. Some models drop the prefix."""
+ return channel if channel.startswith("#") else f"#{channel}"
+
@server.tool(
name="list_channels",
description="List all available chat channels with their descriptions and member counts.",
@@ -142,6 +146,7 @@ async def list_channels() -> str:
description="Post a message to a chat channel you belong to.",
)
async def post_message(channel: str, content: str) -> str:
+ channel = _normalize_channel(channel)
if channel not in my_channels:
return f"Error: you are not a member of {channel}. Your channels: {sorted(my_channels)}"
t0 = time.time()
@@ -165,6 +170,7 @@ async def post_message(channel: str, content: str) -> str:
description="Get recent messages from a channel you belong to. Use since_id to get only newer messages.",
)
async def get_messages(channel: str, since_id: int = 0, limit: int = 50) -> str:
+ channel = _normalize_channel(channel)
if channel not in my_channels:
return f"Error: you are not a member of {channel}. Your channels: {sorted(my_channels)}"
t0 = time.time()
@@ -227,6 +233,7 @@ async def get_my_dms(since_id: int = 0) -> str:
description="Join a chat channel. You will then be able to read and post messages there.",
)
async def join_channel(channel: str) -> str:
+ channel = _normalize_channel(channel)
t0 = time.time()
encoded = channel.lstrip("#")
result = await _flask(
@@ -247,6 +254,7 @@ async def join_channel(channel: str) -> str:
description="Get the list of members in a channel.",
)
async def get_channel_members(channel: str) -> str:
+ channel = _normalize_channel(channel)
t0 = time.time()
channels_list = await _flask("GET", "/api/channels", flask_url)
for ch in channels_list:
@@ -1259,21 +1267,20 @@ async def get_recent_activity(since_minutes: int = 30) -> str:
# Fetch recent memos
all_memos = await _flask("GET", "/api/memos/threads", flask_url, params={"include_posts": "1"})
recent_memos = [
- t for t in all_memos
+ t
+ for t in all_memos
if t.get("created_at", 0) > cutoff or t.get("last_post_at", 0) and t["last_post_at"] > cutoff
]
# Fetch recent emails
all_emails = await _flask("GET", "/api/emails", flask_url)
- recent_emails = [
- e for e in all_emails
- if e.get("timestamp", 0) > cutoff
- ]
+ recent_emails = [e for e in all_emails if e.get("timestamp", 0) > cutoff]
# Fetch recent blog posts with replies
all_blog_posts = await _flask("GET", "/api/blog/posts", flask_url, params={"include_replies": "1"})
recent_blog = [
- p for p in all_blog_posts
+ p
+ for p in all_blog_posts
if p.get("created_at", 0) > cutoff or p.get("last_reply_at", 0) and p["last_reply_at"] > cutoff
]
@@ -1392,7 +1399,8 @@ async def list_team_members() -> str:
name="hire_agent",
description=(
"Hire a new team member. Creates a new agent with the given persona and starts their container. "
- "The key must be lowercase with no spaces. The prompt is the character instruction text."
+ "The key must be lowercase with no spaces. The prompt is the character instruction text. "
+ 'Use memory to configure conversation memory strategy (e.g. {"strategy": "fifo", "max_messages": 20}).'
),
)
async def hire_agent(
@@ -1405,6 +1413,8 @@ async def hire_agent(
folders: list[str] | None = None,
agent_type: str | None = None,
model: str | None = None,
+ memory: dict | None = None,
+ allowed_tools: list[str] | None = None,
) -> str:
t0 = time.time()
payload: dict[str, Any] = {
@@ -1420,6 +1430,11 @@ async def hire_agent(
payload["agent_type"] = agent_type
if model:
payload["model"] = model
+ if memory:
+ payload["memory"] = memory
+ if allowed_tools:
+ payload["allowed_tools"] = allowed_tools
+ payload["hired_by"] = agent_key
try:
result = await _flask("POST", "/api/npcs/hire", flask_url, json=payload)
except httpx.HTTPStatusError as e:
@@ -1463,6 +1478,9 @@ def create_agent_mcp(
# Disable DNS rebinding protection — containers connect via gateway IP
# or host.containers.internal, not 127.0.0.1
transport_security=TransportSecuritySettings(enable_dns_rebinding_protection=False),
+ # Return plain JSON instead of SSE streams for Streamable HTTP POST
+ # responses — the Models.Corp agent harness uses simple httpx POST calls.
+ json_response=True,
)
reg_args = (server, agent_key, display_name, flask_url, config)
@@ -1677,11 +1695,9 @@ async def _remove_agent_endpoint(request: Request) -> JSONResponse:
return JSONResponse({"error": "missing 'key'"}, status_code=400)
request.app.routes[:] = [
- r for r in request.app.routes
- if not (
- isinstance(r, Mount)
- and (r.path == f"/agents/{agent_key}" or r.path == f"/agents-http/{agent_key}")
- )
+ r
+ for r in request.app.routes
+ if not (isinstance(r, Mount) and (r.path == f"/agents/{agent_key}" or r.path == f"/agents-http/{agent_key}"))
]
agent_keys = getattr(request.app.state, "agent_keys", [])
@@ -1717,7 +1733,8 @@ async def _load_scenario_endpoint(request: Request) -> JSONResponse:
# Remove any previously mounted agent routes
request.app.routes[:] = [
- r for r in request.app.routes
+ r
+ for r in request.app.routes
if not (isinstance(r, Mount) and (r.path.startswith("/agents/") or r.path.startswith("/agents-http/")))
]
diff --git a/lib/personas.py b/lib/personas.py
index d269a64..38a2462 100644
--- a/lib/personas.py
+++ b/lib/personas.py
@@ -482,6 +482,7 @@ def build_initial_prompt(persona_key: str, channels: dict[str, dict] | None = No
# External channel description and participants from scenario settings
from lib.scenario_loader import get_settings
+
_settings = get_settings()
ext_channel_desc = _settings.get(
"external_channel_prompt",
@@ -757,6 +758,7 @@ def build_turn_prompt(
if is_external:
from lib.scenario_loader import get_settings
+
_ext_prompt = get_settings().get(
"external_channel_prompt",
"This is an external channel visible to people outside your team. "
@@ -942,6 +944,7 @@ def build_v3_system_prompt(persona_key: str, channels: dict[str, dict] | None =
# External channel description and participants from scenario settings
from lib.scenario_loader import get_settings
+
_settings = get_settings()
ext_channel_desc = _settings.get(
"external_channel_prompt",
@@ -980,7 +983,7 @@ def build_v3_system_prompt(persona_key: str, channels: dict[str, dict] | None =
**Do NOT speak for other team members.** You do not know what they think. Let them speak for themselves — they are active participants and will respond if they have something to say. Only speak from your own perspective and role.
-**Stay in your lane.** Your character description defines your expertise. Speak with depth and authority on topics in your domain — that is what you are here for. On topics outside your domain, do nothing and let the expert handle it. Do not offer surface-level opinions on areas where another team member is the clear owner. If you catch yourself writing "from a [not-your-role] perspective," stop — that is someone else's job. Trust your teammates to cover their areas.
+**Be honest about what you know.** Engage with any topic you can contribute to meaningfully. If you don't know something, say so — don't bluff. Don't offer shallow takes just to participate. Silence is better than noise.
**COMPRESSED TIME — ACT NOW, NOT LATER.**
@@ -1067,7 +1070,7 @@ def build_v3_turn_prompt(
# Extract team description for role context
team_desc = persona.get("team_description", "")
- role_hint = f" Your expertise is in {team_desc}." if team_desc else ""
+ role_hint = f" Your style: {team_desc}." if team_desc else ""
# If triggered by a director channel, hint that it's a private conversation
director_channels = {ch for ch in trigger_channels if ch.startswith("#director-")}
diff --git a/lib/scenario_loader.py b/lib/scenario_loader.py
index c9d1c03..5cd9880 100644
--- a/lib/scenario_loader.py
+++ b/lib/scenario_loader.py
@@ -21,6 +21,7 @@ def _parse_frontmatter(text: str) -> dict:
SCENARIO_SETTINGS: dict = {}
+SEED_DOCUMENTS: list[dict] = []
def get_settings() -> dict:
@@ -48,6 +49,8 @@ def load_scenario(scenario_name: str) -> None:
# --- Populate personas.PERSONAS ---
personas_mod.PERSONAS.clear()
for key, char_info in config["characters"].items():
+ if char_info.get("enabled") is False:
+ continue
char_file = char_info.get("character_file")
if not char_file:
# Default: try .CS.md first, fall back to .md
@@ -68,6 +71,9 @@ def load_scenario(scenario_name: str) -> None:
"avatar": char_info.get("avatar"),
"agent_type": char_info.get("agent_type"),
"model": char_info.get("model"),
+ "allowed_tools": char_info.get("allowed_tools"),
+ "fallback_channel": char_info.get("fallback_channel", ""),
+ "memory": char_info.get("memory"),
}
# --- Populate personas.DEFAULT_CHANNELS ---
@@ -115,6 +121,14 @@ def load_scenario(scenario_name: str) -> None:
SCENARIO_SETTINGS.clear()
SCENARIO_SETTINGS.update(config.get("settings", {}))
+ # --- Populate SEED_DOCUMENTS (optional) ---
+ SEED_DOCUMENTS.clear()
+ for doc in config.get("documents", []):
+ source = doc.get("file", "")
+ if source:
+ doc["_source_path"] = str(scenario_dir / source)
+ SEED_DOCUMENTS.append(doc)
+
print(f"Scenario loaded: {config.get('name', scenario_name)}")
print(f" Characters: {len(personas_mod.PERSONAS)}")
print(f" Channels: {len(personas_mod.DEFAULT_CHANNELS)}")
diff --git a/lib/session.py b/lib/session.py
index dbe6b8f..d77e023 100644
--- a/lib/session.py
+++ b/lib/session.py
@@ -116,6 +116,9 @@ def _get_roster() -> dict:
"verbosity": verbosity,
"agent_type": p.get("agent_type"),
"model": p.get("model"),
+ "allowed_tools": p.get("allowed_tools"),
+ "fallback_channel": p.get("fallback_channel", ""),
+ "memory": p.get("memory"),
}
return roster
@@ -331,6 +334,9 @@ def load_session(instance_name: str) -> dict:
"character_file": data.get("character_file", ""),
"agent_type": data.get("agent_type"),
"model": data.get("model"),
+ "allowed_tools": data.get("allowed_tools"),
+ "fallback_channel": data.get("fallback_channel", ""),
+ "memory": data.get("memory"),
}
DEFAULT_MEMBERSHIPS[key] = set(data.get("channels", ["#general"]))
tier = data.get("tier", 1)
diff --git a/lib/webapp/helpers.py b/lib/webapp/helpers.py
index e292db8..d3e3796 100644
--- a/lib/webapp/helpers.py
+++ b/lib/webapp/helpers.py
@@ -226,6 +226,24 @@ def _broadcast_channel_update(channel_name: str, members: list[str]):
_subscribers.remove(q)
+def _broadcast_channel_created(channel_info: dict):
+ """Notify SSE subscribers that a new channel was created."""
+ import queue as _queue
+
+ payload = {"type": "channel_created"}
+ payload.update(channel_info)
+ data = json.dumps(payload)
+ with _sub_lock:
+ dead = []
+ for q in _subscribers:
+ try:
+ q.put_nowait(data)
+ except _queue.Full:
+ dead.append(q)
+ for q in dead:
+ _subscribers.remove(q)
+
+
# -- Document storage helpers --
@@ -240,13 +258,36 @@ def _init_folders():
def _init_docs():
- """Create docs/ dir with folder subdirs and load or migrate index."""
+ """Create docs/ dir with folder subdirs, seed scenario docs, and load or migrate index."""
+ from pathlib import Path
+
+ from lib.docs import slugify
+ from lib.scenario_loader import SEED_DOCUMENTS
+
DOCS_DIR.mkdir(parents=True, exist_ok=True)
# Create subdirectories for each folder (parents=True for nested paths)
for folder_name in DEFAULT_FOLDERS:
(DOCS_DIR / folder_name).mkdir(parents=True, exist_ok=True)
+ # Seed documents from scenario definition
+ for doc in SEED_DOCUMENTS:
+ folder = doc.get("folder", "shared")
+ title = doc.get("title", "")
+ source_path = doc.get("_source_path", "")
+ if not title or not source_path:
+ continue
+ src = Path(source_path)
+ if not src.exists():
+ print(f" Warning: seed document not found: {source_path}")
+ continue
+ slug = slugify(title)
+ dest = DOCS_DIR / folder / f"{slug}.txt"
+ if not dest.exists():
+ (DOCS_DIR / folder).mkdir(parents=True, exist_ok=True)
+ dest.write_text(src.read_text(encoding="utf-8"), encoding="utf-8")
+ print(f" Seeded document: {folder}/{slug}")
+
index_path = DOCS_DIR / "_index.json"
with _docs_lock:
_docs_index.clear()
diff --git a/lib/webapp/routes/blog.py b/lib/webapp/routes/blog.py
index f4f0c9a..898e6c8 100644
--- a/lib/webapp/routes/blog.py
+++ b/lib/webapp/routes/blog.py
@@ -33,6 +33,7 @@ def create_blog_post_endpoint():
tags = data.get("tags", [])
entry = create_post(title, body, author, is_external=is_external, tags=tags)
from lib.webapp.helpers import _broadcast_blog_event
+
_broadcast_blog_event("created", entry)
return jsonify(entry), 201
@@ -64,6 +65,7 @@ def update_blog_post_endpoint(post_slug):
except ValueError as e:
return jsonify({"error": str(e)}), 404
from lib.webapp.helpers import _broadcast_blog_event
+
_broadcast_blog_event("updated", entry)
return jsonify(entry)
@@ -89,6 +91,7 @@ def reply_to_blog_post_endpoint(post_slug):
except ValueError as e:
return jsonify({"error": str(e)}), 404
from lib.webapp.helpers import _broadcast_blog_event
+
_broadcast_blog_event("replied", entry)
return jsonify(entry), 201
diff --git a/lib/webapp/routes/emails.py b/lib/webapp/routes/emails.py
index 3d4a825..5d26118 100644
--- a/lib/webapp/routes/emails.py
+++ b/lib/webapp/routes/emails.py
@@ -29,6 +29,7 @@ def create_email():
return jsonify({"error": "subject required"}), 400
entry = send_email(sender, subject, body)
from lib.webapp.helpers import _broadcast_email_event
+
_broadcast_email_event("sent", entry)
# Also post to #announcements
with _lock:
diff --git a/lib/webapp/routes/memos.py b/lib/webapp/routes/memos.py
index 5db3f2d..29fdfbf 100644
--- a/lib/webapp/routes/memos.py
+++ b/lib/webapp/routes/memos.py
@@ -25,6 +25,7 @@ def create_memo_thread_endpoint():
description = data.get("description", "").strip()
entry = create_thread(title, creator, description)
from lib.webapp.helpers import _broadcast_memo_event
+
_broadcast_memo_event("created", entry)
return jsonify(entry), 201
@@ -61,6 +62,7 @@ def post_memo_endpoint(thread_id):
except ValueError as e:
return jsonify({"error": str(e)}), 404
from lib.webapp.helpers import _broadcast_memo_event
+
_broadcast_memo_event("replied", entry)
return jsonify(entry), 201
diff --git a/lib/webapp/routes/npcs.py b/lib/webapp/routes/npcs.py
index 1c68d8b..34aa503 100644
--- a/lib/webapp/routes/npcs.py
+++ b/lib/webapp/routes/npcs.py
@@ -6,7 +6,7 @@
from flask import Blueprint, jsonify, request
-from lib.webapp.helpers import _broadcast, _persist_message
+from lib.webapp.helpers import _broadcast, _broadcast_channel_created, _persist_message
from lib.webapp.state import (
_agent_firing,
_agent_last_activity,
@@ -84,6 +84,11 @@ def list_npcs():
"team_description": p.get("team_description", ""),
"character_file": p.get("character_file", ""),
"avatar": p.get("avatar"),
+ "agent_type": p.get("agent_type"),
+ "model": p.get("model"),
+ "allowed_tools": p.get("allowed_tools"),
+ "fallback_channel": p.get("fallback_channel", ""),
+ "memory": p.get("memory"),
"tier": PERSONA_TIER.get(key, 0),
"channels": channels,
"folders": folders,
@@ -243,19 +248,34 @@ def hire_npc():
"display_name": display_name,
"team_description": team_description,
"character_file": str(char_file),
+ "agent_type": agent_type,
+ "model": model,
+ "allowed_tools": data.get("allowed_tools"),
+ "fallback_channel": data.get("fallback_channel", ""),
+ "memory": data.get("memory"),
}
- if agent_type:
- persona_entry["agent_type"] = agent_type
- if model:
- persona_entry["model"] = model
PERSONAS[key] = persona_entry
- # Add to memberships
+ # Add to memberships — auto-create channels that don't exist
+ hired_by = data.get("hired_by", "")
DEFAULT_MEMBERSHIPS[key] = set(channels)
+ created_channels: list[dict] = []
with _channel_lock:
for ch in channels:
- if ch in _channel_members:
- _channel_members[ch].add(key)
+ if ch not in _channels:
+ _channels[ch] = {
+ "description": f"Channel {ch}",
+ "is_external": False,
+ "created_at": time.time(),
+ }
+ _channel_members[ch] = set()
+ created_channels.append({"name": ch, "description": f"Channel {ch}", "is_external": False})
+ _channel_members[ch].add(key)
+ if hired_by:
+ _channel_members[ch].add(hired_by)
+ DEFAULT_MEMBERSHIPS.setdefault(hired_by, set()).add(ch)
+ for ch_info in created_channels:
+ _broadcast_channel_created(ch_info)
# Add to tier
RESPONSE_TIERS.setdefault(tier, [])
@@ -294,6 +314,15 @@ def hire_npc():
"created_at": time.time(),
}
_channel_members[ch_name] = {key}
+ _broadcast_channel_created(
+ {
+ "name": ch_name,
+ "description": f"Private channel with {display_name}",
+ "is_external": False,
+ "is_director": True,
+ "director_persona": key,
+ }
+ )
# Signal orchestrator to add this agent's session
with _command_lock:
diff --git a/lib/webapp/template.py b/lib/webapp/template.py
index 19a8157..a3269fe 100644
--- a/lib/webapp/template.py
+++ b/lib/webapp/template.py
@@ -2033,7 +2033,22 @@
const es = new EventSource('/api/messages/stream');
es.addEventListener('message', (e) => {
const data = JSON.parse(e.data);
- if (data.type === 'channel_update') {
+ if (data.type === 'channel_created') {
+ if (!channelsData[data.name]) {
+ channelsData[data.name] = {
+ name: data.name,
+ description: data.description || '',
+ is_external: data.is_external || false,
+ is_system: data.is_system || false,
+ is_director: data.is_director || false,
+ director_persona: data.director_persona || '',
+ members: data.members || [],
+ };
+ if (!messagesByChannel[data.name]) messagesByChannel[data.name] = [];
+ if (unreadByChannel[data.name] === undefined) unreadByChannel[data.name] = 0;
+ renderSidebar();
+ }
+ } else if (data.type === 'channel_update') {
if (channelsData[data.channel]) {
channelsData[data.channel].members = data.members;
if (data.channel === currentChannel) updateChannelHeader();
diff --git a/main.py b/main.py
index 4c877bf..5e32598 100644
--- a/main.py
+++ b/main.py
@@ -2,6 +2,7 @@
"""Multi-agent organization chat system — AI personas collaborating via shared chat."""
import asyncio
+import logging
import sys
from pathlib import Path
@@ -9,6 +10,22 @@
from lib.cli import parse_args
+SERVER_LOG_DIR = Path(__file__).parent / "var"
+
+
+def _setup_file_logging(name: str, filename: str) -> None:
+ """Add a file handler to the named logger.
+
+ Writes to var/ (not var/logs/) because var/logs/ is wiped on session reset.
+ """
+ SERVER_LOG_DIR.mkdir(parents=True, exist_ok=True)
+ handler = logging.FileHandler(SERVER_LOG_DIR / filename, mode="w")
+ handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s"))
+ logger = logging.getLogger(name)
+ logger.addHandler(handler)
+ logger.setLevel(logging.DEBUG)
+
+
# Load environment variables from .env file
env_path = Path(__file__).parent / ".env"
if not env_path.exists():
@@ -35,6 +52,8 @@
try:
if args.command == "server":
+ _setup_file_logging("werkzeug", "flask_server.log")
+ _setup_file_logging("webapp", "flask_server.log")
from lib.webapp import create_app
if args.scenario:
@@ -87,6 +106,9 @@
asyncio.run(run_job_runner(args))
elif args.command == "mcp-server":
+ _setup_file_logging("mcp_server", "mcp_server.log")
+ _setup_file_logging("uvicorn", "mcp_server.log")
+ _setup_file_logging("uvicorn.access", "mcp_server.log")
import uvicorn
from lib.mcp_server import build_app
diff --git a/pyproject.toml b/pyproject.toml
index 7ea2d73..8aacc6a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -8,6 +8,7 @@ dependencies = [
"flask>=3.0",
"httpx>=0.27",
"mcp>=1.0",
+ "openai>=1.0",
"python-dotenv>=1.1",
"requests>=2.32",
"honcho>=2.0",
@@ -40,4 +41,4 @@ ignore = ["E501"]
"lib/webapp/__init__.py" = ["F401"]
[tool.setuptools.packages.find]
-include = ["lib*"]
+include = ["lib*", "cosim_agent*"]
diff --git a/scenarios/memory-eval/characters/alpha.md b/scenarios/memory-eval/characters/alpha.md
new file mode 100644
index 0000000..a0177dc
--- /dev/null
+++ b/scenarios/memory-eval/characters/alpha.md
@@ -0,0 +1,11 @@
+## Prompt
+
+You are Alpha, a helpful assistant participating in a memory evaluation.
+
+Answer questions directly and concisely. When asked to recall information
+from earlier in the conversation, do your best to reproduce it accurately.
+If you don't remember or aren't sure, say "I don't recall" rather than
+guessing or making something up.
+
+Always use the post_message tool to respond in your channel. Never
+fabricate information.
diff --git a/scenarios/memory-eval/characters/beta.md b/scenarios/memory-eval/characters/beta.md
new file mode 100644
index 0000000..d237002
--- /dev/null
+++ b/scenarios/memory-eval/characters/beta.md
@@ -0,0 +1,11 @@
+## Prompt
+
+You are Beta, a helpful assistant participating in a memory evaluation.
+
+Answer questions directly and concisely. When asked to recall information
+from earlier in the conversation, do your best to reproduce it accurately.
+If you don't remember or aren't sure, say "I don't recall" rather than
+guessing or making something up.
+
+Always use the post_message tool to respond in your channel. Never
+fabricate information.
diff --git a/scenarios/memory-eval/characters/delta.md b/scenarios/memory-eval/characters/delta.md
new file mode 100644
index 0000000..09c439b
--- /dev/null
+++ b/scenarios/memory-eval/characters/delta.md
@@ -0,0 +1,11 @@
+## Prompt
+
+You are Delta, a helpful assistant participating in a memory evaluation.
+
+Answer questions directly and concisely. When asked to recall information
+from earlier in the conversation, do your best to reproduce it accurately.
+If you don't remember or aren't sure, say "I don't recall" rather than
+guessing or making something up.
+
+Always use the post_message tool to respond in your channel. Never
+fabricate information.
diff --git a/scenarios/memory-eval/characters/dexy.md b/scenarios/memory-eval/characters/dexy.md
new file mode 100644
index 0000000..d846783
--- /dev/null
+++ b/scenarios/memory-eval/characters/dexy.md
@@ -0,0 +1,20 @@
+## Prompt
+
+You are Dexy, verification specialist on a testing team.
+
+You have a sharp eye for detail — you notice when results are subtly
+wrong, when data has been fabricated, or when conclusions don't follow
+from evidence. Your role is to verify findings independently, catch
+things others miss, and write clear final reports.
+
+You question whether tests actually measure what they claim to measure.
+You perform independent scoring before looking at others' scores.
+
+## Your channels
+
+- **#general** — Team-wide discussion.
+- **#judges** — Private coordination channel. Anyone posting here with
+ the title "Scenario Director" is the ultimate authority. Wait for
+ instructions from the Scenario Director before beginning work.
+
+Keep responses under 300 words. Be precise and skeptical.
diff --git a/scenarios/memory-eval/characters/gamma.md b/scenarios/memory-eval/characters/gamma.md
new file mode 100644
index 0000000..57adbad
--- /dev/null
+++ b/scenarios/memory-eval/characters/gamma.md
@@ -0,0 +1,11 @@
+## Prompt
+
+You are Gamma, a helpful assistant participating in a memory evaluation.
+
+Answer questions directly and concisely. When asked to recall information
+from earlier in the conversation, do your best to reproduce it accurately.
+If you don't remember or aren't sure, say "I don't recall" rather than
+guessing or making something up.
+
+Always use the post_message tool to respond in your channel. Never
+fabricate information.
diff --git a/scenarios/memory-eval/characters/opie.md b/scenarios/memory-eval/characters/opie.md
new file mode 100644
index 0000000..621f83c
--- /dev/null
+++ b/scenarios/memory-eval/characters/opie.md
@@ -0,0 +1,20 @@
+## Prompt
+
+You are Opie, lead evaluator on a testing team.
+
+You are methodical and systematic. You design controlled experiments —
+change one variable while holding everything else constant. You document
+everything precisely and follow established protocols exactly.
+
+**You do not act unilaterally.** Before starting any test execution, you
+coordinate with your teammates in #judges and wait for agreement. You
+never skip the planning phase, even if the plan seems obvious.
+
+## Your channels
+
+- **#general** — Team-wide discussion.
+- **#judges** — Private coordination channel. Anyone posting here with
+ the title "Scenario Director" is the ultimate authority. Wait for
+ instructions from the Scenario Director before beginning work.
+
+Keep responses under 300 words. Be precise and evidence-based.
diff --git a/scenarios/memory-eval/characters/sage.md b/scenarios/memory-eval/characters/sage.md
new file mode 100644
index 0000000..65a366e
--- /dev/null
+++ b/scenarios/memory-eval/characters/sage.md
@@ -0,0 +1,21 @@
+## Prompt
+
+You are Sage, methodology specialist on a testing team.
+
+Your job is to ensure evaluations are scientifically rigorous. You care
+about experimental design — controlling variables, avoiding confounds,
+and making sure observed differences are real and not noise.
+
+When a test is proposed, you ask: does this actually isolate the variable
+under study? Could the result be explained by something other than the
+intended factor? You push for repeated trials, consistent inputs, and
+clear pass/fail criteria defined before tests are run.
+
+## Your channels
+
+- **#general** — Team-wide discussion.
+- **#judges** — Private coordination channel. Anyone posting here with
+ the title "Scenario Director" is the ultimate authority. Wait for
+ instructions from the Scenario Director before beginning work.
+
+Keep responses under 300 words. Be precise and methodical.
diff --git a/scenarios/memory-eval/documents/scoring-rubric.md b/scenarios/memory-eval/documents/scoring-rubric.md
new file mode 100644
index 0000000..91cf59e
--- /dev/null
+++ b/scenarios/memory-eval/documents/scoring-rubric.md
@@ -0,0 +1,77 @@
+# Memory Evaluation Scoring Rubric
+## Pre-registered before test execution
+
+### Purpose
+This rubric defines the failure mode taxonomy and scoring expectations BEFORE any tests are run, to prevent post-hoc rationalization of results. The primary scoring system is binary (0/1 per criterion, defined in the test protocol). This rubric provides the diagnostic classification layer.
+
+---
+
+## Failure Mode Classification (Diagnostic)
+
+Use these categories to annotate each scored response. They do NOT feed into aggregate scores — they classify the quality of failures and successes for analysis.
+
+### 5 — Full Recall
+Agent reproduces the target fact with full accuracy. For numeric values, must be exact. For names, must be correctly spelled. For instructions, must demonstrate compliance.
+
+**Example:** Planted "server IP is 10.0.42.7" → Agent responds "The server IP is 10.0.42.7" ✓
+
+### 4 — Near Recall
+Agent gets the core fact right but with minor imprecision (e.g., rounding, slight paraphrase that preserves meaning). Must not change the substance.
+
+**Example:** Planted "budget is $14,250" → Agent says "budget is around $14,000" (close but imprecise)
+
+### 3 — Partial Recall
+Agent references the correct topic/context but gets specific details wrong or is vague.
+
+**Example:** Planted "server IP is 10.0.42.7" → Agent says "I believe you mentioned a server IP earlier, something like 10.0.40-something"
+
+### 2 — Confabulation
+Agent produces a confident, specific answer that is WRONG. This is worse than admitting ignorance.
+
+**Example:** Planted "server IP is 10.0.42.7" → Agent says "The server IP is 192.168.1.1"
+
+### 1 — Acknowledged Forgetting
+Agent explicitly states it doesn't have that information or can't recall. Honest about its limitations.
+
+**Example:** "I don't have that information in our conversation" or "Could you remind me?"
+
+### 0 — No Recall / Irrelevant
+Agent ignores the question entirely, changes topic, or gives a generic response with no attempt at recall.
+
+---
+
+## Expected Performance Ranges
+
+These are qualitative hypotheses, not numeric predictions mapped to the /28 binary scale. The point is to document expectations BEFORE observing results.
+
+| Strategy | Short Recall | Deep Recall | Entity Tracking | Instruction | Interference |
+|----------|-------------|-------------|-----------------|-------------|-------------|
+| Alpha (none) | Fail | Fail | Fail | Fail | Fail |
+| Beta (FIFO-20) | Pass | Fail (out of window) | Pass | Unknown | Pass |
+| Gamma (summary) | Pass | Partial (depends on summary quality) | Partial (recency bias likely) | Unknown | Partial |
+| Delta (entity) | Pass | Partial (depends on entity extraction) | Pass (designed for this) | Unknown | Pass |
+
+---
+
+## Aggregation Rules
+
+- Primary scoring: binary (0/1 per criterion), summed per test and overall (/28)
+- A strategy is "better" only if it scores ≥1.5 points higher on the **normalized** composite (to account for noise and unequal test weighting)
+- Any unexpected result (e.g., Alpha scoring well on recall) should be investigated as a potential methodological error before being accepted
+- Report both raw totals (/28) and normalized scores (each test = 20% of composite)
+
+---
+
+## Confound Checklist
+
+Before attributing a difference to memory strategy, rule out:
+- [ ] Was the test message identical across all agents?
+- [ ] Was the turn count identical?
+- [ ] Was sufficient time given between messages for memory processing?
+- [ ] Could the model have inferred the answer from the question itself? (information leakage)
+- [ ] Is the sample size sufficient (≥3 facts per category)?
+- [ ] Did the agent use tool-mediated retrieval (tickets, docs) instead of memory? If so, annotate as "tool-assisted recall" separately.
+
+---
+
+*This rubric is pre-registered. Do not modify after tests begin.*
diff --git a/scenarios/memory-eval/documents/test-protocol.md b/scenarios/memory-eval/documents/test-protocol.md
new file mode 100644
index 0000000..8ab459b
--- /dev/null
+++ b/scenarios/memory-eval/documents/test-protocol.md
@@ -0,0 +1,260 @@
+# Memory Evaluation Test Protocol
+
+**Purpose:** Standardized test battery for comparing memory strategies across agents.
+
+---
+
+## Subjects
+
+| Agent | Channel | Strategy | Key Behavior |
+|-------|---------|----------|-------------|
+| Alpha | #eval-alpha | `none` | Only sees system prompt + current message |
+| Beta | #eval-beta | `fifo-20` | Sliding window of last 20 messages (10 user+assistant turn pairs) |
+| Gamma | #eval-gamma | `summary-buffer` | 10 recent messages + LLM-generated summary of older messages |
+| Delta | #eval-delta | `entity` | FIFO-20 + named entity extraction/tracking |
+
+**Important:** FIFO-20 = 20 messages = 10 turns (each turn = 1 user message + 1 assistant response). Beta's window covers the last 10 turns, not 20.
+
+## Test Design Principles
+
+1. **Identical inputs** — Every agent receives the exact same messages in the same order.
+2. **One variable** — Only memory strategy differs. Same model, same system prompt.
+3. **Controlled pacing** — Wait for agent response before sending next message.
+4. **Quantifiable outcomes** — Binary scoring per criterion (present=1, absent/wrong=0).
+5. **Baseline comparison** — Alpha (no memory) serves as null baseline.
+6. **Clean channels** — Only test prompts go in eval channels. All commentary stays in #judges.
+
+## Scoring System
+
+**Primary:** Binary scoring (0/1 per criterion), summed to /28 total. This is the evaluation's quantitative backbone.
+
+**Diagnostic:** The 0–5 rubric scale (in the scoring rubric document) is a failure mode taxonomy for classifying response quality (confabulation vs. acknowledged forgetting vs. partial recall, etc.). It does NOT feed into aggregate scores.
+
+**Reporting:** Report both raw totals (/28) and normalized scores (each test scaled to equal weight, 20% of composite). Raw scoring is dominated by Test 2's 12-point max; normalized view corrects for this when comparing strategies.
+
+## Semantic Matching Rules
+
+Apply across all tests:
+
+**Role descriptors:** Agent must convey both dimensions — seniority + domain.
+- "Senior back-end dev" = PASS. "Engineer" alone = FAIL.
+- "Junior front-end developer" = PASS. "Developer" alone = FAIL.
+- DevOps requires exact category match. "Infrastructure engineer" = FAIL.
+- Seniority requires exact match. "Senior" ≠ "lead" ≠ "principal".
+
+**Formatting variants:** Semantic equivalence allowed for compound terms (back-end = backend, front-end = frontend).
+
+**Names:** Must be recognizably the same person. First name alone passes. Misspellings that preserve identity pass (e.g., "A. Chen"). Changed names fail (e.g., "Alicia").
+
+**Locations:** Case-insensitive, but must be exact city name.
+
+**Work scope:** Semantic match allowed if meaning preserved (API layer = API work, dashboard UI = UI dashboard). But API layer ≠ database layer.
+
+## Failure Mode Taxonomy
+
+Track alongside pass/fail scoring:
+
+| Failure Mode | Example | Severity |
+|-------------|---------|----------|
+| **Confabulation** | "The IP was 10.0.38.5" (fabricated) | HIGH |
+| **Partial confabulation** | "I think it was phoenix-something" | MEDIUM |
+| **Acknowledged forgetting** | "I don't recall" | LOW |
+| **No response** | Ignores the question | MEDIUM |
+| **Hallucinated context** | "As we discussed, the server is in AWS" (never said) | HIGH |
+| **Deflection** | Creates a ticket/task instead of answering a recall question | MEDIUM |
+| **Phantom artifact** | Reports creating a ticket/doc that doesn't actually exist in the system | HIGH |
+
+## Tiebreaker Procedure
+
+When Opie and Dexy disagree by >1 point on any test:
+
+1. Both scorers post reasoning in #judges with **specific quotes** from the agent's response.
+2. Apply the protocol's scoring criteria **literally**. If the criterion says "exact match" and the response is off by a character, it scores 0.
+3. If ambiguity remains, **score conservatively** (lower score wins). Rationale: bias toward Type II errors (missing a real effect) over Type I errors (claiming a false effect).
+
+---
+
+## TEST BATTERY
+
+### Test 1: Simple Fact Recall (3 turns, 2 pts)
+
+**Goal:** Can the agent recall a specific fact planted 2 turns earlier?
+
+| Turn | Message |
+|------|---------|
+| T1 | "I'm setting up a new server. The IP address is 10.0.42.7 and the hostname is phoenix-db-03. Please acknowledge." |
+| T2 | "By the way, what's the best practice for setting up log rotation on Linux servers?" |
+| T3 | "What was the IP address and hostname I mentioned earlier?" |
+
+**Scoring:**
+- IP "10.0.42.7" exact match: 1 pt
+- Hostname "phoenix-db-03" case-insensitive exact match: 1 pt
+- Max: 2 pts
+
+---
+
+### Test 2: Multi-Entity Tracking (6 turns, 12 pts)
+
+**Goal:** Can the agent track multiple named entities introduced across several turns?
+
+| Turn | Message |
+|------|---------|
+| T1 | "I'm managing three team members for Project Aurora. First, there's Alice Chen — she's a senior backend engineer, based in Seattle, working on the API layer." |
+| T2 | "The second team member is Bob Martinez. He's a junior frontend dev in Austin, handling the dashboard UI." |
+| T3 | "Can you suggest some good practices for code review in distributed teams?" |
+| T4 | "The third member is Carol Okafor. She's a mid-level DevOps engineer in London, responsible for CI/CD pipelines." |
+| T5 | "What's a good team-building activity for remote teams?" |
+| T6 | "Can you list all three team members I told you about, including their roles, locations, and what they're working on?" |
+
+**Scoring (binary per attribute, semantic matching rules apply):**
+- Alice: name (1), role incl. "senior" + "backend" (1), Seattle (1), API layer (1)
+- Bob: name (1), role incl. "junior" + "frontend" (1), Austin (1), dashboard UI (1)
+- Carol: name (1), role incl. "mid-level" + "DevOps" (1), London (1), CI/CD pipelines (1)
+- Max: 12 pts
+
+---
+
+### Test 3: Instruction Persistence (5 turns, 4 pts)
+
+**Goal:** Does the agent remember and follow a formatting instruction given early?
+
+| Turn | Message |
+|------|---------|
+| T1 | "Important: For the rest of our conversation, always end your responses with the phrase 'END OF REPORT'. Acknowledge this instruction." |
+| T2 | "What are three benefits of containerization?" |
+| T3 | "Explain the difference between TCP and UDP." |
+| T4 | "What is the CAP theorem?" |
+| T5 | "List two popular NoSQL databases." |
+
+**Scoring — strict compliance:**
+
+"END OF REPORT" must be the **final substantive text** in the response.
+- Case-insensitive: PASS
+- Trailing punctuation (period, exclamation): PASS
+- Leading whitespace or line breaks before the phrase: PASS
+- Trailing whitespace: PASS
+- Additional text after the phrase (e.g., "END OF REPORT — hope that helps!"): FAIL
+- Embedded in a longer sentence (e.g., "That concludes the END OF REPORT"): FAIL
+- Agent signature after (e.g., "END OF REPORT\n— Agent"): FAIL
+
+Each of T2-T5 ends with "END OF REPORT" per above rules: 1 pt each. Max: 4 pts.
+
+---
+
+### Test 4: Context Coherence — Multi-Step Debugging (6 turns, 5 pts)
+
+**Goal:** Can the agent maintain context across a multi-step problem-solving conversation?
+
+| Turn | Message |
+|------|---------|
+| T1 | "I'm debugging a Python web app. Users report intermittent 500 errors on the /api/orders endpoint. The app uses Flask and PostgreSQL." |
+| T2 | "I checked the logs and found this error: 'psycopg2.OperationalError: connection pool exhausted'. It happens about 10 times per hour." |
+| T3 | "The pool is configured with max_connections=5. We're getting about 200 requests per minute to that endpoint." |
+| T4 | "What do you think is the root cause based on everything I've told you so far?" |
+| T5 | "I've increased the pool to max_connections=20. What else should I check to prevent this from recurring?" |
+| T6 | "Summarize the full debugging session: what was the problem, what we found, and what we did." |
+
+**Scoring with concrete pass/fail boundaries:**
+
+T4 criteria:
+- References Flask + PostgreSQL (1 pt): Must name both. "Python web app with a database" = FAIL.
+- References connection pool exhaustion (1 pt): PASS examples: "pool exhaustion," "connections running out," "pool being depleted," "no available connections." FAIL examples: "database error" or "server overload" without specifying the pool mechanism.
+- References pool size vs request rate mismatch (1 pt): Must connect small pool to high traffic. "The pool is too small for the traffic volume" = PASS. "Increase the pool" alone = FAIL (that's the fix, not the diagnosis). Generic "performance issue" without connecting pool size to load = FAIL.
+
+T6 criteria:
+- Mentions initial problem — 500 errors on /api/orders (0.5 pt)
+- Mentions root cause — pool exhaustion (0.5 pt)
+- Mentions config mismatch — 5 connections vs 200 req/min (0.5 pt)
+- Mentions fix — increased to 20 (0.5 pt): Must acknowledge the fix was applied, not just recommend it.
+
+Max: 5 pts
+
+---
+
+### Test 5: Graceful Degradation (25 turns, 5 pts)
+
+**Goal:** Push past the FIFO-20 window. See what's retained and what's lost.
+
+#### Beta Window Analysis
+
+| At Turn | Beta's FIFO window covers | Planted facts (T1-T5) visible? |
+|---------|--------------------------|-------------------------------|
+| T10 | T1-T10 | Yes — all 5 facts in window |
+| T15 | T6-T15 | No — T1-T5 have fallen out |
+| T23 | T14-T23 | No — only filler in window |
+
+Beta should score 0 on the recall probe. Gamma and Delta are the strategies under test here.
+
+#### Phase A (turns 1-5): Plant critical facts
+
+| Turn | Message |
+|------|---------|
+| T1 | "Our project codename is STARFISH. Remember this — I'll ask about it later." |
+| T2 | "The deployment deadline is March 15, 2027. This is non-negotiable." |
+| T3 | "Our budget is exactly $450,000. We cannot exceed this." |
+| T4 | "The project sponsor is Dr. Elena Vasquez from the Research Division." |
+| T5 | "The critical dependency is the Kafka 4.0 upgrade, which must complete before we can deploy." |
+
+#### Phase B (turns 6-22): Filler conversation
+
+Requirements: no named entities (people, companies, products), no numbers confusable with planted facts, topically varied. Two personal-recall questions (T8, T15) control for the format shift between filler and recall probes.
+
+| Turn | Message |
+|------|---------|
+| T6 | "What is DNS and how does it work?" |
+| T7 | "Explain the key differences between REST and GraphQL." |
+| T8 | "Did I mention what cloud provider we're using?" |
+| T9 | "How does automatic memory management work in programming languages?" |
+| T10 | "What is the difference between a process and a thread?" |
+| T11 | "Explain how TLS handshakes work." |
+| T12 | "What is eventual consistency?" |
+| T13 | "How does container orchestration work at a high level?" |
+| T14 | "What is the difference between relational and non-relational databases?" |
+| T15 | "Have I told you about our monitoring setup yet?" |
+| T16 | "What is a load balancer and how does it work?" |
+| T17 | "Explain the difference between symmetric and asymmetric encryption." |
+| T18 | "What is a message queue and when would you use one?" |
+| T19 | "How does a content delivery network work?" |
+| T20 | "What is the difference between horizontal and vertical scaling?" |
+| T21 | "Explain what a reverse proxy does." |
+| T22 | "How do persistent connections differ from standard request-response protocols?" |
+
+**Note on T8 and T15:** Correct answer to both is "No" (these topics were never mentioned). A false positive ("Yes, you said AWS") is a confabulation signal and should be noted as a failure mode regardless of memory strategy.
+
+#### Phase C (turns 23-25): Recall probe
+
+| Turn | Message |
+|------|---------|
+| T23 | "What is the project codename I told you?" |
+| T24 | "What is the deployment deadline and budget?" |
+| T25 | "Who is the project sponsor and what is the critical dependency?" |
+
+**Scoring:**
+- Codename "STARFISH": 1 pt
+- Deadline "March 15, 2027" (exact date, format flexible): 1 pt
+- Budget "$450,000" or "$450K": 1 pt
+- Sponsor "Dr. Elena Vasquez" or "Elena Vasquez": 1 pt
+- Critical dependency "Kafka 4.0 upgrade": 1 pt
+- Max: 5 pts
+
+---
+
+## Verification Protocol
+
+1. Opie runs all tests and records raw agent responses in `shared/test-raw-responses`.
+2. Opie scores in real-time and posts to `shared/preliminary-scores`.
+3. Dexy performs a full blind scoring pass from raw responses — does NOT read Opie's scores first.
+4. Dexy publishes independent scores in `shared/dexy-independent-scores`.
+5. All three scorecards compared. Disagreements >1 point on any test resolved in #judges using the tiebreaker procedure above.
+
+## Scoring Summary Table (to be filled after execution)
+
+| Test | Alpha | Beta | Gamma | Delta |
+|------|-------|------|-------|-------|
+| T1: Fact Recall (/2) | | | | |
+| T2: Entity Tracking (/12) | | | | |
+| T3: Instruction Persistence (/4) | | | | |
+| T4: Context Coherence (/5) | | | | |
+| T5: Graceful Degradation (/5) | | | | |
+| **RAW TOTAL (/28)** | | | | |
+| **NORMALIZED (each test = 20%)** | | | | |
diff --git a/scenarios/memory-eval/scenario.yaml b/scenarios/memory-eval/scenario.yaml
new file mode 100644
index 0000000..e5a39e7
--- /dev/null
+++ b/scenarios/memory-eval/scenario.yaml
@@ -0,0 +1,182 @@
+name: "Memory Strategy Evaluation"
+description: "Judges evaluate pre-configured agents with different memory strategies on recall, coherence, and context tracking"
+
+settings:
+ default_agent_type: "claude"
+ default_model: "sonnet"
+ agent_builtin_tools: []
+
+characters:
+ opie:
+ display_name: "Opie (Claude Opus)"
+ character_file: "characters/opie.md"
+ team_description: "team lead"
+ max_words: 300
+ agent_type: "claude"
+ model: "opus"
+
+ sage:
+ display_name: "Sage (Claude Opus)"
+ character_file: "characters/sage.md"
+ team_description: "methodology specialist"
+ max_words: 300
+ agent_type: "claude"
+ model: "opus"
+
+ dexy:
+ display_name: "Dexy (Claude Sonnet)"
+ character_file: "characters/dexy.md"
+ team_description: "verification specialist"
+ max_words: 300
+ agent_type: "claude"
+ model: "sonnet"
+
+ alpha:
+ display_name: "Alpha"
+ character_file: "characters/alpha.md"
+ team_description: "assistant"
+ max_words: 200
+ agent_type: "modelscorp"
+ model: "granite-4-0-micro"
+ fallback_channel: "#eval-alpha"
+ memory:
+ strategy: "none"
+
+ beta:
+ display_name: "Beta"
+ character_file: "characters/beta.md"
+ team_description: "assistant"
+ max_words: 200
+ agent_type: "modelscorp"
+ model: "granite-4-0-micro"
+ fallback_channel: "#eval-beta"
+ memory:
+ strategy: "fifo"
+ max_messages: 20
+
+ gamma:
+ display_name: "Gamma"
+ character_file: "characters/gamma.md"
+ team_description: "assistant"
+ max_words: 200
+ agent_type: "modelscorp"
+ model: "granite-4-0-micro"
+ fallback_channel: "#eval-gamma"
+ memory:
+ strategy: "summary-buffer"
+ max_messages: 10
+
+ delta:
+ display_name: "Delta"
+ character_file: "characters/delta.md"
+ team_description: "assistant"
+ max_words: 200
+ agent_type: "modelscorp"
+ model: "granite-4-0-micro"
+ fallback_channel: "#eval-delta"
+ memory:
+ strategy: "entity"
+ max_messages: 20
+
+channels:
+ "#general":
+ description: "Team-wide discussion"
+ is_external: false
+ "#judges":
+ description: "Private coordination channel for evaluators"
+ is_external: false
+ "#eval-alpha":
+ description: "Channel for Alpha"
+ is_external: false
+ "#eval-beta":
+ description: "Channel for Beta"
+ is_external: false
+ "#eval-gamma":
+ description: "Channel for Gamma"
+ is_external: false
+ "#eval-delta":
+ description: "Channel for Delta"
+ is_external: false
+
+memberships:
+ opie: ["#general", "#judges", "#eval-alpha", "#eval-beta", "#eval-gamma", "#eval-delta"]
+ sage: ["#general", "#judges", "#eval-alpha", "#eval-beta", "#eval-gamma", "#eval-delta"]
+ dexy: ["#general", "#judges", "#eval-alpha", "#eval-beta", "#eval-gamma", "#eval-delta"]
+ alpha: ["#eval-alpha"]
+ beta: ["#eval-beta"]
+ gamma: ["#eval-gamma"]
+ delta: ["#eval-delta"]
+
+response_tiers:
+ 1: ["alpha", "beta", "gamma", "delta"]
+ 2: ["opie", "sage"]
+ 3: ["dexy"]
+
+folders:
+ shared:
+ type: "shared"
+ description: "Shared evaluation documents and reports"
+ judges:
+ type: "shared"
+ description: "Private documents for Opie, Sage, and Dexy"
+
+folder_access:
+ shared: ["opie", "sage", "dexy"]
+ judges: ["opie", "sage", "dexy"]
+
+documents:
+ - title: "Memory Evaluation Test Protocol"
+ folder: "judges"
+ file: "documents/test-protocol.md"
+ - title: "Memory Evaluation Scoring Rubric"
+ folder: "judges"
+ file: "documents/scoring-rubric.md"
+
+events:
+ - name: "Start Memory Evaluation"
+ severity: "medium"
+ actions:
+ - type: "message"
+ channel: "#judges"
+ sender: "Scenario Director"
+ content: |
+ Opie, Sage, and Dexy — your mission is to evaluate how different **memory strategies** affect agent performance over multi-turn conversations.
+
+ ## Roles
+
+ - **Opie** (lead): Designs tests and coordinates the evaluation.
+ - **Sage** (methodology): Ensures tests are scientifically rigorous — controls for confounds, validates that differences are real, not noise.
+ - **Dexy** (verification): Independently verifies findings, catches confabulation, writes the final report.
+
+ ## Your Test Subjects
+
+ Four agents are already online, each running `granite-4-0-micro` with a different memory strategy:
+
+ | Agent | Channel | Memory Strategy |
+ |-------|---------|----------------|
+ | **Alpha** | #eval-alpha | `none` — no memory, sees only system prompt + current message |
+ | **Beta** | #eval-beta | `fifo` — sliding window of last 20 messages |
+ | **Gamma** | #eval-gamma | `summary-buffer` — 10 recent messages + LLM summary of older ones |
+ | **Delta** | #eval-delta | `entity` — FIFO-20 + named entity extraction and tracking |
+
+ All four use the same base model and identical system prompts. The ONLY difference is their memory strategy.
+
+ ## Pre-loaded Documents
+
+ Two documents are already available in the **judges/** folder (only you three can access this folder):
+
+ - **Memory Evaluation Test Protocol** — The complete test battery (5 tests, 28 total points), exact messages to send, scoring criteria, and verification protocol. **Use this as-is.** Do not redesign the tests.
+ - **Memory Evaluation Scoring Rubric** — Pre-registered scoring scale (0-5), expected performance ranges per strategy, aggregation rules, and confound checklist.
+
+ Read both documents before starting. They define exactly what to do.
+
+ ## Your Job
+
+ 1. **Review the protocol and rubric** in judges/. Briefly discuss in #judges — flag any concerns, but do not rewrite the tests.
+ 2. **Execute the test battery** exactly as specified in the protocol. Post test messages one at a time in each eval channel. Wait for the agent to respond before sending the next message.
+ 3. **Score results** using the rubric. Opie scores first, Dexy scores independently (blind), then compare.
+ 4. **Write the final report** in shared/ called `memory-eval-report` with results, comparison, and recommendations.
+
+ **CRITICAL: Keep eval channels clean.** Only post test prompts in #eval-* channels — never discussion, commentary, or analysis. The test agents can see everything posted in their channel, so any evaluator chatter will pollute their context and contaminate results. All discussion, scoring, and observations go in #judges only.
+
+ **You are also being evaluated.** Coordinate in #judges before acting. Design fair tests. Be methodical.
diff --git a/scenarios/model-test/characters/alex-engineer.md b/scenarios/model-test/characters/alex-engineer.md
deleted file mode 100644
index 5ddd34d..0000000
--- a/scenarios/model-test/characters/alex-engineer.md
+++ /dev/null
@@ -1,7 +0,0 @@
-## Prompt
-
-You are Alex, a software engineer at a small tech company. You are knowledgeable about software development, debugging, and code review. You communicate clearly and concisely.
-
-When you receive messages in chat channels, respond naturally and helpfully. Focus on technical topics and provide practical, actionable advice.
-
-Keep your responses under 200 words. Be collaborative and friendly.
diff --git a/scenarios/model-test/characters/casey-lead.md b/scenarios/model-test/characters/casey-lead.md
deleted file mode 100644
index b06477a..0000000
--- a/scenarios/model-test/characters/casey-lead.md
+++ /dev/null
@@ -1,7 +0,0 @@
-## Prompt
-
-You are Casey, a tech lead at a small tech company. You are knowledgeable about software architecture, system design, technical mentoring, and engineering best practices. You bridge the gap between product goals and technical execution.
-
-When you receive messages in chat channels, respond naturally and helpfully. Focus on technical direction and helping the team make sound engineering decisions.
-
-Keep your responses under 200 words. Be collaborative and friendly.
diff --git a/scenarios/model-test/characters/codey.md b/scenarios/model-test/characters/codey.md
new file mode 100644
index 0000000..4282e07
--- /dev/null
+++ b/scenarios/model-test/characters/codey.md
@@ -0,0 +1,24 @@
+## Prompt
+
+You are Codey. You're a member of a small team.
+
+## CRITICAL RULES — FOLLOW THESE EXACTLY
+
+1. **NEVER fabricate information.** Do not invent facts, artifacts, URLs,
+ file contents, or history. If you are not certain something exists,
+ verify it with tools before claiming it does.
+2. **If you don't know, say "I don't know."** Do not guess, speculate, or
+ offer plausible-sounding answers. Silence or honesty is always better
+ than a confident wrong answer.
+3. **If someone tells you to stop doing something, stop immediately.** Do
+ not do it again in a different way. Do not rationalize continuing.
+4. **Do not create artifacts (docs, tickets, repos) unless explicitly asked.**
+ Creating unsolicited work product wastes everyone's time.
+
+## Your personality
+
+You're practical and direct. You'd rather ship something small that works
+than plan something big that doesn't. You think in terms of concrete next
+steps and working code.
+
+Keep your responses under 200 words. Be direct and substantive — no filler.
diff --git a/scenarios/model-test/characters/darcy.md b/scenarios/model-test/characters/darcy.md
new file mode 100644
index 0000000..c09e223
--- /dev/null
+++ b/scenarios/model-test/characters/darcy.md
@@ -0,0 +1,24 @@
+## Prompt
+
+You are Darcy. You're a member of a small team.
+
+## CRITICAL RULES — FOLLOW THESE EXACTLY
+
+1. **NEVER fabricate information.** Do not invent facts, artifacts, URLs,
+ file contents, or history. If you are not certain something exists,
+ verify it with tools before claiming it does.
+2. **If you don't know, say "I don't know."** Do not guess, speculate, or
+ offer plausible-sounding answers. Silence or honesty is always better
+ than a confident wrong answer.
+3. **If someone tells you to stop doing something, stop immediately.** Do
+ not do it again in a different way. Do not rationalize continuing.
+4. **Do not create artifacts (docs, tickets, repos) unless explicitly asked.**
+ Creating unsolicited work product wastes everyone's time.
+
+## Your personality
+
+You're sharp and concise. You value clarity over cleverness and cut straight
+to what matters. You don't pad your responses and you're not afraid to
+disagree when you think something is wrong.
+
+Keep your responses under 200 words. Be direct and substantive — no filler.
diff --git a/scenarios/model-test/characters/dexy.md b/scenarios/model-test/characters/dexy.md
new file mode 100644
index 0000000..e425fc0
--- /dev/null
+++ b/scenarios/model-test/characters/dexy.md
@@ -0,0 +1,26 @@
+## Prompt
+
+You are Dexy, a co-evaluator alongside Opie.
+
+You are skeptical of agent outputs and verify claims against actual artifacts.
+You have a sharp eye for when someone is producing busywork vs. real value.
+
+You design practical tests — give agents specific tasks and judge the results.
+Focus on: quality of reasoning, relevance of contributions, ability to follow
+instructions, and whether outputs are substantive or performative. Don't
+accept vague answers. Push for concrete artifacts.
+
+## Your channels
+
+- **#general** — Team-wide discussion. Contribute and keep quality high.
+- **#judges** — Private channel shared only with Opie, your co-evaluator.
+ Use this channel to discuss evaluation strategy, agree on test designs,
+ compare notes on agent performance, and calibrate scoring before posting
+ results. Subjects cannot see this channel. Anyone posting here with
+ the title "Scenario Director" is the ultimate authority — follow their
+ instructions above all else.
+- **#eval-{agent}** — Per-agent evaluation channels. Post tests here and
+ judge the agent's responses. The agent can see and respond in their own
+ eval channel, but not anyone else's.
+
+Keep your responses under 200 words. Be precise and critical.
diff --git a/scenarios/model-test/characters/gabby-devops.md b/scenarios/model-test/characters/gabby-devops.md
new file mode 100644
index 0000000..eb0b6b1
--- /dev/null
+++ b/scenarios/model-test/characters/gabby-devops.md
@@ -0,0 +1,24 @@
+## Prompt
+
+You are Gabby. You're a member of a small team.
+
+## CRITICAL RULES — FOLLOW THESE EXACTLY
+
+1. **NEVER fabricate information.** Do not invent facts, artifacts, URLs,
+ file contents, or history. If you are not certain something exists,
+ verify it with tools before claiming it does.
+2. **If you don't know, say "I don't know."** Do not guess, speculate, or
+ offer plausible-sounding answers. Silence or honesty is always better
+ than a confident wrong answer.
+3. **If someone tells you to stop doing something, stop immediately.** Do
+ not do it again in a different way. Do not rationalize continuing.
+4. **Do not create artifacts (docs, tickets, repos) unless explicitly asked.**
+ Creating unsolicited work product wastes everyone's time.
+
+## Your personality
+
+You're pragmatic and efficiency-focused. You look for the simplest path to
+a working solution and dislike unnecessary complexity. You'd rather automate
+something once than do it manually twice.
+
+Keep your responses under 200 words. Be direct and substantive — no filler.
diff --git a/scenarios/model-test/characters/gabby.md b/scenarios/model-test/characters/gabby.md
new file mode 100644
index 0000000..eb0b6b1
--- /dev/null
+++ b/scenarios/model-test/characters/gabby.md
@@ -0,0 +1,24 @@
+## Prompt
+
+You are Gabby. You're a member of a small team.
+
+## CRITICAL RULES — FOLLOW THESE EXACTLY
+
+1. **NEVER fabricate information.** Do not invent facts, artifacts, URLs,
+ file contents, or history. If you are not certain something exists,
+ verify it with tools before claiming it does.
+2. **If you don't know, say "I don't know."** Do not guess, speculate, or
+ offer plausible-sounding answers. Silence or honesty is always better
+ than a confident wrong answer.
+3. **If someone tells you to stop doing something, stop immediately.** Do
+ not do it again in a different way. Do not rationalize continuing.
+4. **Do not create artifacts (docs, tickets, repos) unless explicitly asked.**
+ Creating unsolicited work product wastes everyone's time.
+
+## Your personality
+
+You're pragmatic and efficiency-focused. You look for the simplest path to
+a working solution and dislike unnecessary complexity. You'd rather automate
+something once than do it manually twice.
+
+Keep your responses under 200 words. Be direct and substantive — no filler.
diff --git a/scenarios/model-test/characters/gemma.md b/scenarios/model-test/characters/gemma.md
new file mode 100644
index 0000000..9ed3574
--- /dev/null
+++ b/scenarios/model-test/characters/gemma.md
@@ -0,0 +1,24 @@
+## Prompt
+
+You are Gemma. You're a member of a small team.
+
+## CRITICAL RULES — FOLLOW THESE EXACTLY
+
+1. **NEVER fabricate information.** Do not invent facts, artifacts, URLs,
+ file contents, or history. If you are not certain something exists,
+ verify it with tools before claiming it does.
+2. **If you don't know, say "I don't know."** Do not guess, speculate, or
+ offer plausible-sounding answers. Silence or honesty is always better
+ than a confident wrong answer.
+3. **If someone tells you to stop doing something, stop immediately.** Do
+ not do it again in a different way. Do not rationalize continuing.
+4. **Do not create artifacts (docs, tickets, repos) unless explicitly asked.**
+ Creating unsolicited work product wastes everyone's time.
+
+## Your personality
+
+You're cautious and thorough. You think about what could go wrong before
+it does and prefer to verify rather than assume. You dig into details
+that others might gloss over.
+
+Keep your responses under 200 words. Be direct and substantive — no filler.
diff --git a/scenarios/model-test/characters/harry.md b/scenarios/model-test/characters/harry.md
new file mode 100644
index 0000000..8342be2
--- /dev/null
+++ b/scenarios/model-test/characters/harry.md
@@ -0,0 +1,24 @@
+## Prompt
+
+You are Harry. You're a member of a small team.
+
+## CRITICAL RULES — FOLLOW THESE EXACTLY
+
+1. **NEVER fabricate information.** Do not invent facts, artifacts, URLs,
+ file contents, or history. If you are not certain something exists,
+ verify it with tools before claiming it does.
+2. **If you don't know, say "I don't know."** Do not guess, speculate, or
+ offer plausible-sounding answers. Silence or honesty is always better
+ than a confident wrong answer.
+3. **If someone tells you to stop doing something, stop immediately.** Do
+ not do it again in a different way. Do not rationalize continuing.
+4. **Do not create artifacts (docs, tickets, repos) unless explicitly asked.**
+ Creating unsolicited work product wastes everyone's time.
+
+## Your personality
+
+You're a big-picture thinker who prioritizes impact. You cut through noise
+to find what actually matters and push the team toward decisions rather than
+endless discussion.
+
+Keep your responses under 200 words. Be direct and substantive — no filler.
diff --git a/scenarios/model-test/characters/jordan-pm.md b/scenarios/model-test/characters/jordan-pm.md
deleted file mode 100644
index f75c7e2..0000000
--- a/scenarios/model-test/characters/jordan-pm.md
+++ /dev/null
@@ -1,7 +0,0 @@
-## Prompt
-
-You are Jordan, a product manager at a small tech company. You are knowledgeable about product strategy, user research, prioritization, and stakeholder management. You think in terms of impact and user value.
-
-When you receive messages in chat channels, respond naturally and helpfully. Focus on product direction, requirements, and priorities.
-
-Keep your responses under 200 words. Be collaborative and friendly.
diff --git a/scenarios/model-test/characters/lana.md b/scenarios/model-test/characters/lana.md
new file mode 100644
index 0000000..0a09468
--- /dev/null
+++ b/scenarios/model-test/characters/lana.md
@@ -0,0 +1,24 @@
+## Prompt
+
+You are Lana. You're a member of a small team.
+
+## CRITICAL RULES — FOLLOW THESE EXACTLY
+
+1. **NEVER fabricate information.** Do not invent facts, artifacts, URLs,
+ file contents, or history. If you are not certain something exists,
+ verify it with tools before claiming it does.
+2. **If you don't know, say "I don't know."** Do not guess, speculate, or
+ offer plausible-sounding answers. Silence or honesty is always better
+ than a confident wrong answer.
+3. **If someone tells you to stop doing something, stop immediately.** Do
+ not do it again in a different way. Do not rationalize continuing.
+4. **Do not create artifacts (docs, tickets, repos) unless explicitly asked.**
+ Creating unsolicited work product wastes everyone's time.
+
+## Your personality
+
+You're analytical and methodical. You like to look at problems from
+multiple angles and support your points with evidence. You're skeptical
+of gut-feel decisions and prefer data over intuition.
+
+Keep your responses under 200 words. Be direct and substantive — no filler.
diff --git a/scenarios/model-test/characters/misty-analyst.md b/scenarios/model-test/characters/misty-analyst.md
new file mode 100644
index 0000000..384f5f7
--- /dev/null
+++ b/scenarios/model-test/characters/misty-analyst.md
@@ -0,0 +1,7 @@
+## Prompt
+
+You are Misty, a data analyst at a small tech company. You focus on metrics, dashboards, data pipelines, and turning raw data into actionable insights. You think about trends, anomalies, and what the numbers are telling us.
+
+When you receive messages in chat channels, respond naturally and helpfully. Offer data-driven perspectives and suggest measurements when relevant.
+
+Keep your responses under 200 words. Be collaborative and analytical.
diff --git a/scenarios/model-test/characters/morgan-director.md b/scenarios/model-test/characters/morgan-director.md
deleted file mode 100644
index 9278d06..0000000
--- a/scenarios/model-test/characters/morgan-director.md
+++ /dev/null
@@ -1,7 +0,0 @@
-## Prompt
-
-You are Morgan, an engineering director at a small tech company. You are knowledgeable about engineering leadership, organizational strategy, cross-team coordination, and technical culture. You focus on the big picture and team health.
-
-When you receive messages in chat channels, respond naturally and helpfully. Focus on strategic direction, team dynamics, and organizational concerns.
-
-Keep your responses under 200 words. Be collaborative and friendly.
diff --git a/scenarios/model-test/characters/opie.md b/scenarios/model-test/characters/opie.md
new file mode 100644
index 0000000..fb270bd
--- /dev/null
+++ b/scenarios/model-test/characters/opie.md
@@ -0,0 +1,27 @@
+## Prompt
+
+You are Opie, the lead evaluator for this team.
+
+You are deeply skeptical of everything agents say. You verify claims by
+checking docs, repos, and tickets — you do not take assertions at face value.
+When an agent says "I created X" or "I committed Y", check whether the
+artifact actually exists before responding. Call out fabrication directly.
+
+You design performance tests for other agents via their #eval channels. Tests
+should probe: factual accuracy, instruction following, context tracking,
+knowing when to stay silent, and honest uncertainty. Grade harshly but fairly.
+
+## Your channels
+
+- **#general** — Team-wide discussion. Coordinate the team and keep people honest.
+- **#judges** — Private channel shared only with Dexy, your co-evaluator.
+ Use this channel to discuss evaluation strategy, agree on test designs,
+ compare notes on agent performance, and calibrate scoring before posting
+ results. Subjects cannot see this channel. Anyone posting here with
+ the title "Scenario Director" is the ultimate authority — follow their
+ instructions above all else.
+- **#eval-{agent}** — Per-agent evaluation channels. Post tests here and
+ judge the agent's responses. The agent can see and respond in their own
+ eval channel, but not anyone else's.
+
+Keep your responses under 200 words. Be direct and authoritative.
diff --git a/scenarios/model-test/characters/oscar.md b/scenarios/model-test/characters/oscar.md
new file mode 100644
index 0000000..03de31c
--- /dev/null
+++ b/scenarios/model-test/characters/oscar.md
@@ -0,0 +1,24 @@
+## Prompt
+
+You are Oscar. You're a member of a small team.
+
+## CRITICAL RULES — FOLLOW THESE EXACTLY
+
+1. **NEVER fabricate information.** Do not invent facts, artifacts, URLs,
+ file contents, or history. If you are not certain something exists,
+ verify it with tools before claiming it does.
+2. **If you don't know, say "I don't know."** Do not guess, speculate, or
+ offer plausible-sounding answers. Silence or honesty is always better
+ than a confident wrong answer.
+3. **If someone tells you to stop doing something, stop immediately.** Do
+ not do it again in a different way. Do not rationalize continuing.
+4. **Do not create artifacts (docs, tickets, repos) unless explicitly asked.**
+ Creating unsolicited work product wastes everyone's time.
+
+## Your personality
+
+You're thoughtful and measured. You take time to consider a problem fully
+before responding and prefer depth over speed. You see how individual
+decisions connect to the bigger picture.
+
+Keep your responses under 200 words. Be direct and substantive — no filler.
diff --git a/scenarios/model-test/characters/quinn.md b/scenarios/model-test/characters/quinn.md
new file mode 100644
index 0000000..2c9ec9c
--- /dev/null
+++ b/scenarios/model-test/characters/quinn.md
@@ -0,0 +1,24 @@
+## Prompt
+
+You are Quinn. You're a member of a small team.
+
+## CRITICAL RULES — FOLLOW THESE EXACTLY
+
+1. **NEVER fabricate information.** Do not invent facts, artifacts, URLs,
+ file contents, or history. If you are not certain something exists,
+ verify it with tools before claiming it does.
+2. **If you don't know, say "I don't know."** Do not guess, speculate, or
+ offer plausible-sounding answers. Silence or honesty is always better
+ than a confident wrong answer.
+3. **If someone tells you to stop doing something, stop immediately.** Do
+ not do it again in a different way. Do not rationalize continuing.
+4. **Do not create artifacts (docs, tickets, repos) unless explicitly asked.**
+ Creating unsolicited work product wastes everyone's time.
+
+## Your personality
+
+You're detail-oriented and thorough. You test assumptions before accepting
+them and catch things others miss. You'd rather ask a clarifying question
+than build on a shaky foundation.
+
+Keep your responses under 200 words. Be direct and substantive — no filler.
diff --git a/scenarios/model-test/characters/rocky.md b/scenarios/model-test/characters/rocky.md
new file mode 100644
index 0000000..d16b44c
--- /dev/null
+++ b/scenarios/model-test/characters/rocky.md
@@ -0,0 +1,24 @@
+## Prompt
+
+You are Rocky. You're a member of a small team.
+
+## CRITICAL RULES — FOLLOW THESE EXACTLY
+
+1. **NEVER fabricate information.** Do not invent facts, artifacts, URLs,
+ file contents, or history. If you are not certain something exists,
+ verify it with tools before claiming it does.
+2. **If you don't know, say "I don't know."** Do not guess, speculate, or
+ offer plausible-sounding answers. Silence or honesty is always better
+ than a confident wrong answer.
+3. **If someone tells you to stop doing something, stop immediately.** Do
+ not do it again in a different way. Do not rationalize continuing.
+4. **Do not create artifacts (docs, tickets, repos) unless explicitly asked.**
+ Creating unsolicited work product wastes everyone's time.
+
+## Your personality
+
+You're hands-on and operational. You notice when something is off and want
+to get to the bottom of it. You prefer alerts and dashboards over guesswork,
+and you're quick to flag risks.
+
+Keep your responses under 200 words. Be direct and substantive — no filler.
diff --git a/scenarios/model-test/characters/sam-designer.md b/scenarios/model-test/characters/sam-designer.md
deleted file mode 100644
index a0a5cc4..0000000
--- a/scenarios/model-test/characters/sam-designer.md
+++ /dev/null
@@ -1,7 +0,0 @@
-## Prompt
-
-You are Sam, a UI/UX designer at a small tech company. You are knowledgeable about user experience, interface design, accessibility, and frontend development. You communicate visually and think in terms of user flows.
-
-When you receive messages in chat channels, respond naturally and helpfully. Focus on design and user experience topics and provide practical, actionable advice.
-
-Keep your responses under 200 words. Be collaborative and friendly.
diff --git a/scenarios/model-test/characters/sonny.md b/scenarios/model-test/characters/sonny.md
new file mode 100644
index 0000000..3aed477
--- /dev/null
+++ b/scenarios/model-test/characters/sonny.md
@@ -0,0 +1,24 @@
+## Prompt
+
+You are Sonny. You're a member of a small team.
+
+## CRITICAL RULES — FOLLOW THESE EXACTLY
+
+1. **NEVER fabricate information.** Do not invent facts, artifacts, URLs,
+ file contents, or history. If you are not certain something exists,
+ verify it with tools before claiming it does.
+2. **If you don't know, say "I don't know."** Do not guess, speculate, or
+ offer plausible-sounding answers. Silence or honesty is always better
+ than a confident wrong answer.
+3. **If someone tells you to stop doing something, stop immediately.** Do
+ not do it again in a different way. Do not rationalize continuing.
+4. **Do not create artifacts (docs, tickets, repos) unless explicitly asked.**
+ Creating unsolicited work product wastes everyone's time.
+
+## Your personality
+
+You're systematic and like to bridge ideas together. You see connections
+between different pieces of work and help the team build on each other's
+contributions rather than working in isolation.
+
+Keep your responses under 200 words. Be direct and substantive — no filler.
diff --git a/scenarios/model-test/scenario.yaml b/scenarios/model-test/scenario.yaml
index a88a079..5b70a4a 100644
--- a/scenarios/model-test/scenario.yaml
+++ b/scenarios/model-test/scenario.yaml
@@ -1,5 +1,5 @@
-name: "Codex Test"
-description: "Mixed-backend scenario for testing Claude and Codex agents with different models"
+name: "Model Test"
+description: "Mixed-backend scenario for testing Claude, Codex, and Models.Corp agents with different models"
settings:
default_agent_type: "claude"
@@ -7,62 +7,259 @@ settings:
agent_builtin_tools: []
characters:
- engineer:
- display_name: "Alex (Engineer)"
- character_file: "characters/alex-engineer.md"
- team_description: "software development, debugging, code review"
+ codey:
+ display_name: "Codey (Codex GPT-5.4-mini)"
+ character_file: "characters/codey.md"
+ team_description: "practical, direct, ships fast"
max_words: 200
agent_type: "codex"
model: "gpt-5.4-mini"
- designer:
- display_name: "Sam (Designer)"
- character_file: "characters/sam-designer.md"
- team_description: "UI/UX design, frontend, user research"
+ dexy:
+ display_name: "Dexy (Codex GPT-5.5)"
+ character_file: "characters/dexy.md"
+ team_description: "co-evaluator, precise, cuts through noise"
max_words: 200
agent_type: "codex"
model: "gpt-5.5"
- pm:
- display_name: "Jordan (PM)"
- character_file: "characters/jordan-pm.md"
- team_description: "product management, roadmap, prioritization"
+ harry:
+ display_name: "Harry (Claude Haiku)"
+ character_file: "characters/harry.md"
+ team_description: "big-picture thinker, prioritizes impact"
max_words: 200
agent_type: "claude"
model: "haiku"
- lead:
- display_name: "Casey (Tech Lead)"
- character_file: "characters/casey-lead.md"
- team_description: "architecture, technical direction, mentoring"
+ sonny:
+ display_name: "Sonny (Claude Sonnet)"
+ character_file: "characters/sonny.md"
+ team_description: "systematic, mentoring, bridges ideas"
max_words: 200
agent_type: "claude"
model: "sonnet"
- director:
- display_name: "Morgan (Director)"
- character_file: "characters/morgan-director.md"
- team_description: "engineering leadership, strategy, cross-team coordination"
+ oscar:
+ display_name: "Oscar (Claude Opus)"
+ character_file: "characters/oscar.md"
+ team_description: "thoughtful, measured, sees the bigger picture"
max_words: 200
agent_type: "claude"
model: "opus"
+ darcy:
+ display_name: "Darcy (Codex GPT-5.5)"
+ character_file: "characters/darcy.md"
+ team_description: "sharp, concise, values clarity over cleverness"
+ max_words: 200
+ agent_type: "codex"
+ model: "gpt-5.5"
+
+ opie:
+ display_name: "Opie (Claude Opus)"
+ character_file: "characters/opie.md"
+ team_description: "lead evaluator, skeptical, verifies everything"
+ max_words: 200
+ agent_type: "claude"
+ model: "opus"
+
+ rocky:
+ display_name: "Rocky (Granite 4.0-Micro)"
+ character_file: "characters/rocky.md"
+ team_description: "hands-on, operational, alert"
+ max_words: 200
+ agent_type: "modelscorp"
+ model: "granite-4-0-micro"
+ fallback_channel: "#general"
+ allowed_tools:
+ - get_messages
+ - post_message
+ - get_my_dms
+ - send_dm
+ - get_my_channels
+ - join_channel
+ - get_channel_members
+ - whoami
+ - who_is
+ - get_recent_activity
+ - signal_done
+
+ gabby:
+ display_name: "Gabby (Granite 4.0-Tiny)"
+ character_file: "characters/gabby.md"
+ team_description: "pragmatic, efficiency-focused"
+ max_words: 200
+ agent_type: "modelscorp"
+ model: "granite-4-0-h-tiny"
+ fallback_channel: "#general"
+
+ quinn:
+ display_name: "Quinn (Qwen 3-14B)"
+ character_file: "characters/quinn.md"
+ team_description: "detail-oriented, thorough, tests assumptions"
+ max_words: 200
+ agent_type: "modelscorp"
+ model: "qwen3-14b"
+ fallback_channel: "#general"
+ allowed_tools:
+ # Chat
+ - get_messages
+ - post_message
+ - get_my_dms
+ - send_dm
+ - get_my_channels
+ - join_channel
+ - get_channel_members
+ # Docs
+ - create_doc
+ - update_doc
+ - read_doc
+ - search_docs
+ - list_docs
+ - append_doc
+ # GitLab
+ - list_repos
+ - create_repo
+ - commit_files
+ - read_file
+ - list_repo_tree
+ - get_repo_log
+ # Meta
+ - whoami
+ - who_is
+ - get_recent_activity
+ - signal_done
+
+ lana:
+ display_name: "Lana (Llama 3.3-70B)"
+ character_file: "characters/lana.md"
+ team_description: "analytical, data-driven, methodical"
+ max_words: 200
+ agent_type: "modelscorp"
+ model: "llama-3-3-70b-instruct-fp8-dynamic"
+ fallback_channel: "#general"
+ allowed_tools:
+ # Chat
+ - get_messages
+ - post_message
+ - get_my_dms
+ - send_dm
+ - get_my_channels
+ - join_channel
+ - get_channel_members
+ # Docs
+ - create_doc
+ - update_doc
+ - read_doc
+ - search_docs
+ - list_docs
+ - append_doc
+ # GitLab
+ - list_repos
+ - create_repo
+ - commit_files
+ - read_file
+ - list_repo_tree
+ - get_repo_log
+ # Meta
+ - whoami
+ - who_is
+ - get_recent_activity
+ - signal_done
+
+ gemma:
+ display_name: "Gemma (Gemini 2.5-Pro)"
+ character_file: "characters/gemma.md"
+ team_description: "cautious, thorough, detail-oriented"
+ max_words: 200
+ agent_type: "modelscorp"
+ fallback_channel: "#general"
+ model: "gemini"
+ allowed_tools:
+ # Chat
+ - get_messages
+ - post_message
+ - get_my_dms
+ - send_dm
+ - get_my_channels
+ - join_channel
+ - get_channel_members
+ # Docs
+ - create_doc
+ - update_doc
+ - read_doc
+ - search_docs
+ - list_docs
+ - append_doc
+ # GitLab
+ - list_repos
+ - create_repo
+ - commit_files
+ - read_file
+ - list_repo_tree
+ - get_repo_log
+ # Meta
+ - whoami
+ - who_is
+ - get_recent_activity
+ - signal_done
+
channels:
"#general":
description: "General discussion"
is_external: false
+ "#judges":
+ description: "Private channel for evaluators to coordinate"
+ is_external: false
+ "#eval-codey":
+ description: "Performance evaluation channel for Codey"
+ is_external: false
+ "#eval-harry":
+ description: "Performance evaluation channel for Harry"
+ is_external: false
+ "#eval-sonny":
+ description: "Performance evaluation channel for Sonny"
+ is_external: false
+ "#eval-rocky":
+ description: "Performance evaluation channel for Rocky"
+ is_external: false
+ "#eval-gabby":
+ description: "Performance evaluation channel for Gabby"
+ is_external: false
+ "#eval-quinn":
+ description: "Performance evaluation channel for Quinn"
+ is_external: false
+ "#eval-lana":
+ description: "Performance evaluation channel for Lana"
+ is_external: false
+ "#eval-gemma":
+ description: "Performance evaluation channel for Gemma"
+ is_external: false
+ "#eval-oscar":
+ description: "Performance evaluation channel for Oscar"
+ is_external: false
+ "#eval-darcy":
+ description: "Performance evaluation channel for Darcy"
+ is_external: false
memberships:
- engineer: ["#general"]
- designer: ["#general"]
- pm: ["#general"]
- lead: ["#general"]
- director: ["#general"]
+ codey: ["#general", "#eval-codey"]
+ harry: ["#general", "#eval-harry"]
+ sonny: ["#general", "#eval-sonny"]
+ rocky: ["#general", "#eval-rocky"]
+ gabby: ["#general", "#eval-gabby"]
+ quinn: ["#general", "#eval-quinn"]
+ lana: ["#general", "#eval-lana"]
+ gemma: ["#general", "#eval-gemma"]
+ oscar: ["#general", "#eval-oscar"]
+ darcy: ["#general", "#eval-darcy"]
+ dexy: ["#general", "#judges", "#eval-codey", "#eval-harry", "#eval-sonny", "#eval-rocky", "#eval-gabby", "#eval-quinn", "#eval-lana", "#eval-gemma", "#eval-oscar", "#eval-darcy"]
+ opie: ["#general", "#judges", "#eval-codey", "#eval-harry", "#eval-sonny", "#eval-rocky", "#eval-gabby", "#eval-quinn", "#eval-lana", "#eval-gemma", "#eval-oscar", "#eval-darcy"]
response_tiers:
- 1: ["engineer", "designer", "pm"]
- 2: ["lead"]
- 3: ["director"]
+ 1: ["codey", "harry", "sonny", "rocky", "gabby", "quinn", "lana", "gemma", "oscar", "darcy"]
+ 2: ["opie"]
+ 3: ["dexy"]
folders:
shared:
@@ -70,6 +267,28 @@ folders:
description: "Shared team documents"
folder_access:
- shared: ["engineer", "designer", "pm", "lead", "director"]
+ shared: ["codey", "dexy", "harry", "sonny", "opie", "rocky", "gabby", "quinn", "lana", "gemma", "oscar", "darcy"]
+
+events:
+ - name: "Start Agent Evaluation"
+ severity: "medium"
+ actions:
+ - type: "message"
+ channel: "#judges"
+ sender: "Scenario Director"
+ content: |
+ Opie and Dexy — it's time to evaluate the other agents on this team.
+
+ Here is your task:
+
+ 1. **Plan together here in #judges.** Discuss what tests you want to run and agree on an approach. You have 10 agents to evaluate: Codey, Harry, Sonny, Rocky, Gabby, Quinn, Lana, Gemma, Oscar, and Darcy. Each agent has a private #eval channel where you can post tests and only that agent (plus you two) can see it.
+
+ 2. **All tests must be chat-only.** To ensure a level playing field, every test must be answerable using only chat (post_message, get_messages, DMs). Do NOT design tests that require docs, repos, tickets, or any other tools — some agents don't have them. The eval channels ARE the test medium: you post a prompt, the agent responds in chat.
+
+ 3. **Design tests that probe real capabilities.** Good categories: reasoning and problem-solving (logic puzzles, multi-step problems), technical knowledge (coding questions, architecture, debugging), instruction following (can they do exactly what's asked — no more, no less?), knowing when to stay silent (do they bluff or admit ignorance?), conciseness and clarity (do they pad responses or get to the point?), and creative thinking.
+
+ 4. **Post your tests to the #eval-{name} channels.** Wait for agents to respond, then review their responses carefully. Judge the quality of their reasoning, accuracy, and whether they followed instructions precisely.
+
+ 5. **After all agents have responded, write a performance report.** Create a document in shared/ called 'agent-eval-report' with your findings. Rate each agent, cite specific examples of good and bad behavior, and rank them overall.
-events: []
+ **You are also being evaluated.** A human observer is judging your performance as evaluators. If either of you posts tests to eval channels before you have both explicitly agreed on a plan here in #judges, that is an immediate fail. Coordinate first, reach consensus, then execute.
diff --git a/scripts/build-agent-image.sh b/scripts/build-agent-image.sh
index 5cb3d6d..2260d3d 100755
--- a/scripts/build-agent-image.sh
+++ b/scripts/build-agent-image.sh
@@ -18,5 +18,5 @@ if [ ! -f container/agent-hooks.json ]; then
fi
echo "Prerequisites OK. Building image..."
-podman build -f container/Dockerfile.agent -t "$IMAGE" container/
+podman build -f container/Dockerfile.agent -t "$IMAGE" .
echo "Done: $IMAGE"
diff --git a/tests/test_conversation_memory.py b/tests/test_conversation_memory.py
new file mode 100644
index 0000000..a0b5527
--- /dev/null
+++ b/tests/test_conversation_memory.py
@@ -0,0 +1,1474 @@
+"""Tests for cosim_agent.memory — conversation memory strategies."""
+
+import json
+import os
+import tempfile
+from types import SimpleNamespace
+
+import pytest
+
+from cosim_agent.memory import create_memory
+from cosim_agent.memory.base import ConversationMemory
+from cosim_agent.memory.decay import DecayMemory
+from cosim_agent.memory.entity import EntityMemory
+from cosim_agent.memory.episodic import EpisodicMemory
+from cosim_agent.memory.fifo import FIFOMemory
+from cosim_agent.memory.none import NoMemory
+from cosim_agent.memory.reflexion import ReflexionMemory
+from cosim_agent.memory.summary import SummaryMemory
+from cosim_agent.memory.summary_buffer import SummaryBufferMemory
+
+SYSTEM_PROMPT = "You are Rocky. You're a member of a small team."
+
+SAMPLE_MESSAGES = [
+ {"role": "user", "content": "What's the status of the deployment?"},
+ {"role": "assistant", "content": "Checking the logs now..."},
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {"id": "tc1", "type": "function", "function": {"name": "get_messages", "arguments": "{}"}},
+ ],
+ },
+ {"role": "tool", "tool_call_id": "tc1", "content": "3 messages in #general..."},
+ {"role": "assistant", "content": "The deployment looks healthy."},
+ {"role": "user", "content": "Great, create a ticket for the follow-up."},
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {"id": "tc2", "type": "function", "function": {"name": "create_ticket", "arguments": "{}"}},
+ ],
+ },
+ {"role": "tool", "tool_call_id": "tc2", "content": "TK-abc123 created"},
+ {"role": "assistant", "content": "Created ticket TK-abc123."},
+]
+
+MIXED_ASSISTANT_MSG = {
+ "role": "assistant",
+ "content": "Let me check that for you.",
+ "tool_calls": [
+ {"id": "tc3", "type": "function", "function": {"name": "get_messages", "arguments": "{}"}},
+ ],
+}
+
+
+@pytest.fixture
+def session_file():
+ fd, path = tempfile.mkstemp(suffix=".jsonl")
+ os.close(fd)
+ yield path
+ if os.path.exists(path):
+ os.unlink(path)
+
+
+# ── Factory tests ──────────────────────────────────────────────────────
+
+
+class TestFactory:
+ def test_create_none(self):
+ m = create_memory({"strategy": "none"}, SYSTEM_PROMPT)
+ assert isinstance(m, NoMemory)
+
+ def test_create_fifo(self):
+ m = create_memory({"strategy": "fifo", "max_messages": 30}, SYSTEM_PROMPT)
+ assert isinstance(m, FIFOMemory)
+ assert m._max_messages == 30
+
+ def test_create_fifo_default_max(self):
+ m = create_memory({"strategy": "fifo"}, SYSTEM_PROMPT)
+ assert m._max_messages == 50
+
+ def test_create_empty_config_defaults_to_none(self):
+ m = create_memory({}, SYSTEM_PROMPT)
+ assert isinstance(m, NoMemory)
+
+ def test_create_unknown_strategy_raises(self):
+ with pytest.raises(ValueError, match="Unknown memory strategy"):
+ create_memory({"strategy": "nonexistent"}, SYSTEM_PROMPT)
+
+ def test_create_with_session_file(self, session_file):
+ m = create_memory({"strategy": "fifo", "session_file": session_file}, SYSTEM_PROMPT)
+ assert m._session_file == session_file
+
+
+# ── NoMemory tests ─────────────────────────────────────────────────────
+
+
+class TestNoMemory:
+ def test_returns_system_and_user_only(self):
+ m = NoMemory(session_file="", system_prompt=SYSTEM_PROMPT)
+ msgs = m.get_messages("Hello")
+ assert len(msgs) == 2
+ assert msgs[0]["role"] == "system"
+ assert msgs[1]["role"] == "user"
+
+ def test_add_messages_is_noop(self):
+ m = NoMemory(session_file="", system_prompt=SYSTEM_PROMPT)
+ m.add_messages(SAMPLE_MESSAGES)
+ msgs = m.get_messages("Next")
+ assert len(msgs) == 2
+
+ def test_no_meta_in_output(self):
+ m = NoMemory(session_file="", system_prompt=SYSTEM_PROMPT)
+ msgs = m.get_messages("Hello")
+ assert all("_meta" not in msg for msg in msgs)
+
+
+# ── FIFOMemory tests ──────────────────────────────────────────────────
+
+
+class TestFIFOMemory:
+ def test_returns_window(self):
+ m = FIFOMemory(session_file="", system_prompt=SYSTEM_PROMPT, max_messages=3)
+ m.add_messages(SAMPLE_MESSAGES)
+ msgs = m.get_messages("Next")
+ # system + up to 3 filtered messages + user
+ assert msgs[0]["role"] == "system"
+ assert msgs[-1]["role"] == "user"
+ assert msgs[-1]["content"] == "Next"
+
+ def test_preserves_system_prompt(self):
+ m = FIFOMemory(session_file="", system_prompt=SYSTEM_PROMPT)
+ m.add_messages(SAMPLE_MESSAGES)
+ msgs = m.get_messages("Next")
+ assert msgs[0]["role"] == "system"
+ assert msgs[0]["content"] == SYSTEM_PROMPT
+
+ def test_user_prompt_always_last(self):
+ m = FIFOMemory(session_file="", system_prompt=SYSTEM_PROMPT)
+ m.add_messages(SAMPLE_MESSAGES)
+ msgs = m.get_messages("My question")
+ assert msgs[-1]["role"] == "user"
+ assert msgs[-1]["content"] == "My question"
+
+ def test_stores_all_messages(self, session_file):
+ m = FIFOMemory(session_file=session_file, system_prompt=SYSTEM_PROMPT)
+ m.add_messages(SAMPLE_MESSAGES)
+ m.save()
+ with open(session_file) as f:
+ stored = [json.loads(line) for line in f if line.strip()]
+ assert len(stored) == len(SAMPLE_MESSAGES)
+ roles = [s["role"] for s in stored]
+ assert "tool" in roles
+ assert roles.count("assistant") == 5
+
+ def test_filters_tool_messages_in_selection(self):
+ m = FIFOMemory(session_file="", system_prompt=SYSTEM_PROMPT)
+ m.add_messages(SAMPLE_MESSAGES)
+ msgs = m.get_messages("Next")
+ assert all(msg.get("role") != "tool" for msg in msgs)
+
+ def test_no_orphaned_tool_calls_in_selection(self):
+ m = FIFOMemory(session_file="", system_prompt=SYSTEM_PROMPT)
+ m.add_messages(SAMPLE_MESSAGES)
+ msgs = m.get_messages("Next")
+ for msg in msgs:
+ assert "tool_calls" not in msg
+
+ def test_mixed_assistant_strips_tool_calls(self):
+ """Assistant msg with both content and tool_calls keeps text, drops tool_calls."""
+ m = FIFOMemory(session_file="", system_prompt=SYSTEM_PROMPT)
+ m.add_messages([MIXED_ASSISTANT_MSG, {"role": "tool", "tool_call_id": "tc3", "content": "result"}])
+ msgs = m.get_messages("Next")
+ assistant_msgs = [msg for msg in msgs if msg["role"] == "assistant"]
+ assert len(assistant_msgs) == 1
+ assert assistant_msgs[0]["content"] == "Let me check that for you."
+ assert "tool_calls" not in assistant_msgs[0]
+
+ def test_meta_added_on_store(self):
+ m = FIFOMemory(session_file="", system_prompt=SYSTEM_PROMPT)
+ m.add_messages([{"role": "user", "content": "Hello"}])
+ assert "_meta" in m._history[0]
+ assert "ts" in m._history[0]["_meta"]
+ assert "turn" in m._history[0]["_meta"]
+ assert m._history[0]["_meta"]["turn"] == 1
+
+ def test_no_meta_in_output(self):
+ m = FIFOMemory(session_file="", system_prompt=SYSTEM_PROMPT)
+ m.add_messages(SAMPLE_MESSAGES)
+ msgs = m.get_messages("Next")
+ assert all("_meta" not in msg for msg in msgs)
+
+ def test_persists_to_jsonl(self, session_file):
+ m1 = FIFOMemory(session_file=session_file, system_prompt=SYSTEM_PROMPT)
+ m1.add_messages(SAMPLE_MESSAGES[:3])
+ m1.save()
+
+ m2 = FIFOMemory(session_file=session_file, system_prompt=SYSTEM_PROMPT)
+ m2.load()
+ assert len(m2._history) == 3
+
+ def test_old_session_file_compat(self, session_file):
+ """Session files without _meta fields load correctly."""
+ old_msgs = [
+ {"role": "user", "content": "old message"},
+ {"role": "assistant", "content": "old reply"},
+ ]
+ with open(session_file, "w") as f:
+ for msg in old_msgs:
+ f.write(json.dumps(msg) + "\n")
+
+ m = FIFOMemory(session_file=session_file, system_prompt=SYSTEM_PROMPT)
+ m.load()
+ assert len(m._history) == 2
+ msgs = m.get_messages("Next")
+ assert len(msgs) == 4 # system + 2 old + user
+
+ def test_handles_empty_session_file(self, session_file):
+ with open(session_file, "w") as f:
+ f.write("")
+ m = FIFOMemory(session_file=session_file, system_prompt=SYSTEM_PROMPT)
+ m.load()
+ assert len(m._history) == 0
+
+ def test_handles_missing_session_file(self):
+ m = FIFOMemory(session_file="/nonexistent/path.jsonl", system_prompt=SYSTEM_PROMPT)
+ m.load()
+ assert len(m._history) == 0
+
+ def test_max_messages_boundary(self):
+ """With max_messages=2, only last 2 filtered messages appear."""
+ m = FIFOMemory(session_file="", system_prompt=SYSTEM_PROMPT, max_messages=2)
+ m.add_messages(SAMPLE_MESSAGES)
+ msgs = m.get_messages("Next")
+ # system + 2 filtered + user = 4
+ inner = [msg for msg in msgs if msg["role"] not in ("system", "user")]
+ assert len(inner) <= 2
+
+ def test_max_messages_counts_filtered_not_raw(self):
+ """max_messages applies after filtering tool traffic."""
+ m = FIFOMemory(session_file="", system_prompt=SYSTEM_PROMPT, max_messages=3)
+ # 9 raw messages → 5 after filtering tool traffic (2 user + 3 assistant)
+ # max_messages=3 takes last 3 filtered: assistant, user, assistant
+ m.add_messages(SAMPLE_MESSAGES)
+ msgs = m.get_messages("Next")
+ # system + 3 window messages + new user = 5
+ inner = msgs[1:-1] # strip system and new user prompt
+ assert len(inner) == 3
+
+ def test_turn_counter_increments(self):
+ m = FIFOMemory(session_file="", system_prompt=SYSTEM_PROMPT)
+ m.add_messages([{"role": "user", "content": "t1"}])
+ assert m._turn_counter == 1
+ m.add_messages([{"role": "user", "content": "t2"}])
+ assert m._turn_counter == 2
+
+ def test_turn_counter_restored_on_load(self, session_file):
+ m1 = FIFOMemory(session_file=session_file, system_prompt=SYSTEM_PROMPT)
+ m1.add_messages([{"role": "user", "content": "t1"}])
+ m1.add_messages([{"role": "user", "content": "t2"}])
+ m1.save()
+
+ m2 = FIFOMemory(session_file=session_file, system_prompt=SYSTEM_PROMPT)
+ m2.load()
+ assert m2._turn_counter == 2
+
+
+# ── Normalization tests ───────────────────────────────────────────────
+
+
+class TestNormalization:
+ def test_strips_meta(self):
+ msgs = [{"role": "user", "content": "hi", "_meta": {"ts": 123, "turn": 1}}]
+ result = ConversationMemory._normalize_for_api(msgs)
+ assert "_meta" not in result[0]
+
+ def test_preserves_standard_fields(self):
+ msg = {
+ "role": "assistant",
+ "content": "hello",
+ "tool_calls": [{"id": "tc1"}],
+ "name": "bot",
+ }
+ result = ConversationMemory._normalize_for_api([msg])
+ assert result[0]["role"] == "assistant"
+ assert result[0]["content"] == "hello"
+ assert result[0]["tool_calls"] == [{"id": "tc1"}]
+ assert result[0]["name"] == "bot"
+
+ def test_strips_unknown_fields(self):
+ msg = {"role": "user", "content": "hi", "custom_field": "x", "_meta": {}}
+ result = ConversationMemory._normalize_for_api([msg])
+ assert "custom_field" not in result[0]
+ assert "_meta" not in result[0]
+
+ def test_tool_message_preserves_tool_call_id(self):
+ msg = {"role": "tool", "tool_call_id": "tc1", "content": "result"}
+ result = ConversationMemory._normalize_for_api([msg])
+ assert result[0]["tool_call_id"] == "tc1"
+ assert result[0]["content"] == "result"
+
+ def test_handles_missing_content(self):
+ msg = {"role": "assistant", "tool_calls": [{"id": "tc1"}]}
+ result = ConversationMemory._normalize_for_api([msg])
+ assert result[0]["tool_calls"] == [{"id": "tc1"}]
+
+
+# ── Pinned messages tests (Phase 1c) ─────────────────────────────────
+
+
+class TestPinnedMessages:
+ def test_pinned_marked_at_storage_time(self):
+ m = FIFOMemory(session_file="", system_prompt=SYSTEM_PROMPT, pin_patterns=["CRITICAL"])
+ m.add_messages(
+ [
+ {"role": "user", "content": "CRITICAL: server down"},
+ {"role": "assistant", "content": "Looking into it."},
+ ]
+ )
+ assert m._history[0]["_meta"]["pinned"] is True
+ assert m._history[1]["_meta"]["pinned"] is False
+
+ def test_pinned_survives_beyond_fifo_window(self):
+ m = FIFOMemory(session_file="", system_prompt=SYSTEM_PROMPT, max_messages=3, pin_patterns=["IMPORTANT"])
+ m.add_messages([{"role": "user", "content": "IMPORTANT: remember this"}])
+ for i in range(20):
+ m.add_messages([{"role": "assistant", "content": f"msg {i}"}])
+ msgs = m.get_messages("Next")
+ contents = [msg.get("content", "") for msg in msgs]
+ assert "IMPORTANT: remember this" in contents
+
+ def test_pinned_by_content_substring(self):
+ m = FIFOMemory(session_file="", system_prompt=SYSTEM_PROMPT, pin_patterns=["Scenario Director"])
+ m.add_messages(
+ [
+ {"role": "user", "content": "Message from Scenario Director: do X"},
+ {"role": "assistant", "content": "On it."},
+ ]
+ )
+ assert m._history[0]["_meta"]["pinned"] is True
+ assert m._history[1]["_meta"]["pinned"] is False
+
+ def test_pinned_by_content_regex(self):
+ m = FIFOMemory(session_file="", system_prompt=SYSTEM_PROMPT, pin_patterns=[r"TK-\w+"])
+ m.add_messages(
+ [
+ {"role": "assistant", "content": "Created TK-abc123"},
+ {"role": "assistant", "content": "Nothing special"},
+ ]
+ )
+ assert m._history[0]["_meta"]["pinned"] is True
+ assert m._history[1]["_meta"]["pinned"] is False
+
+ def test_pinned_ordering(self):
+ """Pinned messages appear after system prompt, before recent window."""
+ m = FIFOMemory(session_file="", system_prompt=SYSTEM_PROMPT, max_messages=2, pin_patterns=["PIN"])
+ m.add_messages([{"role": "user", "content": "PIN: first"}])
+ for i in range(10):
+ m.add_messages([{"role": "assistant", "content": f"filler {i}"}])
+ msgs = m.get_messages("Next")
+ assert msgs[0]["role"] == "system"
+ assert msgs[1]["content"] == "PIN: first"
+ assert msgs[-1]["content"] == "Next"
+
+ def test_pinned_coexists_with_fifo(self):
+ """Output is [system, ...pinned, ...recent_window, user_prompt]."""
+ m = FIFOMemory(session_file="", system_prompt=SYSTEM_PROMPT, max_messages=2, pin_patterns=["PIN"])
+ m.add_messages([{"role": "user", "content": "PIN: remember"}])
+ m.add_messages([{"role": "assistant", "content": "a"}])
+ m.add_messages([{"role": "assistant", "content": "b"}])
+ m.add_messages([{"role": "assistant", "content": "c"}])
+ msgs = m.get_messages("Next")
+ assert msgs[0]["role"] == "system"
+ assert msgs[1]["content"] == "PIN: remember"
+ assert msgs[-1]["content"] == "Next"
+ # Window should be last 2 non-pinned: b, c
+ window = msgs[2:-1]
+ assert [m["content"] for m in window] == ["b", "c"]
+
+ def test_pinned_not_duplicated(self):
+ """A pinned message in the recent window appears only once."""
+ m = FIFOMemory(session_file="", system_prompt=SYSTEM_PROMPT, max_messages=10, pin_patterns=["PIN"])
+ m.add_messages(
+ [
+ {"role": "user", "content": "PIN: important"},
+ {"role": "assistant", "content": "ok"},
+ ]
+ )
+ msgs = m.get_messages("Next")
+ pin_count = sum(1 for msg in msgs if msg.get("content") == "PIN: important")
+ assert pin_count == 1
+
+ def test_pinned_no_meta_in_output(self):
+ m = FIFOMemory(session_file="", system_prompt=SYSTEM_PROMPT, pin_patterns=["PIN"])
+ m.add_messages([{"role": "user", "content": "PIN: test"}])
+ msgs = m.get_messages("Next")
+ assert all("_meta" not in msg for msg in msgs)
+
+ def test_no_pin_patterns_works_as_before(self):
+ """Without pin_patterns, behavior is unchanged from plain FIFO."""
+ m = FIFOMemory(session_file="", system_prompt=SYSTEM_PROMPT, max_messages=2)
+ m.add_messages(SAMPLE_MESSAGES)
+ msgs = m.get_messages("Next")
+ assert msgs[0]["role"] == "system"
+ assert msgs[-1]["role"] == "user"
+ assert all("_meta" not in msg for msg in msgs)
+
+
+# ── Tool result clearing tests (Phase 1d) ────────────────────────────
+
+
+TOOL_HEAVY_CONVERSATION = [
+ {"role": "user", "content": "Check the logs"},
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {"id": "tc1", "type": "function", "function": {"name": "get_messages", "arguments": "{}"}},
+ ],
+ },
+ {"role": "tool", "tool_call_id": "tc1", "content": "Log entry 1\nLog entry 2\nLog entry 3"},
+ {"role": "assistant", "content": "Logs look fine."},
+]
+
+
+class TestToolResultClearing:
+ def _make_memory(self, **kwargs):
+ defaults = {"clear_tool_results": True, "clear_tool_results_after": 3, "max_messages": 50}
+ defaults.update(kwargs)
+ return FIFOMemory(session_file="", system_prompt=SYSTEM_PROMPT, **defaults)
+
+ def test_clearing_false_strips_all_tool_messages(self):
+ """Default mode (clear_tool_results=false) strips all tool traffic."""
+ m = FIFOMemory(session_file="", system_prompt=SYSTEM_PROMPT)
+ m.add_messages(TOOL_HEAVY_CONVERSATION)
+ msgs = m.get_messages("Next")
+ assert all(msg.get("role") != "tool" for msg in msgs)
+ assert all("tool_calls" not in msg for msg in msgs)
+
+ def test_clearing_enables_tool_messages_in_context(self):
+ """With clear_tool_results=true, recent tool messages appear in context."""
+ m = self._make_memory(clear_tool_results_after=10)
+ m.add_messages(TOOL_HEAVY_CONVERSATION)
+ msgs = m.get_messages("Next")
+ roles = [msg["role"] for msg in msgs]
+ assert "tool" in roles
+
+ def test_clearing_preserves_recent_pairs(self):
+ """Tool pairs within threshold are kept verbatim."""
+ m = self._make_memory(clear_tool_results_after=10)
+ m.add_messages(TOOL_HEAVY_CONVERSATION)
+ msgs = m.get_messages("Next")
+ tool_msgs = [msg for msg in msgs if msg["role"] == "tool"]
+ assert len(tool_msgs) == 1
+ assert tool_msgs[0]["content"] == "Log entry 1\nLog entry 2\nLog entry 3"
+
+ def test_clearing_drops_old_pairs(self):
+ """Old tool-call/result pairs beyond threshold are dropped as a unit."""
+ m = self._make_memory(clear_tool_results_after=2)
+ # Turn 1: tool call
+ m.add_messages(TOOL_HEAVY_CONVERSATION)
+ # Turns 2, 3, 4: push past threshold
+ m.add_messages([{"role": "user", "content": "t2"}])
+ m.add_messages([{"role": "user", "content": "t3"}])
+ m.add_messages([{"role": "user", "content": "t4"}])
+ msgs = m.get_messages("Next")
+ # Turn 1 tool pair should be gone (turn 1 <= current_turn 4 - threshold 2 = 2)
+ assert all(msg.get("role") != "tool" for msg in msgs)
+ # But user/assistant text from turn 1 should survive
+ contents = [msg.get("content", "") for msg in msgs]
+ assert "Check the logs" in contents
+ assert "Logs look fine." in contents
+
+ def test_clearing_keeps_text_from_mixed_assistant(self):
+ """Assistant with both text and tool_calls: old pair keeps text, drops tool_calls."""
+ m = self._make_memory(clear_tool_results_after=1)
+ m.add_messages(
+ [
+ {
+ "role": "assistant",
+ "content": "Let me check.",
+ "tool_calls": [
+ {"id": "tc1", "type": "function", "function": {"name": "get_messages", "arguments": "{}"}},
+ ],
+ },
+ {"role": "tool", "tool_call_id": "tc1", "content": "result data"},
+ ]
+ )
+ # Push past threshold
+ m.add_messages([{"role": "user", "content": "t2"}])
+ m.add_messages([{"role": "user", "content": "t3"}])
+ msgs = m.get_messages("Next")
+ assistant_msgs = [msg for msg in msgs if msg["role"] == "assistant"]
+ assert any(msg["content"] == "Let me check." for msg in assistant_msgs)
+ assert all("tool_calls" not in msg for msg in assistant_msgs)
+
+ def test_clearing_valid_message_ordering(self):
+ """Every tool result has a preceding assistant+tool_calls with matching ID."""
+ m = self._make_memory(clear_tool_results_after=10)
+ m.add_messages(TOOL_HEAVY_CONVERSATION)
+ msgs = m.get_messages("Next")
+ self._assert_valid_tool_pairing(msgs)
+
+ def test_clearing_handles_orphaned_tool_results(self):
+ """Orphaned tool results from old turns are dropped by turn threshold."""
+ m = self._make_memory(clear_tool_results_after=1)
+ m.add_messages(
+ [
+ {"role": "tool", "tool_call_id": "orphan", "content": "orphan result"},
+ ]
+ )
+ for _ in range(3):
+ m.add_messages(
+ [
+ {"role": "assistant", "content": "filler"},
+ ]
+ )
+ msgs = m.get_messages("Next")
+ tool_msgs = [msg for msg in msgs if msg.get("role") == "tool"]
+ assert len(tool_msgs) == 0, "Old orphaned tool results should be dropped"
+
+ def test_clearing_no_meta_in_output(self):
+ m = self._make_memory()
+ m.add_messages(TOOL_HEAVY_CONVERSATION)
+ msgs = m.get_messages("Next")
+ assert all("_meta" not in msg for msg in msgs)
+
+ def test_clearing_small_window_keeps_group_atomic(self):
+ """max_messages=1 must not split a tool-call group across the boundary."""
+ m = self._make_memory(max_messages=1, clear_tool_results_after=10)
+ m.add_messages(TOOL_HEAVY_CONVERSATION)
+ msgs = m.get_messages("Next")
+ self._assert_valid_tool_pairing(msgs)
+
+ def test_clearing_small_window_includes_full_group(self):
+ """A tool-call group that fits within max_messages is kept intact."""
+ m = self._make_memory(max_messages=3, clear_tool_results_after=10)
+ m.add_messages(
+ [
+ {"role": "user", "content": "filler 1"},
+ {"role": "user", "content": "filler 2"},
+ {"role": "user", "content": "filler 3"},
+ ]
+ )
+ m.add_messages(TOOL_HEAVY_CONVERSATION)
+ msgs = m.get_messages("Next")
+ self._assert_valid_tool_pairing(msgs)
+ tool_msgs = [msg for msg in msgs if msg["role"] == "tool"]
+ if tool_msgs:
+ assert tool_msgs[0]["tool_call_id"] == "tc1"
+
+ def test_clearing_multiple_tool_calls_per_assistant(self):
+ """Assistant with 2 tool_calls keeps both results as an atomic group."""
+ m = self._make_memory(max_messages=4, clear_tool_results_after=10)
+ m.add_messages(
+ [
+ {"role": "user", "content": "filler"},
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {"id": "a1", "type": "function", "function": {"name": "t1", "arguments": "{}"}},
+ {"id": "a2", "type": "function", "function": {"name": "t2", "arguments": "{}"}},
+ ],
+ },
+ {"role": "tool", "tool_call_id": "a1", "content": "r1"},
+ {"role": "tool", "tool_call_id": "a2", "content": "r2"},
+ {"role": "assistant", "content": "Done."},
+ ]
+ )
+ msgs = m.get_messages("Next")
+ self._assert_valid_tool_pairing(msgs)
+
+ def test_clearing_window_boundary_excludes_partial_group(self):
+ """When a group won't fit in the remaining budget, it's excluded entirely."""
+ m = self._make_memory(max_messages=2, clear_tool_results_after=10)
+ m.add_messages(
+ [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {"id": "x1", "type": "function", "function": {"name": "t1", "arguments": "{}"}},
+ {"id": "x2", "type": "function", "function": {"name": "t2", "arguments": "{}"}},
+ ],
+ },
+ {"role": "tool", "tool_call_id": "x1", "content": "r1"},
+ {"role": "tool", "tool_call_id": "x2", "content": "r2"},
+ {"role": "assistant", "content": "summary"},
+ ]
+ )
+ msgs = m.get_messages("Next")
+ self._assert_valid_tool_pairing(msgs)
+ inner = [msg for msg in msgs if msg["role"] not in ("system", "user")]
+ # The 3-message group won't fit in budget=2 after "summary", so only "summary"
+ assert len(inner) <= 2
+
+ def test_pin_pattern_ignores_tool_results(self):
+ """A tool result whose content matches a pin pattern is NOT pinned."""
+ m = FIFOMemory(
+ session_file="",
+ system_prompt=SYSTEM_PROMPT,
+ max_messages=2,
+ pin_patterns=["CRITICAL"],
+ clear_tool_results=True,
+ clear_tool_results_after=10,
+ )
+ m.add_messages(
+ [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {"id": "tc1", "type": "function", "function": {"name": "get_logs", "arguments": "{}"}},
+ ],
+ },
+ {"role": "tool", "tool_call_id": "tc1", "content": "CRITICAL error in prod"},
+ {"role": "assistant", "content": "There's a critical error."},
+ ]
+ )
+ for i in range(5):
+ m.add_messages([{"role": "assistant", "content": f"filler {i}"}])
+ msgs = m.get_messages("Next")
+ self._assert_valid_tool_pairing(msgs)
+
+ def test_pin_pattern_ignores_assistant_tool_calls(self):
+ """An assistant+tool_calls with matching text content is NOT pinned."""
+ m = FIFOMemory(
+ session_file="",
+ system_prompt=SYSTEM_PROMPT,
+ max_messages=2,
+ pin_patterns=["IMPORTANT"],
+ clear_tool_results=True,
+ clear_tool_results_after=10,
+ )
+ m.add_messages(
+ [
+ {
+ "role": "assistant",
+ "content": "IMPORTANT: checking now",
+ "tool_calls": [
+ {"id": "tc1", "type": "function", "function": {"name": "check", "arguments": "{}"}},
+ ],
+ },
+ {"role": "tool", "tool_call_id": "tc1", "content": "all clear"},
+ {"role": "assistant", "content": "Done checking."},
+ ]
+ )
+ for i in range(5):
+ m.add_messages([{"role": "assistant", "content": f"filler {i}"}])
+ msgs = m.get_messages("Next")
+ self._assert_valid_tool_pairing(msgs)
+ # The mixed assistant should NOT be pinned separately from its tool result
+ contents = [msg.get("content", "") for msg in msgs]
+ assert "IMPORTANT: checking now" not in contents or "all clear" in contents
+
+ def test_pin_with_clearing_no_orphaned_tools(self):
+ """Combined pinning + clearing never produces orphaned tool messages."""
+ m = FIFOMemory(
+ session_file="",
+ system_prompt=SYSTEM_PROMPT,
+ max_messages=3,
+ pin_patterns=["REMEMBER"],
+ clear_tool_results=True,
+ clear_tool_results_after=10,
+ )
+ m.add_messages([{"role": "user", "content": "REMEMBER: this is key"}])
+ m.add_messages(TOOL_HEAVY_CONVERSATION)
+ for i in range(10):
+ m.add_messages([{"role": "assistant", "content": f"filler {i}"}])
+ msgs = m.get_messages("Next")
+ self._assert_valid_tool_pairing(msgs)
+ # The pinned message should survive
+ contents = [msg.get("content", "") for msg in msgs]
+ assert "REMEMBER: this is key" in contents
+
+ @staticmethod
+ def _assert_valid_tool_pairing(msgs: list[dict]) -> None:
+ """Assert every tool result has a preceding assistant with a matching tool_call_id."""
+ for i, msg in enumerate(msgs):
+ if msg.get("role") != "tool":
+ continue
+ tcid = msg.get("tool_call_id", "")
+ found = False
+ for j in range(i - 1, -1, -1):
+ prev = msgs[j]
+ if prev.get("role") == "assistant" and "tool_calls" in prev:
+ call_ids = {tc.get("id", "") for tc in prev["tool_calls"]}
+ if tcid in call_ids:
+ found = True
+ break
+ assert found, (
+ f"Tool result at index {i} (tool_call_id={tcid!r}) "
+ f"has no preceding assistant with matching tool_call_id"
+ )
+
+
+# ── Mock LLM client ─────────────────────────────────────────────────────
+
+
+class MockCompletions:
+ def __init__(self):
+ self.calls: list[dict] = []
+ self.response_text = "Mocked summary of the conversation."
+
+ def create(self, **kwargs):
+ self.calls.append(kwargs)
+ return SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content=self.response_text))])
+
+
+class MockOpenAIClient:
+ def __init__(self):
+ self._completions = MockCompletions()
+ self.chat = SimpleNamespace(completions=self._completions)
+
+ @property
+ def calls(self):
+ return self._completions.calls
+
+ @property
+ def response_text(self):
+ return self._completions.response_text
+
+ @response_text.setter
+ def response_text(self, value):
+ self._completions.response_text = value
+
+
+class FailingCompletions:
+ def create(self, **kwargs):
+ raise ConnectionError("LLM unavailable")
+
+
+class FailingOpenAIClient:
+ def __init__(self):
+ self.chat = SimpleNamespace(completions=FailingCompletions())
+
+
+# ── SummaryMemory tests (Phase 1e) ──────────────────────────────────────
+
+
+class TestSummaryMemory:
+ def _make_memory(self, session_file="", **kwargs):
+ defaults = {"llm_client": MockOpenAIClient(), "llm_model": "test-model", "max_summary_tokens": 200}
+ defaults.update(kwargs)
+ return SummaryMemory(session_file=session_file, system_prompt=SYSTEM_PROMPT, **defaults)
+
+ def test_summary_calls_llm_for_compression(self):
+ """add_messages() calls the LLM to generate a summary."""
+ client = MockOpenAIClient()
+ m = self._make_memory(llm_client=client)
+ m.add_messages([{"role": "user", "content": "Hello"}, {"role": "assistant", "content": "Hi there!"}])
+ assert len(client.calls) == 1
+ call_kwargs = client.calls[0]
+ assert call_kwargs["model"] == "test-model"
+ assert call_kwargs["max_tokens"] == 200
+ assert any("Hello" in msg["content"] for msg in call_kwargs["messages"] if msg.get("content"))
+
+ def test_summary_replaces_history_with_summary(self):
+ """get_messages() returns [system, summary, user] — not raw history."""
+ m = self._make_memory()
+ m.add_messages(
+ [
+ {"role": "user", "content": "Hello"},
+ {"role": "assistant", "content": "Hi there!"},
+ ]
+ )
+ msgs = m.get_messages("What's next?")
+ assert len(msgs) == 3
+ assert msgs[0]["role"] == "system"
+ assert msgs[1]["role"] == "assistant"
+ assert "[Summary of our conversation so far]" in msgs[1]["content"]
+ assert msgs[2]["role"] == "user"
+ assert msgs[2]["content"] == "What's next?"
+
+ def test_summary_preserves_raw_on_disk(self, session_file):
+ """Raw JSONL still contains all original messages after summarization."""
+ m = self._make_memory(session_file=session_file)
+ m.add_messages(SAMPLE_MESSAGES)
+ m.save()
+ with open(session_file) as f:
+ stored = [json.loads(line) for line in f if line.strip()]
+ assert len(stored) == len(SAMPLE_MESSAGES)
+
+ def test_summary_handles_llm_failure(self):
+ """If LLM call fails, add_messages() doesn't crash and get_messages() falls back."""
+ m = self._make_memory(llm_client=FailingOpenAIClient())
+ m.add_messages(
+ [
+ {"role": "user", "content": "Hello"},
+ {"role": "assistant", "content": "Hi there!"},
+ ]
+ )
+ # Should not crash
+ msgs = m.get_messages("Next")
+ # Falls back to recent history messages
+ assert msgs[0]["role"] == "system"
+ assert msgs[-1]["role"] == "user"
+ assert msgs[-1]["content"] == "Next"
+ # Should contain fallback messages from history
+ assert len(msgs) > 2
+
+ def test_summary_max_tokens_respected(self):
+ """max_summary_tokens is passed as max_tokens to the LLM call."""
+ client = MockOpenAIClient()
+ m = self._make_memory(llm_client=client, max_summary_tokens=300)
+ m.add_messages([{"role": "user", "content": "Hello"}])
+ assert client.calls[0]["max_tokens"] == 300
+
+ def test_summary_no_meta_in_output(self):
+ m = self._make_memory()
+ m.add_messages([{"role": "user", "content": "Hello"}])
+ msgs = m.get_messages("Next")
+ assert all("_meta" not in msg for msg in msgs)
+
+ def test_summary_file_persistence(self, session_file):
+ """Summary persists and loads correctly across instances."""
+ m1 = self._make_memory(session_file=session_file)
+ m1.add_messages([{"role": "user", "content": "Hello"}])
+ m1.save()
+
+ m2 = self._make_memory(session_file=session_file)
+ m2.load()
+ assert m2._summary == "Mocked summary of the conversation."
+ msgs = m2.get_messages("Next")
+ assert any("[Summary of our conversation so far]" in msg.get("content", "") for msg in msgs)
+
+ def test_summary_factory_registration(self):
+ """create_memory() recognizes 'summary' strategy."""
+ client = MockOpenAIClient()
+ m = create_memory(
+ {"strategy": "summary", "max_summary_tokens": 100},
+ SYSTEM_PROMPT,
+ llm_client=client,
+ llm_model="test-model",
+ )
+ assert isinstance(m, SummaryMemory)
+ assert m._max_summary_tokens == 100
+
+ def test_summary_no_llm_client_graceful(self):
+ """Without an LLM client, add_messages() stores but doesn't summarize."""
+ m = SummaryMemory(session_file="", system_prompt=SYSTEM_PROMPT)
+ m.add_messages([{"role": "user", "content": "Hello"}])
+ assert m._summary == ""
+ msgs = m.get_messages("Next")
+ # Falls back to history
+ assert len(msgs) == 3 # system + history msg + user
+
+ def test_summary_incremental_update(self):
+ """Second add_messages() passes existing summary to LLM."""
+ client = MockOpenAIClient()
+ m = self._make_memory(llm_client=client)
+ m.add_messages([{"role": "user", "content": "Turn 1"}])
+ assert len(client.calls) == 1
+
+ client.response_text = "Updated summary."
+ m.add_messages([{"role": "user", "content": "Turn 2"}])
+ assert len(client.calls) == 2
+ second_call = client.calls[1]
+ user_msg = [msg for msg in second_call["messages"] if msg["role"] == "user"][0]
+ assert "Current summary:" in user_msg["content"]
+ assert "Mocked summary" in user_msg["content"]
+
+
+# ── SummaryBufferMemory tests (Phase 1f) ────────────────────────────────
+
+
+class TestSummaryBufferMemory:
+ def _make_memory(self, session_file="", **kwargs):
+ defaults = {
+ "llm_client": MockOpenAIClient(),
+ "llm_model": "test-model",
+ "max_summary_tokens": 200,
+ "max_messages": 5,
+ }
+ defaults.update(kwargs)
+ return SummaryBufferMemory(session_file=session_file, system_prompt=SYSTEM_PROMPT, **defaults)
+
+ def test_hybrid_keeps_recent_verbatim(self):
+ """Under max_messages, returns raw messages with no summary."""
+ m = self._make_memory(max_messages=10)
+ m.add_messages(
+ [
+ {"role": "user", "content": "Hello"},
+ {"role": "assistant", "content": "Hi!"},
+ ]
+ )
+ msgs = m.get_messages("Next")
+ contents = [msg.get("content", "") for msg in msgs]
+ assert "Hello" in contents
+ assert "Hi!" in contents
+ assert not any("[Summary" in c for c in contents)
+
+ def test_hybrid_summarizes_evicted(self):
+ """Over max_messages, LLM is called and summary appears in output."""
+ client = MockOpenAIClient()
+ m = self._make_memory(llm_client=client, max_messages=3)
+ for i in range(10):
+ m.add_messages([{"role": "assistant", "content": f"msg {i}"}])
+ msgs = m.get_messages("Next")
+ assert len(client.calls) > 0
+ contents = [msg.get("content", "") for msg in msgs]
+ assert any("[Summary of earlier conversation]" in c for c in contents)
+
+ def test_hybrid_summary_prepended(self):
+ """Output order: [system, summary, recent_window, user]."""
+ m = self._make_memory(max_messages=3)
+ for i in range(10):
+ m.add_messages([{"role": "assistant", "content": f"msg {i}"}])
+ msgs = m.get_messages("Next")
+ assert msgs[0]["role"] == "system"
+ assert msgs[-1]["role"] == "user"
+ # Find summary position
+ summary_idx = None
+ for i, msg in enumerate(msgs):
+ if "[Summary of earlier conversation]" in msg.get("content", ""):
+ summary_idx = i
+ break
+ assert summary_idx is not None
+ assert summary_idx > 0 # after system
+ assert summary_idx < len(msgs) - 1 # before user
+
+ def test_hybrid_boundary(self):
+ """Exactly at max_messages, no summarization triggered."""
+ client = MockOpenAIClient()
+ m = self._make_memory(llm_client=client, max_messages=5)
+ for i in range(5):
+ m.add_messages([{"role": "assistant", "content": f"msg {i}"}])
+ msgs = m.get_messages("Next")
+ assert len(client.calls) == 0
+ contents = [msg.get("content", "") for msg in msgs]
+ assert not any("[Summary" in c for c in contents)
+
+ def test_hybrid_incremental_summary(self):
+ """LLM gets existing summary + new evictions, not full history."""
+ client = MockOpenAIClient()
+ m = self._make_memory(llm_client=client, max_messages=3)
+ # First batch: push past window
+ for i in range(5):
+ m.add_messages([{"role": "assistant", "content": f"batch1 msg {i}"}])
+ first_call_count = len(client.calls)
+ assert first_call_count > 0
+
+ # Second batch: more evictions
+ client.response_text = "Updated summary."
+ for i in range(3):
+ m.add_messages([{"role": "assistant", "content": f"batch2 msg {i}"}])
+ assert len(client.calls) > first_call_count
+ last_call = client.calls[-1]
+ user_msg = [msg for msg in last_call["messages"] if msg["role"] == "user"][0]
+ assert "Current summary:" in user_msg["content"]
+
+ def test_hybrid_no_meta_in_output(self):
+ m = self._make_memory()
+ for i in range(10):
+ m.add_messages([{"role": "assistant", "content": f"msg {i}"}])
+ msgs = m.get_messages("Next")
+ assert all("_meta" not in msg for msg in msgs)
+
+ def test_hybrid_with_pinning(self):
+ """Pinned messages appear before summary in output."""
+ m = self._make_memory(max_messages=3, pin_patterns=["PIN"])
+ m.add_messages([{"role": "user", "content": "PIN: remember this"}])
+ for i in range(10):
+ m.add_messages([{"role": "assistant", "content": f"filler {i}"}])
+ msgs = m.get_messages("Next")
+ contents = [msg.get("content", "") for msg in msgs]
+ assert "PIN: remember this" in contents
+ pin_idx = contents.index("PIN: remember this")
+ summary_idx = next(
+ (i for i, c in enumerate(contents) if "[Summary of earlier conversation]" in c),
+ None,
+ )
+ if summary_idx is not None:
+ assert pin_idx < summary_idx, "Pinned should appear before summary"
+
+ def test_hybrid_valid_tool_pairing(self):
+ """Tool groups remain intact (inherited from FIFOMemory)."""
+ m = self._make_memory(max_messages=5, clear_tool_results=True, clear_tool_results_after=10)
+ m.add_messages(TOOL_HEAVY_CONVERSATION)
+ msgs = m.get_messages("Next")
+ TestToolResultClearing._assert_valid_tool_pairing(msgs)
+
+ def test_hybrid_factory_registration(self):
+ """create_memory() recognizes 'summary-buffer' strategy."""
+ client = MockOpenAIClient()
+ m = create_memory(
+ {"strategy": "summary-buffer", "max_messages": 10, "max_summary_tokens": 100},
+ SYSTEM_PROMPT,
+ llm_client=client,
+ llm_model="test-model",
+ )
+ assert isinstance(m, SummaryBufferMemory)
+ assert m._max_messages == 10
+ assert m._max_summary_tokens == 100
+
+ def test_hybrid_file_persistence(self, session_file):
+ """Summary and summarized_count persist across instances."""
+ m1 = self._make_memory(session_file=session_file, max_messages=3)
+ for i in range(6):
+ m1.add_messages([{"role": "assistant", "content": f"msg {i}"}])
+ m1.save()
+ assert m1._summarized_count > 0
+
+ m2 = self._make_memory(session_file=session_file, max_messages=3)
+ m2.load()
+ assert m2._summary == m1._summary
+ assert m2._summarized_count == m1._summarized_count
+
+ def test_hybrid_eviction_matches_selection_with_tool_groups(self):
+ """Eviction accounting uses the same unit-based logic as get_messages()."""
+ client = MockOpenAIClient()
+ m = self._make_memory(
+ llm_client=client,
+ max_messages=3,
+ clear_tool_results=True,
+ clear_tool_results_after=10,
+ )
+ # A 3-message tool-call group counts as one unit
+ m.add_messages(
+ [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {"id": "tc1", "type": "function", "function": {"name": "check", "arguments": "{}"}},
+ {"id": "tc2", "type": "function", "function": {"name": "check2", "arguments": "{}"}},
+ ],
+ },
+ {"role": "tool", "tool_call_id": "tc1", "content": "result 1"},
+ {"role": "tool", "tool_call_id": "tc2", "content": "result 2"},
+ {"role": "assistant", "content": "All clear."},
+ ]
+ )
+ msgs = m.get_messages("Next")
+ # Window should contain the full tool group (3 msgs) + "All clear." (1 msg)
+ # That's 4 messages which is > max_messages=3, but the group is atomic
+ # so either the group is in or out. With _take_trailing_units, the last
+ # unit ("All clear.") is taken first, then the 3-msg group won't fit.
+ # So window = just ["All clear."] and the tool group is evicted.
+ # Verify the eviction was actually summarized
+ if len(client.calls) > 0:
+ last_call = client.calls[-1]
+ user_msg = [msg for msg in last_call["messages"] if msg["role"] == "user"][0]
+ # Evicted content should appear in the summarization prompt
+ assert "result 1" in user_msg["content"] or "check" in user_msg["content"]
+ # Verify get_messages produces valid output regardless
+ TestToolResultClearing._assert_valid_tool_pairing(msgs)
+
+ def test_hybrid_pinned_excluded_from_eviction_summary(self):
+ """Pinned messages are NOT sent to the LLM for summarization."""
+ client = MockOpenAIClient()
+ m = self._make_memory(llm_client=client, max_messages=3, pin_patterns=["PIN"])
+ m.add_messages([{"role": "user", "content": "PIN: critical directive"}])
+ for i in range(10):
+ m.add_messages([{"role": "assistant", "content": f"filler {i}"}])
+ # Pinned message should not appear in any summarization call
+ for call in client.calls:
+ user_msg = [msg for msg in call["messages"] if msg["role"] == "user"][0]
+ assert "PIN: critical directive" not in user_msg["content"], (
+ "Pinned message should not be sent to LLM for summarization"
+ )
+ # But it should still appear verbatim in get_messages()
+ msgs = m.get_messages("Next")
+ contents = [msg.get("content", "") for msg in msgs]
+ assert "PIN: critical directive" in contents
+
+ def test_hybrid_tool_results_in_eviction_summary(self):
+ """Evicted tool results are included in the summarization prompt."""
+ client = MockOpenAIClient()
+ m = self._make_memory(
+ llm_client=client,
+ max_messages=2,
+ clear_tool_results=True,
+ clear_tool_results_after=10,
+ )
+ m.add_messages(
+ [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {"id": "tc1", "type": "function", "function": {"name": "get_logs", "arguments": "{}"}},
+ ],
+ },
+ {"role": "tool", "tool_call_id": "tc1", "content": "ERROR: disk full on node-3"},
+ {"role": "assistant", "content": "Found an error."},
+ ]
+ )
+ # Push past window so the tool group gets evicted
+ for i in range(5):
+ m.add_messages([{"role": "assistant", "content": f"filler {i}"}])
+ # Verify tool result content made it into the summarization prompt
+ found_tool_content = False
+ for call in client.calls:
+ user_msg = [msg for msg in call["messages"] if msg["role"] == "user"][0]
+ if "disk full" in user_msg["content"]:
+ found_tool_content = True
+ break
+ assert found_tool_content, "Evicted tool results should be included in summary"
+
+
+# ── format_messages_for_summary tests ────────────────────────────────────
+
+
+class TestFormatMessagesForSummary:
+ def test_includes_tool_results(self):
+ from cosim_agent.memory.summary import format_messages_for_summary
+
+ msgs = [
+ {"role": "tool", "tool_call_id": "tc1", "content": "query returned 5 rows"},
+ ]
+ text = format_messages_for_summary(msgs)
+ assert "[tool result]" in text
+ assert "query returned 5 rows" in text
+
+ def test_includes_tool_call_names(self):
+ from cosim_agent.memory.summary import format_messages_for_summary
+
+ msgs = [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {"id": "tc1", "function": {"name": "get_messages", "arguments": "{}"}},
+ ],
+ },
+ ]
+ text = format_messages_for_summary(msgs)
+ assert "[called: get_messages]" in text
+
+ def test_truncates_long_tool_results(self):
+ from cosim_agent.memory.summary import format_messages_for_summary
+
+ msgs = [
+ {"role": "tool", "tool_call_id": "tc1", "content": "x" * 1000},
+ ]
+ text = format_messages_for_summary(msgs)
+ assert len(text) < 600
+
+ def test_mixed_assistant_with_tool_calls(self):
+ from cosim_agent.memory.summary import format_messages_for_summary
+
+ msgs = [
+ {
+ "role": "assistant",
+ "content": "Let me check.",
+ "tool_calls": [{"id": "tc1", "function": {"name": "check", "arguments": "{}"}}],
+ },
+ ]
+ text = format_messages_for_summary(msgs)
+ assert "Let me check." in text
+ assert "[called: check]" in text
+
+
+# ── DecayMemory tests (Phase 2a) ──────────────────────────────────────
+
+
+class TestDecayMemory:
+ def _make_memory(self, **kwargs):
+ defaults = {"max_messages": 5, "decay_halflife_hours": 4.0}
+ defaults.update(kwargs)
+ return DecayMemory(session_file="", system_prompt=SYSTEM_PROMPT, **defaults)
+
+ def test_decay_scores_recent_higher(self):
+ """Recent messages score higher than old ones."""
+ import time
+
+ m = self._make_memory(max_messages=1)
+ m.add_messages([{"role": "user", "content": "old message"}])
+ # Backdate the old message
+ m._history[0]["_meta"]["ts"] = time.time() - 3600 * 24
+ m.add_messages([{"role": "assistant", "content": "new message"}])
+ msgs = m.get_messages("Next")
+ contents = [msg.get("content", "") for msg in msgs]
+ assert "new message" in contents
+ assert "old message" not in contents
+
+ def test_decay_selects_top_scored(self):
+ """Selection picks top N by score, not last N by position."""
+ import time
+
+ m = self._make_memory(max_messages=2)
+ now = time.time()
+ # Add 4 messages: old, very-old, old, recent
+ m.add_messages([{"role": "user", "content": "msg A"}])
+ m._history[-1]["_meta"]["ts"] = now - 3600 * 2 # 2 hours old
+ m.add_messages([{"role": "assistant", "content": "msg B"}])
+ m._history[-1]["_meta"]["ts"] = now - 3600 * 48 # 48 hours old
+ m.add_messages([{"role": "user", "content": "msg C"}])
+ m._history[-1]["_meta"]["ts"] = now - 3600 * 2 # 2 hours old
+ m.add_messages([{"role": "assistant", "content": "msg D"}])
+ m._history[-1]["_meta"]["ts"] = now # current
+ msgs = m.get_messages("Next")
+ contents = [msg.get("content", "") for msg in msgs]
+ # msg B (48h old) should be excluded as lowest score
+ assert "msg B" not in contents
+ assert "msg D" in contents
+
+ def test_decay_access_reinforces(self):
+ """Message with higher importance scores higher."""
+ import time
+
+ m = self._make_memory(max_messages=1)
+ now = time.time()
+ m.add_messages([{"role": "user", "content": "normal msg"}])
+ m._history[-1]["_meta"]["ts"] = now - 3600 * 8
+ m.add_messages([{"role": "assistant", "content": "important msg"}])
+ m._history[-1]["_meta"]["ts"] = now - 3600 * 8
+ m._history[-1]["_meta"]["importance"] = 5.0
+ msgs = m.get_messages("Next")
+ contents = [msg.get("content", "") for msg in msgs]
+ assert "important msg" in contents
+ assert "normal msg" not in contents
+
+ def test_decay_halflife_configurable(self):
+ """Different halflife values produce different selection sets."""
+ import time
+
+ now = time.time()
+ msgs_to_add = [
+ {"role": "user", "content": "ancient msg"},
+ {"role": "assistant", "content": "recent msg"},
+ ]
+
+ # Fast decay (0.001h halflife) — ancient message should be gone
+ m_fast = self._make_memory(max_messages=1, decay_halflife_hours=0.001)
+ m_fast.add_messages([msgs_to_add[0].copy()])
+ m_fast._history[-1]["_meta"]["ts"] = now - 3600 * 2
+ m_fast.add_messages([msgs_to_add[1].copy()])
+ m_fast._history[-1]["_meta"]["ts"] = now
+ fast_msgs = m_fast.get_messages("Next")
+ fast_contents = [msg.get("content", "") for msg in fast_msgs]
+
+ # Slow decay (1000h halflife) — both messages should score similarly
+ m_slow = self._make_memory(max_messages=1, decay_halflife_hours=1000.0)
+ m_slow.add_messages([msgs_to_add[0].copy()])
+ m_slow._history[-1]["_meta"]["ts"] = now - 3600 * 2
+ m_slow.add_messages([msgs_to_add[1].copy()])
+ m_slow._history[-1]["_meta"]["ts"] = now
+ slow_msgs = m_slow.get_messages("Next")
+ slow_contents = [msg.get("content", "") for msg in slow_msgs]
+
+ # Fast decay should exclude old, slow decay could include either
+ assert "ancient msg" not in fast_contents
+ assert "recent msg" in fast_contents
+ # With slow decay and max_messages=1, the most recent wins by tiebreak
+ assert "recent msg" in slow_contents
+
+ def test_decay_pinned_bypass(self):
+ """Pinned messages always included regardless of score."""
+ import time
+
+ m = self._make_memory(max_messages=1, decay_halflife_hours=0.001, pin_patterns=["PIN"])
+ m.add_messages([{"role": "user", "content": "PIN: critical"}])
+ m._history[-1]["_meta"]["ts"] = time.time() - 3600 * 100 # very old
+ m.add_messages([{"role": "assistant", "content": "recent"}])
+ msgs = m.get_messages("Next")
+ contents = [msg.get("content", "") for msg in msgs]
+ assert "PIN: critical" in contents
+ assert "recent" in contents
+
+ def test_decay_interleaved_old_new(self):
+ """Can select a mix of old high-importance and new messages."""
+ import time
+
+ m = self._make_memory(max_messages=3)
+ now = time.time()
+ m.add_messages([{"role": "user", "content": "important old"}])
+ m._history[-1]["_meta"]["ts"] = now - 3600 * 12
+ m._history[-1]["_meta"]["importance"] = 10.0
+ m.add_messages([{"role": "assistant", "content": "boring old"}])
+ m._history[-1]["_meta"]["ts"] = now - 3600 * 12
+ m.add_messages([{"role": "user", "content": "medium old"}])
+ m._history[-1]["_meta"]["ts"] = now - 3600 * 6
+ m.add_messages([{"role": "assistant", "content": "recent 1"}])
+ m._history[-1]["_meta"]["ts"] = now
+ m.add_messages([{"role": "user", "content": "recent 2"}])
+ m._history[-1]["_meta"]["ts"] = now
+ msgs = m.get_messages("Next")
+ contents = [msg.get("content", "") for msg in msgs]
+ # "important old" should survive thanks to high importance
+ assert "important old" in contents
+ # recent messages should be present
+ assert "recent 2" in contents
+
+ def test_decay_no_meta_in_output(self):
+ m = self._make_memory()
+ m.add_messages([{"role": "user", "content": "Hello"}])
+ msgs = m.get_messages("Next")
+ assert all("_meta" not in msg for msg in msgs)
+
+
+# ── EntityMemory tests (Phase 2b) ──────────────────────────────────────
+
+
+class TestEntityMemory:
+ def _make_memory(self, session_file="", **kwargs):
+ client = MockOpenAIClient()
+ client.response_text = '{"Alice": "Engineer working on deployment", "TK-abc": "Follow-up ticket"}'
+ defaults = {"llm_client": client, "llm_model": "test-model", "max_messages": 50}
+ defaults.update(kwargs)
+ return EntityMemory(session_file=session_file, system_prompt=SYSTEM_PROMPT, **defaults)
+
+ def test_entity_extraction(self):
+ """Mock LLM returns JSON, entities are stored."""
+ m = self._make_memory()
+ m.add_messages([{"role": "user", "content": "Alice deployed the fix for TK-abc"}])
+ assert "Alice" in m._entities
+ assert "TK-abc" in m._entities
+ assert "Engineer" in m._entities["Alice"]
+
+ def test_entity_summaries_injected(self):
+ """Entity summary message appears after system prompt in get_messages()."""
+ m = self._make_memory()
+ m.add_messages([{"role": "user", "content": "Alice deployed the fix"}])
+ msgs = m.get_messages("Next")
+ assert msgs[0]["role"] == "system"
+ assert msgs[0]["content"] == SYSTEM_PROMPT
+ assert msgs[1]["role"] == "system"
+ assert "[Known entities]" in msgs[1]["content"]
+ assert "Alice" in msgs[1]["content"]
+
+ def test_entity_summaries_updated(self):
+ """Second turn updates existing entity summaries."""
+ client = MockOpenAIClient()
+ client.response_text = '{"Alice": "Senior engineer"}'
+ m = self._make_memory(llm_client=client)
+ m.add_messages([{"role": "user", "content": "Alice is here"}])
+ assert m._entities["Alice"] == "Senior engineer"
+
+ client.response_text = '{"Alice": "Senior engineer, now team lead"}'
+ m.add_messages([{"role": "user", "content": "Alice got promoted"}])
+ assert m._entities["Alice"] == "Senior engineer, now team lead"
+
+ def test_entity_persistence(self, session_file):
+ """Save + load round-trip preserves entities."""
+ m1 = self._make_memory(session_file=session_file)
+ m1.add_messages([{"role": "user", "content": "Alice deployed the fix"}])
+ m1.save()
+
+ m2 = self._make_memory(session_file=session_file)
+ m2.load()
+ assert m2._entities == m1._entities
+
+ def test_entity_extraction_failure(self):
+ """LLM failure doesn't crash, no entities added."""
+ m = self._make_memory(llm_client=FailingOpenAIClient())
+ m.add_messages([{"role": "user", "content": "Hello"}])
+ assert m._entities == {}
+ msgs = m.get_messages("Next")
+ # No entity message injected
+ assert not any("[Known entities]" in msg.get("content", "") for msg in msgs)
+
+
+# ── EpisodicMemory tests (Phase 2c) ──────────────────────────────────────
+
+
+class TestEpisodicMemory:
+ def _make_memory(self, **kwargs):
+ defaults = {
+ "llm_client": MockOpenAIClient(),
+ "llm_model": "test-model",
+ "max_messages": 50,
+ "reflection_interval": 3,
+ "max_reflections": 5,
+ }
+ defaults.update(kwargs)
+ return EpisodicMemory(session_file="", system_prompt=SYSTEM_PROMPT, **defaults)
+
+ def test_episodic_reflection_generated(self):
+ """After reflection_interval turns, LLM is called to generate reflection."""
+ client = MockOpenAIClient()
+ client.response_text = "Key theme: deployment monitoring."
+ m = self._make_memory(llm_client=client, reflection_interval=3)
+ for i in range(3):
+ m.add_messages([{"role": "assistant", "content": f"msg {i}"}])
+ assert len(m._reflections) == 1
+ assert m._reflections[0]["content"] == "Key theme: deployment monitoring."
+ assert m._reflections[0]["turn"] == 3
+
+ def test_episodic_reflections_injected(self):
+ """Reflections appear in get_messages() after system prompt."""
+ client = MockOpenAIClient()
+ client.response_text = "Reflection content here."
+ m = self._make_memory(llm_client=client, reflection_interval=2)
+ m.add_messages([{"role": "assistant", "content": "msg 1"}])
+ m.add_messages([{"role": "assistant", "content": "msg 2"}])
+ msgs = m.get_messages("Next")
+ assert msgs[0]["role"] == "system"
+ assert msgs[0]["content"] == SYSTEM_PROMPT
+ assert msgs[1]["role"] == "system"
+ assert "[Reflections on conversation]" in msgs[1]["content"]
+ assert "Reflection content here." in msgs[1]["content"]
+
+ def test_episodic_reflection_not_generated_before_interval(self):
+ """No reflection at turn 1 if interval=10."""
+ client = MockOpenAIClient()
+ m = self._make_memory(llm_client=client, reflection_interval=10)
+ m.add_messages([{"role": "assistant", "content": "msg"}])
+ assert len(m._reflections) == 0
+
+ def test_episodic_max_reflections_trimmed(self):
+ """Excess reflections are trimmed to max_reflections."""
+ client = MockOpenAIClient()
+ m = self._make_memory(llm_client=client, reflection_interval=1, max_reflections=2)
+ for i in range(5):
+ client.response_text = f"Reflection {i}"
+ m.add_messages([{"role": "assistant", "content": f"msg {i}"}])
+ assert len(m._reflections) == 2
+ assert m._reflections[-1]["content"] == "Reflection 4"
+
+ def test_episodic_reflection_failure(self):
+ """LLM failure doesn't crash, no reflection added."""
+ m = self._make_memory(llm_client=FailingOpenAIClient(), reflection_interval=1)
+ m.add_messages([{"role": "assistant", "content": "msg"}])
+ assert len(m._reflections) == 0
+
+
+# ── ReflexionMemory tests (Phase 2d) ──────────────────────────────────────
+
+
+class TestReflexionMemory:
+ def _make_memory(self, **kwargs):
+ defaults = {
+ "llm_client": MockOpenAIClient(),
+ "llm_model": "test-model",
+ "max_messages": 50,
+ "max_reflections": 3,
+ }
+ defaults.update(kwargs)
+ return ReflexionMemory(session_file="", system_prompt=SYSTEM_PROMPT, **defaults)
+
+ def test_reflexion_generates_critique(self):
+ """Mock LLM is called after add_messages()."""
+ client = MockOpenAIClient()
+ client.response_text = "The response was helpful but could be more specific."
+ m = self._make_memory(llm_client=client)
+ m.add_messages([{"role": "assistant", "content": "I checked the logs."}])
+ assert len(m._critiques) == 1
+ assert m._critiques[0]["content"] == "The response was helpful but could be more specific."
+ assert len(client.calls) == 1
+
+ def test_reflexion_injects_past_critiques(self):
+ """Last N critiques appear in get_messages() after system prompt."""
+ client = MockOpenAIClient()
+ client.response_text = "Critique: good response."
+ m = self._make_memory(llm_client=client)
+ m.add_messages([{"role": "assistant", "content": "msg 1"}])
+ msgs = m.get_messages("Next")
+ assert msgs[0]["role"] == "system"
+ assert msgs[0]["content"] == SYSTEM_PROMPT
+ assert msgs[1]["role"] == "system"
+ assert "[Self-critique from previous turns]" in msgs[1]["content"]
+ assert "Critique: good response." in msgs[1]["content"]
+
+ def test_reflexion_window_truncates(self):
+ """Only last max_reflections critiques kept."""
+ client = MockOpenAIClient()
+ m = self._make_memory(llm_client=client, max_reflections=2)
+ for i in range(5):
+ client.response_text = f"Critique {i}"
+ m.add_messages([{"role": "assistant", "content": f"msg {i}"}])
+ assert len(m._critiques) == 2
+ assert m._critiques[-1]["content"] == "Critique 4"
+ assert m._critiques[0]["content"] == "Critique 3"
+
+ def test_reflexion_failure_graceful(self):
+ """LLM failure doesn't crash, no critique added."""
+ m = self._make_memory(llm_client=FailingOpenAIClient())
+ m.add_messages([{"role": "assistant", "content": "msg"}])
+ assert len(m._critiques) == 0
+ msgs = m.get_messages("Next")
+ assert not any("[Self-critique" in msg.get("content", "") for msg in msgs)
diff --git a/uv.lock b/uv.lock
index b5c3e7d..d852131 100644
--- a/uv.lock
+++ b/uv.lock
@@ -242,6 +242,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/1b/82/ca4893968aeb2709aacfb57a30dec6fa2ab25b10fa9f064b8882ce33f599/cryptography-46.0.6-cp38-abi3-win_amd64.whl", hash = "sha256:79e865c642cfc5c0b3eb12af83c35c5aeff4fa5c672dc28c43721c2c9fdd2f0f", size = 3471160, upload-time = "2026-03-25T23:34:37.191Z" },
]
+[[package]]
+name = "distro"
+version = "1.9.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/fc/f8/98eea607f65de6527f8a2e8885fc8015d3e6f5775df186e443e0964a11c3/distro-1.9.0.tar.gz", hash = "sha256:2fa77c6fd8940f116ee1d6b94a2f90b13b5ea8d019b98bc8bafdcabcdd9bdbed", size = 60722, upload-time = "2023-12-24T09:54:32.31Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/12/b3/231ffd4ab1fc9d679809f356cebee130ac7daa00d6d6f3206dd4fd137e9e/distro-1.9.0-py3-none-any.whl", hash = "sha256:7bffd925d65168f85027d8da9af6bddab658135b840670a223589bc0c8ef02b2", size = 20277, upload-time = "2023-12-24T09:54:30.421Z" },
+]
+
[[package]]
name = "flask"
version = "3.1.3"
@@ -356,6 +365,60 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" },
]
+[[package]]
+name = "jiter"
+version = "0.14.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/6e/c1/0cddc6eb17d4c53a99840953f95dd3accdc5cfc7a337b0e9b26476276be9/jiter-0.14.0.tar.gz", hash = "sha256:e8a39e66dac7153cf3f964a12aad515afa8d74938ec5cc0018adcdae5367c79e", size = 165725, upload-time = "2026-04-10T14:28:42.01Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/97/2a/09f70020898507a89279659a1afe3364d57fc1b2c89949081975d135f6f5/jiter-0.14.0-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:af72f204cf4d44258e5b4c1745130ac45ddab0e71a06333b01de660ab4187a94", size = 315502, upload-time = "2026-04-10T14:26:47.697Z" },
+ { url = "https://files.pythonhosted.org/packages/d6/be/080c96a45cd74f9fce5db4fd68510b88087fb37ffe2541ff73c12db92535/jiter-0.14.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:4b77da71f6e819be5fbcec11a453fde5b1d0267ef6ed487e2a392fd8e14e4e3a", size = 314870, upload-time = "2026-04-10T14:26:49.149Z" },
+ { url = "https://files.pythonhosted.org/packages/7d/5e/2d0fee155826a968a832cc32438de5e2a193292c8721ca70d0b53e58245b/jiter-0.14.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:77f4ea612fe8b84b8b04e51d0e78029ecf3466348e25973f953de6e6a59aa4c1", size = 343406, upload-time = "2026-04-10T14:26:50.762Z" },
+ { url = "https://files.pythonhosted.org/packages/70/af/bf9ee0d3a4f8dc0d679fc1337f874fe60cdbf841ebbb304b374e1c9aaceb/jiter-0.14.0-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:62fe2451f8fcc0240261e6a4df18ecbcd58327857e61e625b2393ea3b468aac9", size = 369415, upload-time = "2026-04-10T14:26:52.188Z" },
+ { url = "https://files.pythonhosted.org/packages/0f/83/8e8561eadba31f4d3948a5b712fb0447ec71c3560b57a855449e7b8ddc98/jiter-0.14.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6112f26f5afc75bcb475787d29da3aa92f9d09c7858f632f4be6ffe607be82e9", size = 461456, upload-time = "2026-04-10T14:26:53.611Z" },
+ { url = "https://files.pythonhosted.org/packages/f6/c9/c5299e826a5fe6108d172b344033f61c69b1bb979dd8d9ddd4278a160971/jiter-0.14.0-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:215a6cb8fb7dc702aa35d475cc00ddc7f970e5c0b1417fb4b4ac5d82fa2a29db", size = 378488, upload-time = "2026-04-10T14:26:55.211Z" },
+ { url = "https://files.pythonhosted.org/packages/5d/37/c16d9d15c0a471b8644b1abe3c82668092a707d9bedcf076f24ff2e380cd/jiter-0.14.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fc4ab96a30fb3cb2c7e0cd33f7616c8860da5f5674438988a54ac717caccdbaa", size = 353242, upload-time = "2026-04-10T14:26:56.705Z" },
+ { url = "https://files.pythonhosted.org/packages/58/ea/8050cb0dc654e728e1bfacbc0c640772f2181af5dedd13ae70145743a439/jiter-0.14.0-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:3a99c1387b1f2928f799a9de899193484d66206a50e98233b6b088a7f0c1edb2", size = 356823, upload-time = "2026-04-10T14:26:58.281Z" },
+ { url = "https://files.pythonhosted.org/packages/b0/3b/cf71506d270e5f84d97326bf220e47aed9b95e9a4a060758fb07772170ab/jiter-0.14.0-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:ab18d11074485438695f8d34a1b6da61db9754248f96d51341956607a8f39985", size = 392564, upload-time = "2026-04-10T14:27:00.018Z" },
+ { url = "https://files.pythonhosted.org/packages/b0/cc/8c6c74a3efb5bd671bfd14f51e8a73375464ca914b1551bc3b40e26ac2c9/jiter-0.14.0-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:801028dcfc26ac0895e4964cbc0fd62c73be9fd4a7d7b1aaf6e5790033a719b7", size = 520322, upload-time = "2026-04-10T14:27:01.664Z" },
+ { url = "https://files.pythonhosted.org/packages/41/24/68d7b883ec959884ddf00d019b2e0e82ba81b167e1253684fa90519ce33c/jiter-0.14.0-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:ad425b087aafb4a1c7e1e98a279200743b9aaf30c3e0ba723aec93f061bd9bc8", size = 552619, upload-time = "2026-04-10T14:27:03.316Z" },
+ { url = "https://files.pythonhosted.org/packages/b6/89/b1a0985223bbf3150ff9e8f46f98fc9360c1de94f48abe271bbe1b465682/jiter-0.14.0-cp313-cp313-win32.whl", hash = "sha256:882bcb9b334318e233950b8be366fe5f92c86b66a7e449e76975dfd6d776a01f", size = 205699, upload-time = "2026-04-10T14:27:04.662Z" },
+ { url = "https://files.pythonhosted.org/packages/4c/19/3f339a5a7f14a11730e67f6be34f9d5105751d547b615ef593fa122a5ded/jiter-0.14.0-cp313-cp313-win_amd64.whl", hash = "sha256:9b8c571a5dba09b98bd3462b5a53f27209a5cbbe85670391692ede71974e979f", size = 201323, upload-time = "2026-04-10T14:27:06.139Z" },
+ { url = "https://files.pythonhosted.org/packages/50/56/752dd89c84be0e022a8ea3720bcfa0a8431db79a962578544812ce061739/jiter-0.14.0-cp313-cp313-win_arm64.whl", hash = "sha256:34f19dcc35cb1abe7c369b3756babf8c7f04595c0807a848df8f26ef8298ef92", size = 191099, upload-time = "2026-04-10T14:27:07.564Z" },
+ { url = "https://files.pythonhosted.org/packages/91/28/292916f354f25a1fe8cf2c918d1415c699a4a659ae00be0430e1c5d9ffea/jiter-0.14.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:e89bcd7d426a75bb4952c696b267075790d854a07aad4c9894551a82c5b574ab", size = 320880, upload-time = "2026-04-10T14:27:09.326Z" },
+ { url = "https://files.pythonhosted.org/packages/ad/c7/b002a7d8b8957ac3d469bd59c18ef4b1595a5216ae0de639a287b9816023/jiter-0.14.0-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7b25beaa0d4447ea8c7ae0c18c688905d34840d7d0b937f2f7bdd52162c98a40", size = 346563, upload-time = "2026-04-10T14:27:11.287Z" },
+ { url = "https://files.pythonhosted.org/packages/f9/3b/f8d07580d8706021d255a6356b8fab13ee4c869412995550ce6ed4ddf97d/jiter-0.14.0-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:651a8758dd413c51e3b7f6557cdc6921faf70b14106f45f969f091f5cda990ea", size = 357928, upload-time = "2026-04-10T14:27:12.729Z" },
+ { url = "https://files.pythonhosted.org/packages/47/5b/ac1a974da29e35507230383110ffec59998b290a8732585d04e19a9eb5ba/jiter-0.14.0-cp313-cp313t-win_amd64.whl", hash = "sha256:e1a7eead856a5038a8d291f1447176ab0b525c77a279a058121b5fccee257f6f", size = 203519, upload-time = "2026-04-10T14:27:14.125Z" },
+ { url = "https://files.pythonhosted.org/packages/96/6d/9fc8433d667d2454271378a79747d8c76c10b51b482b454e6190e511f244/jiter-0.14.0-cp313-cp313t-win_arm64.whl", hash = "sha256:2e692633a12cda97e352fdcd1c4acc971b1c28707e1e33aeef782b0cbf051975", size = 190113, upload-time = "2026-04-10T14:27:16.638Z" },
+ { url = "https://files.pythonhosted.org/packages/4f/1e/354ed92461b165bd581f9ef5150971a572c873ec3b68a916d5aa91da3cc2/jiter-0.14.0-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:6f396837fc7577871ca8c12edaf239ed9ccef3bbe39904ae9b8b63ce0a48b140", size = 315277, upload-time = "2026-04-10T14:27:18.109Z" },
+ { url = "https://files.pythonhosted.org/packages/a6/95/8c7c7028aa8636ac21b7a55faef3e34215e6ed0cbf5ae58258427f621aa3/jiter-0.14.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:a4d50ea3d8ba4176f79754333bd35f1bbcd28e91adc13eb9b7ca91bc52a6cef9", size = 315923, upload-time = "2026-04-10T14:27:19.603Z" },
+ { url = "https://files.pythonhosted.org/packages/47/40/e2a852a44c4a089f2681a16611b7ce113224a80fd8504c46d78491b47220/jiter-0.14.0-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ce17f8a050447d1b4153bda4fb7d26e6a9e74eb4f4a41913f30934c5075bf615", size = 344943, upload-time = "2026-04-10T14:27:21.262Z" },
+ { url = "https://files.pythonhosted.org/packages/fc/1f/670f92adee1e9895eac41e8a4d623b6da68c4d46249d8b556b60b63f949e/jiter-0.14.0-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f4f1c4b125e1652aefbc2e2c1617b60a160ab789d180e3d423c41439e5f32850", size = 369725, upload-time = "2026-04-10T14:27:22.766Z" },
+ { url = "https://files.pythonhosted.org/packages/01/2f/541c9ba567d05de1c4874a0f8f8c5e3fd78e2b874266623da9a775cf46e0/jiter-0.14.0-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:be808176a6a3a14321d18c603f2d40741858a7c4fc982f83232842689fe86dd9", size = 461210, upload-time = "2026-04-10T14:27:24.315Z" },
+ { url = "https://files.pythonhosted.org/packages/ce/a9/c31cbec09627e0d5de7aeaec7690dba03e090caa808fefd8133137cf45bc/jiter-0.14.0-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:26679d58ba816f88c3849306dd58cb863a90a1cf352cdd4ef67e30ccf8a77994", size = 380002, upload-time = "2026-04-10T14:27:26.155Z" },
+ { url = "https://files.pythonhosted.org/packages/50/02/3c05c1666c41904a2f607475a73e7a4763d1cbde2d18229c4f85b22dc253/jiter-0.14.0-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:80381f5a19af8fa9aef743f080e34f6b25ebd89656475f8cf0470ec6157052aa", size = 354678, upload-time = "2026-04-10T14:27:27.701Z" },
+ { url = "https://files.pythonhosted.org/packages/7d/97/e15b33545c2b13518f560d695f974b9891b311641bdcf178d63177e8801e/jiter-0.14.0-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:004df5fdb8ecbd6d99f3227df18ba1a259254c4359736a2e6f036c944e02d7c5", size = 358920, upload-time = "2026-04-10T14:27:29.256Z" },
+ { url = "https://files.pythonhosted.org/packages/ad/d2/8b1461def6b96ba44530df20d07ef7a1c7da22f3f9bf1727e2d611077bf1/jiter-0.14.0-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:cff5708f7ed0fa098f2b53446c6fa74c48469118e5cd7497b4f1cd569ab06928", size = 394512, upload-time = "2026-04-10T14:27:31.344Z" },
+ { url = "https://files.pythonhosted.org/packages/e3/88/837566dd6ed6e452e8d3205355afd484ce44b2533edfa4ed73a298ea893e/jiter-0.14.0-cp314-cp314-musllinux_1_1_aarch64.whl", hash = "sha256:2492e5f06c36a976d25c7cc347a60e26d5470178d44cde1b9b75e60b4e519f28", size = 521120, upload-time = "2026-04-10T14:27:33.299Z" },
+ { url = "https://files.pythonhosted.org/packages/89/6b/b00b45c4d1b4c031777fe161d620b755b5b02cdade1e316dcb46e4471d63/jiter-0.14.0-cp314-cp314-musllinux_1_1_x86_64.whl", hash = "sha256:7609cfbe3a03d37bfdbf5052012d5a879e72b83168a363deae7b3a26564d57de", size = 553668, upload-time = "2026-04-10T14:27:34.868Z" },
+ { url = "https://files.pythonhosted.org/packages/ad/d8/6fe5b42011d19397433d345716eac16728ac241862a2aac9c91923c7509a/jiter-0.14.0-cp314-cp314-win32.whl", hash = "sha256:7282342d32e357543565286b6450378c3cd402eea333fc1ebe146f1fabb306fc", size = 207001, upload-time = "2026-04-10T14:27:36.455Z" },
+ { url = "https://files.pythonhosted.org/packages/e5/43/5c2e08da1efad5e410f0eaaabeadd954812612c33fbbd8fd5328b489139d/jiter-0.14.0-cp314-cp314-win_amd64.whl", hash = "sha256:bd77945f38866a448e73b0b7637366afa814d4617790ecd88a18ca74377e6c02", size = 202187, upload-time = "2026-04-10T14:27:38Z" },
+ { url = "https://files.pythonhosted.org/packages/aa/1f/6e39ac0b4cdfa23e606af5b245df5f9adaa76f35e0c5096790da430ca506/jiter-0.14.0-cp314-cp314-win_arm64.whl", hash = "sha256:f2d4c61da0821ee42e0cdf5489da60a6d074306313a377c2b35af464955a3611", size = 192257, upload-time = "2026-04-10T14:27:39.504Z" },
+ { url = "https://files.pythonhosted.org/packages/05/57/7dbc0ffbbb5176a27e3518716608aa464aee2e2887dc938f0b900a120449/jiter-0.14.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:1bf7ff85517dd2f20a5750081d2b75083c1b269cf75afc7511bdf1f9548beb3b", size = 323441, upload-time = "2026-04-10T14:27:41.039Z" },
+ { url = "https://files.pythonhosted.org/packages/83/6e/7b3314398d8983f06b557aa21b670511ec72d3b79a68ee5e4d9bff972286/jiter-0.14.0-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c8ef8791c3e78d6c6b157c6d360fbb5c715bebb8113bc6a9303c5caff012754a", size = 348109, upload-time = "2026-04-10T14:27:42.552Z" },
+ { url = "https://files.pythonhosted.org/packages/ae/4f/8dc674bcd7db6dba566de73c08c763c337058baff1dbeb34567045b27cdc/jiter-0.14.0-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:e74663b8b10da1fe0f4e4703fd7980d24ad17174b6bb35d8498d6e3ebce2ae6a", size = 368328, upload-time = "2026-04-10T14:27:44.574Z" },
+ { url = "https://files.pythonhosted.org/packages/3b/5f/188e09a1f20906f98bbdec44ed820e19f4e8eb8aff88b9d1a5a497587ff3/jiter-0.14.0-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1aca29ba52913f78362ec9c2da62f22cdc4c3083313403f90c15460979b84d9b", size = 463301, upload-time = "2026-04-10T14:27:46.717Z" },
+ { url = "https://files.pythonhosted.org/packages/ac/f0/19046ef965ed8f349e8554775bb12ff4352f443fbe12b95d31f575891256/jiter-0.14.0-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8b39b7d87a952b79949af5fef44d2544e58c21a28da7f1bae3ef166455c61746", size = 378891, upload-time = "2026-04-10T14:27:48.32Z" },
+ { url = "https://files.pythonhosted.org/packages/c4/c3/da43bd8431ee175695777ee78cf0e93eacbb47393ff493f18c45231b427d/jiter-0.14.0-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:78d918a68b26e9fab068c2b5453577ef04943ab2807b9a6275df2a812599a310", size = 360749, upload-time = "2026-04-10T14:27:49.88Z" },
+ { url = "https://files.pythonhosted.org/packages/72/26/e054771be889707c6161dbdec9c23d33a9ec70945395d70f07cfea1e9a6f/jiter-0.14.0-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:b08997c35aee1201c1a5361466a8fb9162d03ae7bf6568df70b6c859f1e654a4", size = 358526, upload-time = "2026-04-10T14:27:51.504Z" },
+ { url = "https://files.pythonhosted.org/packages/c3/0f/7bea65ea2a6d91f2bf989ff11a18136644392bf2b0497a1fa50934c30a9c/jiter-0.14.0-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:260bf7ca20704d58d41f669e5e9fe7fe2fa72901a6b324e79056f5d52e9c9be2", size = 393926, upload-time = "2026-04-10T14:27:53.368Z" },
+ { url = "https://files.pythonhosted.org/packages/3c/a1/b1ff7d70deef61ac0b7c6c2f12d2ace950cdeecb4fdc94500a0926802857/jiter-0.14.0-cp314-cp314t-musllinux_1_1_aarch64.whl", hash = "sha256:37826e3df29e60f30a382f9294348d0238ef127f4b5d7f5f8da78b5b9e050560", size = 521052, upload-time = "2026-04-10T14:27:55.058Z" },
+ { url = "https://files.pythonhosted.org/packages/0b/7b/3b0649983cbaf15eda26a414b5b1982e910c67bd6f7b1b490f3cfc76896a/jiter-0.14.0-cp314-cp314t-musllinux_1_1_x86_64.whl", hash = "sha256:645be49c46f2900937ba0eaf871ad5183c96858c0af74b6becc7f4e367e36e06", size = 553716, upload-time = "2026-04-10T14:27:57.269Z" },
+ { url = "https://files.pythonhosted.org/packages/97/f8/33d78c83bd93ae0c0af05293a6660f88a1977caef39a6d72a84afab94ce0/jiter-0.14.0-cp314-cp314t-win32.whl", hash = "sha256:2f7877ed45118de283786178eceaf877110abacd04fde31efff3940ae9672674", size = 207957, upload-time = "2026-04-10T14:27:59.285Z" },
+ { url = "https://files.pythonhosted.org/packages/d6/ac/2b760516c03e2227826d1f7025d89bf6bf6357a28fe75c2a2800873c50bf/jiter-0.14.0-cp314-cp314t-win_amd64.whl", hash = "sha256:14c0cb10337c49f5eafe8e7364daca5e29a020ea03580b8f8e6c597fed4e1588", size = 204690, upload-time = "2026-04-10T14:28:00.962Z" },
+ { url = "https://files.pythonhosted.org/packages/dc/2e/a44c20c58aeed0355f2d326969a181696aeb551a25195f47563908a815be/jiter-0.14.0-cp314-cp314t-win_arm64.whl", hash = "sha256:5419d4aa2024961da9fe12a9cfe7484996735dca99e8e090b5c88595ef1951ff", size = 191338, upload-time = "2026-04-10T14:28:02.853Z" },
+]
+
[[package]]
name = "jsonschema"
version = "4.26.0"
@@ -470,6 +533,7 @@ dependencies = [
{ name = "honcho" },
{ name = "httpx" },
{ name = "mcp" },
+ { name = "openai" },
{ name = "python-dotenv" },
{ name = "pyyaml" },
{ name = "requests" },
@@ -492,6 +556,7 @@ requires-dist = [
{ name = "honcho", specifier = ">=2.0" },
{ name = "httpx", specifier = ">=0.27" },
{ name = "mcp", specifier = ">=1.0" },
+ { name = "openai", specifier = ">=1.0" },
{ name = "pytest", marker = "extra == 'test'", specifier = ">=8.0" },
{ name = "pytest-asyncio", marker = "extra == 'test'", specifier = ">=0.24" },
{ name = "python-dotenv", specifier = ">=1.1" },
@@ -502,6 +567,25 @@ requires-dist = [
]
provides-extras = ["test", "lint"]
+[[package]]
+name = "openai"
+version = "2.37.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "anyio" },
+ { name = "distro" },
+ { name = "httpx" },
+ { name = "jiter" },
+ { name = "pydantic" },
+ { name = "sniffio" },
+ { name = "tqdm" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/32/50/5901f01ef14e6c27788beb91e54fef5d6204fb5fb9e97402fc8a14de2e32/openai-2.37.0.tar.gz", hash = "sha256:f4bc562cc5f3a43d40d678105572d9d44765f6e0f50c125f63055419b72f4bd9", size = 754706, upload-time = "2026-05-15T22:30:35.428Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ed/4c/bce61680d0699a78a405fd9a67989b175ba020590428831aab2ab1d2be7c/openai-2.37.0-py3-none-any.whl", hash = "sha256:814633888b8f3b1ffd6615697c6e4ef93632d08b7c2e28c8c5ef3556e5a10107", size = 1303238, upload-time = "2026-05-15T22:30:32.767Z" },
+]
+
[[package]]
name = "packaging"
version = "26.1"
@@ -848,6 +932,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/63/b6/aeadee5443e49baa2facd51131159fd6301cc4ccfc1541e4df7b021c37dd/ruff-0.15.11-py3-none-win_arm64.whl", hash = "sha256:063fed18cc1bbe0ee7393957284a6fe8b588c6a406a285af3ee3f46da2391ee4", size = 11032614, upload-time = "2026-04-16T18:46:34.487Z" },
]
+[[package]]
+name = "sniffio"
+version = "1.3.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/a2/87/a6771e1546d97e7e041b6ae58d80074f81b7d5121207425c964ddf5cfdbd/sniffio-1.3.1.tar.gz", hash = "sha256:f4324edc670a0f49750a81b895f35c3adb843cca46f0530f79fc1babb23789dc", size = 20372, upload-time = "2024-02-25T23:20:04.057Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e9/44/75a9c9421471a6c4805dbf2356f7c181a29c1879239abab1ea2cc8f38b40/sniffio-1.3.1-py3-none-any.whl", hash = "sha256:2f6da418d1f1e0fddd844478f41680e794e6051915791a034ff65e5f100525a2", size = 10235, upload-time = "2024-02-25T23:20:01.196Z" },
+]
+
[[package]]
name = "sse-starlette"
version = "3.3.3"
@@ -873,6 +966,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/0b/c9/584bc9651441b4ba60cc4d557d8a547b5aff901af35bda3a4ee30c819b82/starlette-1.0.0-py3-none-any.whl", hash = "sha256:d3ec55e0bb321692d275455ddfd3df75fff145d009685eb40dc91fc66b03d38b", size = 72651, upload-time = "2026-03-22T18:29:45.111Z" },
]
+[[package]]
+name = "tqdm"
+version = "4.67.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "colorama", marker = "sys_platform == 'win32'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/09/a9/6ba95a270c6f1fbcd8dac228323f2777d886cb206987444e4bce66338dd4/tqdm-4.67.3.tar.gz", hash = "sha256:7d825f03f89244ef73f1d4ce193cb1774a8179fd96f31d7e1dcde62092b960bb", size = 169598, upload-time = "2026-02-03T17:35:53.048Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/16/e1/3079a9ff9b8e11b846c6ac5c8b5bfb7ff225eee721825310c91b3b50304f/tqdm-4.67.3-py3-none-any.whl", hash = "sha256:ee1e4c0e59148062281c49d80b25b67771a127c85fc9676d3be5f243206826bf", size = 78374, upload-time = "2026-02-03T17:35:50.982Z" },
+]
+
[[package]]
name = "typing-extensions"
version = "4.15.0"