File size: 10,508 Bytes
891fe52 a526b57 891fe52 418081b 891fe52 418081b 891fe52 a526b57 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 | """Session management for Polyhedra v3.0.
A Session captures all mutable state for a single research collaboration:
- which agents are active
- the role registry
- the thread message log
- a reference to the Research State manager
Sessions are persisted under ``~/.polyhedra/sessions/<session_id>/``.
V4.4 additions:
- ``SessionManager.active_sessions_with_positions()`` — returns session IDs
that have open paper positions, used by the PortfolioMonitor scheduler.
- ``SessionManager`` persists an active sessions registry to
``~/.polyhedra/sessions/registry.json`` (FR-2.5).
"""
from __future__ import annotations
import json
import logging
import os
import uuid
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from polyhedra.core.research_state import ResearchState, ResearchStateManager
from polyhedra.core.role_registry import RoleRegistry, RoleEntry, HELD_BY_AGENT
logger = logging.getLogger(__name__)
_SESSIONS_DIR = Path.home() / ".polyhedra" / "sessions"
@dataclass
class ThreadMessage:
"""A single message in the session thread."""
from_role: str # "human" | agent role name
content: str
message_id: str = field(default_factory=lambda: str(uuid.uuid4())[:8])
timestamp: datetime = field(default_factory=lambda: datetime.now(tz=timezone.utc))
metadata: dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> dict[str, Any]:
return {
"from_role": self.from_role,
"content": self.content,
"message_id": self.message_id,
"timestamp": self.timestamp.isoformat(),
"metadata": self.metadata,
}
@classmethod
def from_dict(cls, d: dict[str, Any]) -> "ThreadMessage":
return cls(
from_role=d.get("from_role", "unknown"),
content=d.get("content", ""),
message_id=d.get("message_id", ""),
timestamp=datetime.fromisoformat(d["timestamp"]) if d.get("timestamp") else datetime.now(tz=timezone.utc),
metadata=d.get("metadata", {}),
)
class Session:
"""
All mutable state for a single Polyhedra session.
The session directory layout::
~/.polyhedra/sessions/<session_id>/
session.json # goal, active_roles, created_at, etc.
research_state.json # Research State (managed by ResearchStateManager)
thread.jsonl # append-only thread log
artifacts/ # exported draft sections, .bib, etc.
"""
def __init__(self, session_id: str, session_dir: Path) -> None:
self.session_id = session_id
self.session_dir = session_dir
self.session_dir.mkdir(parents=True, exist_ok=True)
self.state_manager = ResearchStateManager(session_dir)
self.registry = RoleRegistry()
self._thread_path = session_dir / "thread.jsonl"
self._meta_path = session_dir / "session.json"
self.goal: str = ""
self.active_roles: list[str] = []
self.created_at: datetime = datetime.now(tz=timezone.utc)
self.platform: str = "cli" # "cli" | "slack" | "teams" | "spark"
# ------------------------------------------------------------------ #
# Thread management
# ------------------------------------------------------------------ #
def post(self, from_role: str, content: str, metadata: dict[str, Any] | None = None) -> ThreadMessage:
"""Append a message to the thread and return it."""
msg = ThreadMessage(from_role=from_role, content=content, metadata=metadata or {})
with self._thread_path.open("a", encoding="utf-8") as fh:
fh.write(json.dumps(msg.to_dict()) + "\n")
return msg
def thread_history(self, last_n: int = 20) -> list[dict[str, Any]]:
"""Return the last N thread messages as plain dicts."""
if not self._thread_path.exists():
return []
lines = self._thread_path.read_text(encoding="utf-8").splitlines()
recent = lines[-last_n:]
messages = []
for line in recent:
try:
messages.append(json.loads(line))
except json.JSONDecodeError:
pass
return messages
def full_thread(self) -> list[ThreadMessage]:
"""Return all thread messages."""
if not self._thread_path.exists():
return []
messages = []
for line in self._thread_path.read_text(encoding="utf-8").splitlines():
try:
messages.append(ThreadMessage.from_dict(json.loads(line)))
except Exception:
pass
return messages
# ------------------------------------------------------------------ #
# Research State convenience
# ------------------------------------------------------------------ #
@property
def research_state(self) -> ResearchState:
return self.state_manager.load()
# ------------------------------------------------------------------ #
# Persistence
# ------------------------------------------------------------------ #
def save_meta(self) -> None:
meta = {
"session_id": self.session_id,
"goal": self.goal,
"active_roles": self.active_roles,
"created_at": self.created_at.isoformat(),
"platform": self.platform,
"role_registry": self.registry.to_dict(),
}
self._meta_path.write_text(json.dumps(meta, indent=2), encoding="utf-8")
def load_meta(self) -> None:
if not self._meta_path.exists():
return
try:
meta = json.loads(self._meta_path.read_text(encoding="utf-8"))
self.goal = meta.get("goal", "")
self.active_roles = meta.get("active_roles", [])
self.platform = meta.get("platform", "cli")
created = meta.get("created_at")
if created:
self.created_at = datetime.fromisoformat(created)
except Exception as exc:
logger.error("Failed to load session meta for %s: %s", self.session_id, exc)
class SessionManager:
"""Create, list, and resume sessions."""
def __init__(self, sessions_dir: Path | None = None) -> None:
configured_dir = os.environ.get("POLYHEDRA_SESSIONS_DIR", "").strip()
self._dir = sessions_dir or (
Path(configured_dir).expanduser() if configured_dir else _SESSIONS_DIR
)
self._dir.mkdir(parents=True, exist_ok=True)
def create(self, goal: str = "", platform: str = "cli", roles: list[str] | None = None) -> Session:
session_id = str(uuid.uuid4())[:8]
session_dir = self._dir / session_id
session = Session(session_id=session_id, session_dir=session_dir)
session.goal = goal
session.platform = platform
session.active_roles = roles or []
session.save_meta()
return session
def resume(self, session_id: str) -> Session | None:
session_dir = self._dir / session_id
if not session_dir.exists():
logger.error("Session %s not found.", session_id)
return None
session = Session(session_id=session_id, session_dir=session_dir)
session.load_meta()
return session
def list_sessions(self) -> list[dict[str, Any]]:
sessions = []
for path in sorted(self._dir.iterdir()):
if path.is_dir():
meta_file = path / "session.json"
if meta_file.exists():
try:
sessions.append(json.loads(meta_file.read_text(encoding="utf-8")))
except Exception:
pass
return sessions
def export(self, session_id: str, output_dir: Path) -> Path:
"""
Export all session artifacts (Research State, thread log, drafts, .bib)
into a zip archive at ``output_dir/<session_id>.zip``.
"""
import zipfile
session_dir = self._dir / session_id
if not session_dir.exists():
raise FileNotFoundError(f"Session {session_id} not found.")
output_dir.mkdir(parents=True, exist_ok=True)
zip_path = output_dir / f"{session_id}.zip"
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
for file in session_dir.rglob("*"):
if file.is_file():
zf.write(file, file.relative_to(session_dir))
return zip_path
# ------------------------------------------------------------------ #
# V4.4 FIX-2: Active session registry for PortfolioMonitor scheduler
# ------------------------------------------------------------------ #
def active_sessions_with_positions(self) -> list[str]:
"""Return session_ids where QuantState.portfolio has open PaperPositions.
Used by the PortfolioMonitor scheduler to know which sessions to
check on each tick (FR-2.1). Sessions with ``monitor_paused=True``
are excluded (FR-2.3).
"""
from polyhedra.core.research_state import ResearchStateManager
active: list[str] = []
for path in sorted(self._dir.iterdir()):
if not path.is_dir():
continue
meta_file = path / "session.json"
if not meta_file.exists():
continue
try:
manager = ResearchStateManager(path)
state = manager.load()
qs = state.quant_state
if qs is None:
continue
if qs.monitor_paused:
continue
open_positions = [p for p in qs.portfolio if p.status == "open"]
if open_positions:
active.append(path.name)
except Exception:
pass
return active
def _registry_path(self) -> Path:
return self._dir / "registry.json"
def _save_registry(self, session_ids: list[str]) -> None:
"""Persist active session IDs to registry.json so it survives restarts (FR-2.5)."""
try:
self._registry_path().write_text(
json.dumps({"active_sessions": session_ids}, indent=2),
encoding="utf-8",
)
except Exception as exc:
logger.warning("Failed to persist session registry: %s", exc)
|