Skip to content
Python

feat(observability): turn stamps, coworker fingerprint, context step, notices and sandbox facts (OPE-244)

Devika Vermae0a6400a4eaf
diff --git a/coworker/agent.py b/coworker/agent.py
index 299e128c..12a27a8f 100644
--- a/coworker/agent.py
+++ b/coworker/agent.py
@@ -28,6 +28,7 @@ from .environment import environment_context
from .memory import (
MemoryStore,
Scope,
+ format_memories,
format_user_rules,
memory_tools,
render_memory_block,
@@ -487,6 +488,9 @@ def build_engine(
# sleep_until all come from here.
registry.register_all(clock_tools())
+ _remembered: list = []
+ _memory_mode = "full"
+ _agents_md_count = 0
instructions = f"{agent.system_prompt}\n\n{_NARRATION_GUIDANCE}\n\n{_FIRST_CONTACT_GUIDANCE}"
if agent.team == "lead":
from .teams.proposals import PROPOSAL_GUIDANCE
@@ -519,6 +523,7 @@ def build_engine(
if ws is not None:
instructions = f"{instructions}\n\n{environment_context(ws)}"
conventions = load_agents_md(ws)
+ _agents_md_count = conventions.count(" AGENTS.md>\n") if conventions else 0
if conventions:
instructions = f"{instructions}\n\n{conventions}"
@@ -562,7 +567,9 @@ def build_engine(
remembered = memory_store.list(scope=Scope.GLOBAL)
if mem_ws is not None:
remembered += memory_store.list(scope=Scope.WORKSPACE, workspace=mem_ws)
+ _remembered = remembered
block = render_memory_block(remembered)
+ _memory_mode = "index" if block and block != format_memories(remembered) else "full"
if block:
instructions = f"{instructions}\n\n{block}"
@@ -886,6 +893,22 @@ def build_engine(
# attached but the LIVE path stays off unless the live feature flag is also on
# and the session is in Mode.AUTO_APPROVE. Shadow verdicts never clear actions.
engine.reviewer_shadow = bool(shadow_on)
+ # Observability E16 / E5: which version of the coworker this is, and what the session's
+ # system prompt was built from (counts and ids, never the text).
+ try:
+ from .observability.stamps import persona_fingerprint
+
+ engine.persona_fp = persona_fingerprint(
+ agent.name, agent.system_prompt, [Path(d) for d in (extra_skill_dirs or [])]
+ )
+ except Exception: # noqa: BLE001
+ engine.persona_fp = None
+ engine.context_facts = {
+ "memories": [getattr(m, "id", None) for m in (_remembered or [])],
+ "memory_mode": _memory_mode,
+ "rules": len([ln for ln in (rules_block or "").splitlines() if ln.strip().startswith("-")]),
+ "agents_md": _agents_md_count,
+ }
engine.audit_context = {
"session_id": session_id or "",
"agent": agent.name,
diff --git a/coworker/engine.py b/coworker/engine.py
index 82f6ed5f..d6197b52 100644
--- a/coworker/engine.py
+++ b/coworker/engine.py
@@ -35,6 +35,8 @@ from . import unattended as _attendance
from .events import Event, EventType
from .observability.decision import DecisionPath
from .observability.engine_hooks import ToolRun, TurnRecording, set_tool_run
+from .observability.recorder import short_hash as _short_hash
+from .observability import stamps as _stamps
from .observability.provider_view import tag as _tag_provider, view_for_engine
from .observability.ids import new_ulid
@@ -565,6 +567,13 @@ class TurnEngine:
# Auto-approver check steps by tool call (E12), and shadow checks waiting to be
# compared with your answer: call id -> (step id, verdict or None).
self._review_steps: dict[str, str] = {}
+ # The coworker fingerprint and the session-start context facts, set by the session
+ # build (observability E16, E5); and this turn's context block, to spot a change.
+ self.persona_fp: Optional[str] = None
+ self.context_facts: dict[str, Any] = {}
+ self._last_context_block = ""
+ self._turn_context_hash: Optional[str] = None
+ self._context_turn: Optional[str] = None
self._shadow_checks: dict[str, tuple[Optional[str], Any]] = {}
self._user_answers: dict[str, bool] = {}
if instructions and not (
@@ -704,11 +713,59 @@ class TurnEngine:
"model": getattr(self.reviewer, "model", None) if reviewer_kind == "session_model" else None,
},
},
- stamp={},
+ stamp=self._turn_stamp(),
first_message_id=first,
wait_for_first_message=kind == "retry",
)
+ def _turn_stamp(self) -> dict[str, Any]:
+ """Facts saved with the turn (observability §9): machine, model, sandbox, coworker."""
+ stamp: dict[str, Any] = {}
+ try:
+ stamp["machine"] = _stamps.machine_stamp()
+ stamp["model"] = _stamps.model_stamp(self.model)
+ sandbox = _stamps.sandbox_stamp(getattr(self, "sandbox_workspace", None))
+ if sandbox:
+ stamp["sandbox"] = sandbox
+ if self.persona_fp:
+ stamp["persona_fp"] = self.persona_fp
+ except Exception: # noqa: BLE001 - a stamp never breaks a turn
+ logger.exception("observability: could not stamp the turn")
+ return stamp
+
+ def _note_context(self) -> None:
+ """The context step at the turn's first model call, and a `context_changed` notice
+ when the per-turn block changes later in the turn (observability E5, §5.6)."""
+ obs = self._obs
+ if not obs.enabled or not obs.in_turn or not getattr(obs, "records_context", True):
+ return
+ block = self._last_context_block or ""
+ block_hash = _short_hash(block) if block else None
+ per_turn = {
+ "mode_note": self.permissions.mode.value if self.permissions.mode in (Mode.PLAN, Mode.DISCUSS) else None,
+ "folders": len(getattr(self, "roots", None) or []) if isinstance(getattr(self, "roots", None), (list, tuple)) else None,
+ "sandbox_note": getattr(getattr(self, "sandbox_workspace", None), "describe", None) is not None,
+ "skills_menu": None,
+ "skills_hash": None,
+ }
+ if self._context_turn != obs.turn_id:
+ self._context_turn, self._turn_context_hash = obs.turn_id, block_hash
+ system = self.messages[0].get("content") if self.messages and self.messages[0].get("role") == "system" else None
+ attrs: dict[str, Any] = {
+ "session_prompt_hash": _short_hash(system) if isinstance(system, str) else None,
+ "per_turn": per_turn,
+ "size_chars": len(block),
+ "block_hash": block_hash,
+ }
+ if self.context_facts and not getattr(self, "_context_session_told", False):
+ attrs["session_start"] = dict(self.context_facts)
+ self._context_session_told = True
+ obs.instant_step(kind="context", name="context", status="ok", attrs=attrs)
+ elif block_hash != self._turn_context_hash:
+ self._turn_context_hash = block_hash
+ obs.instant_step(kind="notice", name="context_changed", status="ok",
+ attrs={"per_turn": per_turn, "size_chars": len(block), "block_hash": block_hash})
+
def _observe_event(self, event: Event) -> None:
"""Ids on a UI event, a call that never ran as a zero-length tool step, and the turn's
end (E1). The app ignores fields it does not know, so older screens keep working."""
@@ -735,7 +792,11 @@ class TurnEngine:
if step_id:
event.data.setdefault("step_id", step_id)
if event.type is EventType.TURN_END:
- obs.end_turn(str(event.data.get("status") or "completed"))
+ status = str(event.data.get("status") or "completed")
+ if status in ("max_iterations_exceeded", "truncated"):
+ obs.instant_step(kind="notice", name="step_limit" if status == "max_iterations_exceeded" else "truncated",
+ status="ok", attrs={})
+ obs.end_turn(status)
elif event.type is EventType.INTERRUPTED:
obs.end_turn("interrupted")
elif event.type is EventType.ERROR:
@@ -916,6 +977,9 @@ class TurnEngine:
notice["text"] = text
notice.update({k: v for k, v in fields.items() if v is not None})
self._add_message(notice)
+ if kind in ("interrupted", "error", "reviewer_paused"):
+ # A zero-length marker on the timeline (observability §5.8).
+ self._obs.instant_step(kind="notice", name=kind, status="ok", attrs={})
@_records_turn("retry")
@_summarizes_turn
@@ -1516,6 +1580,7 @@ class TurnEngine:
self._outbound_messages(),
self.model_settings,
)
+ self._note_context()
provider = self.provider
def produce():
@@ -2703,9 +2768,12 @@ class TurnEngine:
result, status = self._execute_call(tool_call)
finally:
set_tool_run(outer)
+ blocked = result.pop("_blocked", None) if isinstance(result, dict) else None
if step_id is not None:
+ attrs = self._tool_step_attrs(tool_call, {**result, "_blocked": blocked} if blocked else result)
self._obs.end_step(
- step_id, status=status, attrs=self._tool_step_attrs(tool_call, result),
+ step_id, status=status, attrs=attrs,
+ content={"blocked": blocked} if blocked else {},
wait_for_tool_message=True,
)
return result, status
@@ -2724,8 +2792,23 @@ class TurnEngine:
pass
if isinstance(result, dict) and isinstance(result.get("exit_code"), int):
attrs["exit_code"] = result["exit_code"]
+ attrs["sandbox"] = self._sandbox_facts(result)
return attrs
+ def _sandbox_facts(self, result: Any) -> Optional[dict[str, Any]]:
+ """Per-call sandbox facts (observability E13, §9.3): whether this sandbox can report
+ blocked sites now, and how many connections it refused during the call. None when
+ the call did not run in a sandbox."""
+ ws = getattr(self, "sandbox_workspace", None)
+ if ws is None or not hasattr(ws, "reports_blocked"):
+ return None
+ blocked = result.get("_blocked") if isinstance(result, dict) else None
+ return {
+ "blocked_known": bool(getattr(ws, "reports_blocked", False)),
+ "blocked_count": sum(int(b.get("count") or 0) for b in blocked or []),
+ "notice": None,
+ }
+
def _execute_call(self, tool_call: ToolCall) -> tuple[Any, str]:
started, clock = time.time(), time.monotonic()
try:
@@ -3727,6 +3810,7 @@ class TurnEngine:
context = (
self.context_provider() if self.context_provider is not None else ""
) or ""
+ self._last_context_block = context
if not context:
return out
# The block rides on the LAST user message — one shape for every provider. In a
diff --git a/coworker/observability/engine_hooks.py b/coworker/observability/engine_hooks.py
index 6576a9fd..9c9cbcad 100644
--- a/coworker/observability/engine_hooks.py
+++ b/coworker/observability/engine_hooks.py
@@ -397,6 +397,9 @@ class HelperRecording:
not recorded as turns. Its tools run read-only in Plan mode, so their decision is
`{helper: true}` instead of a full path."""
+ # The helper's context is not the session's: no context step under the explore step.
+ records_context = False
+
def __init__(self, parent: TurnRecording, parent_step_id: str, turn_id: Optional[str]) -> None:
self.parent, self.parent_step_id = parent, parent_step_id
self.turn_id = turn_id
diff --git a/coworker/observability/stamps.py b/coworker/observability/stamps.py
new file mode 100644
index 00000000..6b3d0c23
--- /dev/null
+++ b/coworker/observability/stamps.py
@@ -0,0 +1,123 @@
+"""Stamps: facts saved with every turn (observability E15a, E16; technical design §9).
+
+`turn.stamp` has four optional keys: `machine` (where the work ran), `model` (which model
+and provider key), `sandbox` (how protected) and `persona_fp` (which version of the coworker).
+They are taken once at turn start.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import socket
+import threading
+from pathlib import Path
+from typing import Any, Iterable, Optional
+
+CLOUD_CONTROLLER = "https://machines.openworker.com"
+
+_machine_lock = threading.Lock()
+_machine: Optional[dict[str, Any]] = None
+
+
+def machine_kind(controller: Optional[str], cloud_base: str = CLOUD_CONTROLLER) -> str:
+ """`this_machine` when not joined to a controller; `cloud` for OpenWorker's cloud
+ machines; `own_machine` for a remote machine you added (§9.1)."""
+ if not controller:
+ return "this_machine"
+ return "cloud" if controller.rstrip("/") == cloud_base.rstrip("/") else "own_machine"
+
+
+def app_version_or_unknown() -> str:
+ """The OpenWorker version; `unknown`, never `0.0.0` (C6)."""
+ try:
+ from ..remote.channel import app_version
+
+ v = app_version()
+ except Exception: # noqa: BLE001
+ return "unknown"
+ return "unknown" if (not v or v == "0.0.0") else v
+
+
+def machine_stamp() -> dict[str, Any]:
+ """Where this server runs: read once per process."""
+ global _machine
+ with _machine_lock:
+ if _machine is None:
+ cfg: dict[str, Any] = {}
+ try:
+ from ..remote.joiner import load_remote_config
+ from ..secrets import state_dir
+
+ cfg = load_remote_config(state_dir()) or {}
+ except Exception: # noqa: BLE001
+ cfg = {}
+ try:
+ host = socket.gethostname()
+ except Exception: # noqa: BLE001
+ host = None
+ _machine = {
+ "kind": machine_kind(cfg.get("controller")),
+ "id": cfg.get("machine_id") or None,
+ "name": cfg.get("name") or host,
+ "app_version": app_version_or_unknown(),
+ }
+ return dict(_machine)
+
+
+def model_stamp(model: str) -> dict[str, Any]:
+ """The turn's model and which provider key it used (§9.2)."""
+ provider = model.split(":", 1)[0] if ":" in model else "openai"
+ title = kind = None
+ try:
+ from ..providers.registry import get_descriptor
+
+ d = get_descriptor(provider)
+ if d is not None:
+ title, kind = getattr(d, "title", None), getattr(d, "kind", None)
+ except Exception: # noqa: BLE001
+ pass
+ return {"id": model, "provider_title": title, "kind": kind}
+
+
+def sandbox_stamp(workspace: Any) -> Optional[dict[str, Any]]:
+ """The turn's sandbox (§9.3, per turn), from `describe()`; None when there is none."""
+ describe = getattr(workspace, "describe", None)
+ if describe is None:
+ return None
+ try:
+ info = describe() or {}
+ except Exception: # noqa: BLE001
+ return None
+ runner = info.get("runner") or {}
+ out = {
+ "provider": info.get("provider"),
+ "enforcement": info.get("enforcement"),
+ "profile": getattr(getattr(workspace, "provider", None), "profile", None),
+ "sites": _site_count(workspace),
+ "runner_version": runner.get("runner_version"),
+ "image": info.get("image"),
+ }
+ return {k: v for k, v in out.items() if v is not None}
+
+
+def _site_count(workspace: Any) -> Optional[int]:
+ sites = getattr(getattr(workspace, "provider", None), "allowed_sites", None)
+ try:
+ return len(sites) if sites is not None else None
+ except TypeError:
+ return None
+
+
+def persona_fingerprint(persona_id: str, manifest: str | bytes, skill_dirs: Iterable[Path] = ()) -> str:
+ """Which version of this coworker ran (§9.4): sha256 of its id, its manifest text and
+ its own skill files (sorted by relative path), first 6 hex characters. Not your own or
+ the workspace's skills, memories, AGENTS.md, the model or the tools."""
+ data = manifest.encode("utf-8") if isinstance(manifest, str) else manifest
+ h = hashlib.sha256(("persona:" + persona_id + "\n").encode("utf-8") + data)
+ for d in skill_dirs:
+ d = Path(d)
+ if not d.is_dir():
+ continue
+ for f in sorted((p for p in d.rglob("*") if p.is_file()), key=lambda p: p.relative_to(d).as_posix()):
+ h.update(f.relative_to(d).as_posix().encode("utf-8") + b"\n" + f.read_bytes())
+ return h.hexdigest()[:6]
diff --git a/coworker/sandbox/workspace.py b/coworker/sandbox/workspace.py
index 657cf4aa..c2a52b9e 100644
--- a/coworker/sandbox/workspace.py
+++ b/coworker/sandbox/workspace.py
@@ -281,7 +281,18 @@ class RunnerWorkspace(Workspace):
for _, entry in new:
counts[entry] = counts.get(entry, 0) + 1
late = any(when < started - 0.5 for when, _ in new)
- return {"blocked_sites": list(counts), "network_note": network_note_text(counts, can_ask=self._asking(), late=late)}
+ first: dict[str, float] = {}
+ for when, entry in new:
+ first[entry] = min(first.get(entry, when), when)
+ # `_blocked` is for the recording's tool step (observability E13, V-04); the engine
+ # takes it out of the result before the model sees it.
+ blocked = [
+ {"site": entry, "count": n, "first_at": int(first[entry] * 1000),
+ "late": first[entry] < started - 0.5, "uncertain": True}
+ for entry, n in counts.items()
+ ]
+ return {"blocked_sites": list(counts), "network_note": network_note_text(counts, can_ask=self._asking(), late=late),
+ "_blocked": blocked}
def _blocked_untold(self) -> list[tuple[float, str]]:
return [item for item in self.blocked_since(self._blocked_told) if item[0] > self._blocked_told]
diff --git a/tests/test_observability_model_steps.py b/tests/test_observability_model_steps.py
index 906bad2b..9e7d7b40 100644
--- a/tests/test_observability_model_steps.py
+++ b/tests/test_observability_model_steps.py
@@ -146,8 +146,8 @@ def test_every_model_call_is_a_main_model_step(tmp_path):
assert first["attrs"]["model"] == "openai:model-a" and first["attrs"]["provider"] == "openai"
assert first["attrs"]["tools_offered"] > 0 and first["attrs"]["tools_hash"]
assert all(s["turn_id"] == d["turns"][0]["turn_id"] for s in models)
- # canonical order: model, tool, model
- assert [s["kind"] for s in d["steps"]] == ["model", "tool", "model"]
+ # canonical order: the context taken at the first model call, then model, tool, model
+ assert [s["kind"] for s in d["steps"]] == ["context", "model", "tool", "model"]
def test_a_failed_model_call_is_an_error_step(tmp_path):
diff --git a/tests/test_observability_stamps_context.py b/tests/test_observability_stamps_context.py
new file mode 100644
index 00000000..3aae7409
--- /dev/null
+++ b/tests/test_observability_stamps_context.py
@@ -0,0 +1,188 @@
+"""Observability E15a, E16, E5, E13: stamps, the coworker fingerprint, the context step,
+notices and per-call sandbox facts."""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+
+from coworker.engine import TurnEngine
+from coworker.observability import Recorder
+from coworker.observability import stamps
+from coworker.permissions import Mode, PermissionEngine
+from coworker.providers import AssistantTurn, ModelCapabilities, ProviderClient, ToolCall
+from coworker.tools import ToolRegistry
+
+
+class _Scripted(ProviderClient):
+ def __init__(self, turns):
+ self._turns = list(turns)
+
+ def complete(self, *, model, messages, tools=None, **settings):
+ turn = self._turns.pop(0)
+ if isinstance(turn, Exception):
+ raise turn
+ return turn
+
+ def capabilities(self, model):
+ return ModelCapabilities()
+
+
+class _ReadMeta:
+ category: str = ""
+ risk_level: str = "low"
+ requires_approval: bool = False
+
+
+_BLOCK = {"text": ""}
+
+
+def look(path: str) -> dict:
+ """Read something.
+
+ Args:
+ path: what to read
+ """
+ if _BLOCK["text"]:
+ _BLOCK["text"] += ", b" # a skill became available mid-turn
+ return {"path": path}
+
+
+def _engine(tmp_path, turns, *, blocks=None, max_iterations=12):
+ registry = ToolRegistry()
+ registry.register(look, metadata=_ReadMeta())
+ _BLOCK["text"] = blocks[0] if blocks else ""
+ engine = TurnEngine(
+ provider=_Scripted(turns), registry=registry,
+ permissions=PermissionEngine(workspace_root=tmp_path, mode=Mode.BYPASS_APPROVALS),
+ model="openai:model-a", instructions="You are a test coworker.",
+ context_provider=(lambda: _BLOCK["text"]) if blocks else None,
+ max_iterations=max_iterations,
+ )
+ engine.audit_context = {"session_id": "sess_c"}
+ engine.persona_fp = "9f3a21"
+ engine.context_facts = {"memories": [12, 15], "memory_mode": "full", "rules": 2, "agents_md": 1}
+ rec = Recorder()
+ engine.recorder = rec
+ return engine, rec
+
+
+def _run(engine, text="go"):
+ async def go():
+ return [ev async for ev in engine.run(text, trigger="user")]
+
+ return asyncio.run(go())
+
+
+def _call(cid, name, args):
+ return AssistantTurn(tool_calls=[ToolCall(id=cid, name=name, arguments=args)], finish_reason="tool_calls")
+
+
+def test_the_turn_is_stamped(tmp_path):
+ engine, rec = _engine(tmp_path, [AssistantTurn(text="hi")])
+ _run(engine)
+ stamp = rec.as_dict()["turns"][0]["stamp"]
+ assert stamp["machine"]["kind"] in ("this_machine", "own_machine", "cloud")
+ assert stamp["machine"]["app_version"] != "0.0.0"
+ assert stamp["model"]["id"] == "openai:model-a"
+ assert stamp["persona_fp"] == "9f3a21"
+
+
+def test_machine_kind():
+ assert stamps.machine_kind(None) == "this_machine"
+ assert stamps.machine_kind("https://machines.openworker.com/") == "cloud"
+ assert stamps.machine_kind("https://my-box.example:8443") == "own_machine"
+
+
+def test_fingerprint_changes_only_with_the_coworkers_own_files(tmp_path):
+ skills = tmp_path / "skills"
+ (skills / "a").mkdir(parents=True)
+ (skills / "a" / "SKILL.md").write_text("one", encoding="utf-8")
+ fp = stamps.persona_fingerprint("helper", "manifest text", [skills])
+ assert len(fp) == 6
+ assert stamps.persona_fingerprint("helper", "manifest text", [skills]) == fp
+ (skills / "a" / "SKILL.md").write_text("two", encoding="utf-8")
+ assert stamps.persona_fingerprint("helper", "manifest text", [skills]) != fp
+ assert stamps.persona_fingerprint("other", "manifest text", [skills]) != stamps.persona_fingerprint(
+ "helper", "manifest text", [skills])
+
+
+def test_a_context_step_at_the_first_model_call_and_a_notice_when_it_changes(tmp_path):
+ engine, rec = _engine(tmp_path, [_call("c1", "look", {"path": "x"}), AssistantTurn(text="ok")],
+ blocks=["Folders: /w\nSkills: a"])
+ _run(engine)
+ steps = rec.as_dict()["steps"]
+ [context] = [s for s in steps if s["kind"] == "context"]
+ a = context["attrs"]
+ assert context["duration_ms"] == 0
+ assert a["size_chars"] == len("Folders: /w\nSkills: a") and len(a["block_hash"]) == 6
+ assert len(a["session_prompt_hash"]) == 6
+ assert a["session_start"] == {"memories": [12, 15], "memory_mode": "full", "rules": 2, "agents_md": 1}
+ [changed] = [s for s in steps if s["kind"] == "notice"]
+ assert changed["name"] == "context_changed"
+ assert changed["attrs"]["block_hash"] != a["block_hash"]
+ assert steps[0]["kind"] == "context"
+
+
+def test_session_start_facts_only_on_the_first_turn(tmp_path):
+ engine, rec = _engine(tmp_path, [AssistantTurn(text="a"), AssistantTurn(text="b")])
+ _run(engine, "one")
+ _run(engine, "two")
+ contexts = [s for s in rec.as_dict()["steps"] if s["kind"] == "context"]
+ assert len(contexts) == 2
+ assert "session_start" in contexts[0]["attrs"] and "session_start" not in contexts[1]["attrs"]
+
+
+def test_error_and_step_limit_are_notices(tmp_path):
+ engine, rec = _engine(tmp_path, [RuntimeError("boom")])
+ _run(engine)
+ assert [s["name"] for s in rec.as_dict()["steps"] if s["kind"] == "notice"] == ["error"]
+
+ engine, rec = _engine(tmp_path, [_call("c1", "look", {"path": "x"}), _call("c2", "look", {"path": "y"})],
+ max_iterations=1)
+ _run(engine)
+ assert "step_limit" in [s["name"] for s in rec.as_dict()["steps"] if s["kind"] == "notice"]
+
+
+def test_blocked_sites_go_to_the_tool_step_not_the_transcript(tmp_path):
+ class _Sandbox:
+ reports_blocked = True
+
+ def describe(self):
+ return {"provider": "openshell", "enforcement": "full"}
+
+ def fetch(url: str) -> dict:
+ """Fetch a page.
+
+ Args:
+ url: the page
+ """
+ return {"exit_code": 1, "blocked_sites": ["semgrep.dev:443"], "network_note": "blocked",
+ "_blocked": [{"site": "semgrep.dev:443", "count": 2, "first_at": 1, "late": False,
+ "uncertain": True}]}
+
+ engine, rec = _engine(tmp_path, [_call("c1", "fetch", {"url": "https://semgrep.dev"}), AssistantTurn(text="ok")])
+ engine.registry.register(fetch, metadata=_ReadMeta())
+ engine.sandbox_workspace = _Sandbox()
+ _run(engine)
+ [tool] = [s for s in rec.as_dict()["steps"] if s["kind"] == "tool"]
+ assert tool["attrs"]["sandbox"] == {"blocked_known": True, "blocked_count": 2, "notice": None}
+ assert tool["content"]["blocked"][0]["site"] == "semgrep.dev:443"
+ result = next(m for m in engine.messages if m.get("role") == "tool")
+ assert "_blocked" not in str(result["content"])
+ assert rec.as_dict()["turns"][0]["stamp"]["sandbox"] == {"provider": "openshell", "enforcement": "full"}
+
+
+def test_network_note_keeps_the_counts(tmp_path, monkeypatch):
+ from coworker.sandbox.workspace import RunnerWorkspace
+
+ ws = RunnerWorkspace.__new__(RunnerWorkspace)
+ ws._blocked_told = 0.0
+ ws.provider = type("P", (), {"blocked_lag": 0.0})()
+ monkeypatch.setattr(RunnerWorkspace, "reports_blocked", property(lambda self: True), raising=False)
+ monkeypatch.setattr(ws, "blocked_since", lambda t: [(100.0, "semgrep.dev:443"), (101.0, "semgrep.dev:443")], raising=False)
+ monkeypatch.setattr(ws, "_asking", lambda: False, raising=False)
+ note = ws.network_note(started=100.0, result={"exit_code": 0})
+ assert note["blocked_sites"] == ["semgrep.dev:443"]
+ assert note["_blocked"] == [{"site": "semgrep.dev:443", "count": 2, "first_at": 100000, "late": False,
+ "uncertain": True}]