Python
Make the time a tool instead of a line in every turn (OPE-192, final fix)
Devika Vermac1e8b8cdf33e
diff --git a/coworker/agent.py b/coworker/agent.pyindex b8ad3476..0aa3a9c6 100644--- a/coworker/agent.py+++ b/coworker/agent.py@@ -6,12 +6,12 @@ the skill catalog (progressive disclosure) + load_skill into a TurnEngine.from __future__ import annotations-from datetime import datetimefrom pathlib import Pathfrom typing import Any, Callable, Optionalfrom .agents import Agent, AgentContext, code_agentfrom .automation import scheduling_tools+from .clock import clock_toolsfrom .selfwake import selfwake_toolsfrom .subscriptions import subscription_toolsfrom .config import load_config@@ -406,6 +406,11 @@ def build_engine(# on-completion / on-event). The scheduler tick resumes due wakes.if wake_store is not None and session_id and agent.scheduling:registry.register_all(selfwake_tools(wake_store, session_id))+ # The clock, on demand, for every surface: the system prompt's "Today's date" is a+ # session-start snapshot, and the per-turn context block must not carry a live time+ # (see context_provider below). Deadlines, "how long ago", and the wake time for+ # sleep_until all come from here.+ registry.register_all(clock_tools())instructions = f"{agent.system_prompt}\n\n{_NARRATION_GUIDANCE}\n\n{_FIRST_CONTACT_GUIDANCE}"if ws is not None:@@ -530,17 +535,14 @@ def build_engine(_engine_box: list = []def context_provider() -> str:- # Live clock, every turn (owner ruling 2026-08-20): the environment block's- # "Today's date" is a session-START snapshot — stale for long-lived/self-waking- # sessions — and carries no time of day, which absolute scheduling- # (sleep_until, scheduled tasks) needs to compute wake times.+ # Nothing here may move on its own (OPE-192). The block is glued onto a message+ # the provider has already cached, so a value that changes by itself — the live+ # clock this block carried from 2026-08-20 to 2026-09-17 — rewrites that message+ # on every turn and throws the whole cached conversation away. The time is a+ # tool now (`current_time`, registered for every session) and a timer wake says+ # when it fired; the folders, mode notices and skill menu below change only when+ # the user changes something.parts: list[str] = []- if config.live_clock:- now = datetime.now().astimezone()- parts.append(f"Now: {now.strftime('%Y-%m-%d %H:%M')} ({now.tzname()})")- # OPE-192: with live_clock off the block carries only the folders and the skill- # menu, which change rarely, so it stays byte-identical turn to turn and the- # provider's prompt cache keeps working wherever the block lands.if permissions.mode is Mode.PLAN:parts.append(_PLAN_MODE_CONTEXT)elif permissions.mode is Mode.DISCUSS:diff --git a/coworker/clock.py b/coworker/clock.pynew file mode 100644index 00000000..7152ada5--- /dev/null+++ b/coworker/clock.py@@ -0,0 +1,34 @@+"""The clock, as a tool.++The current time is deliberately NOT in the per-turn context block (OPE-192): that block+is glued onto a message the provider has already cached, and a value that changes by+itself rewrites the message on every turn, which throws the whole cached conversation+away — measured at up to 77% of a long session's cost. A tool call costs a+few tokens and only when the model actually needs the time (a deadline, "how long ago",+an absolute wake time for `sleep_until`). Relative waits (`sleep_for`) and timer wakes+(the wake message carries its fire time) need no clock reading at all.+"""++from __future__ import annotations++from datetime import datetime, timezone+++def current_time() -> dict:+ """The current date and time. Call this when a task depends on the clock — a+ deadline, "how long ago", the date for a note, or the wake time for sleep_until.+ The "Today's date" in your environment is a session-start snapshot and may be stale;+ this is live. Returns the local time with its UTC offset and timezone name, the+ same instant in UTC, and the weekday."""+ now = datetime.now().astimezone()+ utc = now.astimezone(timezone.utc)+ return {+ "local": now.isoformat(timespec="seconds"),+ "timezone": now.tzname() or "",+ "utc": utc.isoformat(timespec="seconds").replace("+00:00", "Z"),+ "weekday": now.strftime("%A"),+ }+++def clock_tools() -> list:+ return [current_time]diff --git a/coworker/config.py b/coworker/config.pyindex a79d718e..ee9c018c 100644--- a/coworker/config.py+++ b/coworker/config.py@@ -66,12 +66,6 @@ class Config:# the summary itself never gets written. Environment override:# COWORKER_COMPACTION_SUMMARY_MAX_TOKENS.compaction_summary_max_tokens: Optional[int] = None- # OPE-192: the per-turn context block opens with the current time to the minute (owner- # ruling 2026-08-20: scheduling and self-waking sessions need it). That line changes- # the block every minute, and a provider's prompt cache is reusable only up to the- # first byte that differs. Set false where nothing schedules (benchmarks, batch jobs)- # to make the block static. Environment override: COWORKER_LIVE_CLOCK=0.- live_clock: bool = Trueallowed_commands: list[str] = field(default_factory=lambda: list(DEFAULT_ALLOWED_COMMANDS))@@ -124,7 +118,6 @@ _FIELDS = {"tool_result_max_bytes","compaction_cap_tokens","compaction_summary_max_tokens",- "live_clock","allowed_commands","auto_allow","allowed_domains",@@ -180,7 +173,6 @@ REASONING_EFFORT_ENV = "COWORKER_REASONING_EFFORT"TOOL_RESULT_MAX_BYTES_ENV = "COWORKER_TOOL_RESULT_MAX_BYTES"COMPACTION_CAP_TOKENS_ENV = "COWORKER_COMPACTION_CAP_TOKENS"COMPACTION_SUMMARY_MAX_TOKENS_ENV = "COWORKER_COMPACTION_SUMMARY_MAX_TOKENS"-LIVE_CLOCK_ENV = "COWORKER_LIVE_CLOCK"def _nonnegative_int(value: Any, source: str) -> Optional[int]:@@ -284,13 +276,6 @@ def load_config(f"compaction_cap_tokens must be a positive integer, got {raw_comp!r} ({COMPACTION_CAP_TOKENS_ENV})")cfg.compaction_cap_tokens = parsed_comp- if not isinstance(cfg.live_clock, bool):- raise ValueError(f"live_clock must be true or false, got {cfg.live_clock!r} (config.toml)")- raw_clock = (os.environ.get(LIVE_CLOCK_ENV) or "").strip().lower()- if raw_clock:- if raw_clock not in ("0", "1", "true", "false", "yes", "no", "on", "off"):- raise ValueError(f"live_clock must be 0/1/true/false, got {raw_clock!r} ({LIVE_CLOCK_ENV})")- cfg.live_clock = raw_clock in ("1", "true", "yes", "on")cfg.compaction_summary_max_tokens = _positive_int_setting(cfg.compaction_summary_max_tokens,"compaction_summary_max_tokens",diff --git a/coworker/engine.py b/coworker/engine.pyindex cd8a9c0a..4dfba916 100644--- a/coworker/engine.py+++ b/coworker/engine.py@@ -2268,41 +2268,35 @@ class TurnEngine:) or ""if not context:return out- # OPE-192: the block goes on the NEWEST message, never further up. It carries a live- # clock (owner ruling 2026-08-20), so it changes every minute; anything it is- # attached to changes with it, and a provider's prompt cache is reusable only up to- # the first byte that differs. Attaching it to "the last user message" was right for- # chat (that IS the newest message) and wrong for a tool loop: tool results carry- # role "tool", so the last user message there is the task prompt — message one — and- # every minute crossing rewrote the whole conversation. Measured on Terminal-Bench:- # 16 of 105 calls on one Fable 5.1 attempt held 95% of its cache writes, 77% of its- # cost; on the Kimi K3 run, 60% of minute crossings missed vs 1.5% otherwise.- # Anthropic's diagnostics named it: `messages_changed`, first message.- #- # And it rides as its OWN trailing message in both shapes, never glued onto the- # user's text. The first attempt appended it to the newest user message when there- # was one; that keeps the engine's list stable, but a provider registers a cache- # entry only at its breakpoint, and Anthropic's breakpoint is the final content- # block — the note. The stable text before it was never an entry of its own, so the- # next turn (which no longer carries that note) matched nothing: every call missed- # (27/27 on the validation run, 17.24 USD vs 7.41). A separate message lets the- # Anthropic provider put its breakpoint on the last STABLE block and the note after- # it (see `_add_cache_breakpoints`); the converter folds the note into the same- # user message on the wire, so the model sees exactly what it saw before. The- # OpenAI-compatible wire accepts consecutive user messages and a user message after- # tool messages. Ephemeral like before: never persisted.- if out:- out.append(- {- "role": "user",- "content": (- f"{EPHEMERAL_CONTEXT_OPEN}\n"- "(automatic per-turn context, not a message from the user — "- "continue the task)\n"- f"{context}\n</system-context>"- ),- }- )+ # The block rides on the LAST user message — one shape for every provider. In a+ # chat that is the newest message; in a tool loop (tool results carry role "tool")+ # it is the task prompt, message one. That is only safe because the block holds+ # nothing that moves on its own. OPE-192: it used to open with a `Now:` line to the+ # minute, so every minute crossing rewrote message one, and a provider's prompt+ # cache is reusable only up to the first byte that differs — the whole conversation+ # was re-processed (measured: 16 of 105 calls on one Fable 5.1 attempt held 95% of+ # its cache writes; on the Kimi K3 run 60% of minute crossings missed vs 1.5%+ # otherwise). The time is a tool now (`current_time`). What is left — folders,+ # skill menu, mode notices — changes only when the user changes something, so the+ # outbound history stays byte-identical turn to turn. Ephemeral: never persisted.+ block = (+ f"\n\n{EPHEMERAL_CONTEXT_OPEN}\n"+ "(automatic per-turn context, not part of the user's message)\n"+ f"{context}\n</system-context>"+ )+ for i in range(len(out) - 1, -1, -1):+ if out[i].get("role") != "user":+ continue+ msg = dict(out[i])+ content = msg.get("content")+ if isinstance(content, str):+ msg["content"] = content + block+ elif isinstance(content, list): # content-parts (text + images)+ msg["content"] = [*content, {"type": "text", "text": block}]+ else:+ msg["content"] = block+ out[i] = msg+ breakreturn outdiff --git a/coworker/environment.py b/coworker/environment.pyindex 3e47f5c2..b7eb5345 100644--- a/coworker/environment.py+++ b/coworker/environment.py@@ -62,7 +62,7 @@ def environment_context(workspace: str | Path) -> str:lines = [f"Workspace: {ws}",f"Platform: {sys.platform} ({os_name})",- f"Today's date: {date.today().isoformat()}",+ f"Today's date: {date.today().isoformat()} (at session start; call current_time for the live clock)",*_git_snapshot(ws),]body = "\n".join(lines)diff --git a/coworker/providers/anthropic_provider.py b/coworker/providers/anthropic_provider.pyindex 7197f5a0..ab946c31 100644--- a/coworker/providers/anthropic_provider.py+++ b/coworker/providers/anthropic_provider.py@@ -274,43 +274,6 @@ def _user_blocks(content: Any) -> list[dict[str, Any]]:return blocks-def _relocate_ephemeral_note(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:- """OPE-192: the engine sends its per-turn `<system-context>` note as a trailing user- message (right for the OpenAI-compatible wire, where the prefix through the last tool- result then stays byte-identical). On Anthropic that shape is WORSE: the note folds- into the final user message, and a cache entry made at a block that is followed by- another block in the same message does not match a later request where the message- ends there — measured as 27/27 misses (17.24 USD vs 7.41) on one Terminal-Bench- attempt. Anthropic's own pattern for per-turn reminders keeps them in the transcript,- which is a larger change (OPE-192 follow-up). Until then this provider keeps its- previous shape: the note is glued onto the last user message before it. With a live- clock that is the old minute-crossing miss; with the clock off it is fully cacheable."""- if not messages:- return messages- last = messages[-1]- text = last.get("content")- if last.get("role") != "user" or not (- isinstance(text, str) and text.startswith(_EPHEMERAL_CONTEXT_OPEN)- ):- return messages- out = list(messages[:-1])- for i in range(len(out) - 1, -1, -1):- if out[i].get("role") != "user":- continue- target = dict(out[i])- content = target.get("content")- block = "\n\n" + text- if isinstance(content, str):- target["content"] = content + block- elif isinstance(content, list):- target["content"] = [*content, {"type": "text", "text": block}]- else:- target["content"] = text- out[i] = target- return out- return messages # no user message to glue onto: leave the note where it is--def convert_messages(messages: list[dict[str, Any]],) -> tuple[Optional[str], list[dict[str, Any]]]:@@ -320,7 +283,6 @@ def convert_messages(into one message — this is what collapses a run of `role:"tool"` results (one per parallelcall) into the single user message Anthropic requires, with any steering user text after."""- messages = _relocate_ephemeral_note(messages)system_parts: list[str] = []index = 0while index < len(messages) and messages[index].get("role") == "system":@@ -417,11 +379,6 @@ def convert_tools(tools: Optional[list[dict[str, Any]]]) -> list[dict[str, Any]]return converted-# Mirrors coworker.engine.EPHEMERAL_CONTEXT_OPEN (a string, so this module keeps no-# dependency on the engine).-_EPHEMERAL_CONTEXT_OPEN = "<system-context>"--def _add_cache_breakpoints(kwargs: dict[str, Any]) -> None:"""Opt the request into prompt caching (5-minute ephemeral, prefix-matched).diff --git a/coworker/selfwake.py b/coworker/selfwake.pyindex cf290b3a..d68a6694 100644--- a/coworker/selfwake.py+++ b/coworker/selfwake.py@@ -2,7 +2,8 @@Converts an always-on agent into suspend/resume (event-driven, ~zero idle cost): the sessionsleeps and the runtime re-invokes it when a wake is due. Two triggers here: a **timer**-(`sleep_until`) and **on-completion** (`wake_on` a backgrounded job). This module+(`sleep_for` relative, `sleep_until` absolute) and **on-completion** (`wake_on` a+backgrounded job). This moduleowns the wake records + the due/complete logic; the scheduler tick consumes ``due()`` /``complete_job()`` and resumes the session (shares the automation scheduler — see``PERMISSIONS-AND-INBOX.md``).@@ -155,11 +156,21 @@ class WakeStore:def selfwake_tools(store: WakeStore, session_id: str) -> list:"""Tools an agent calls to schedule its own resumption."""+ def sleep_for(seconds: int, note: str = "") -> dict:+ """Suspend and wake this session after `seconds` (a relative wait: "check again in+ 5 minutes" is sleep_for(300)). Use it for polling/waiting without burning context+ while idle. No clock arithmetic needed — the runtime computes the wake time."""+ secs = int(seconds)+ if secs <= 0:+ raise ValueError("sleep_for needs a positive number of seconds")+ w = store.add_timer(session_id, _now() + timedelta(seconds=secs), note=note)+ return {"ok": True, "wake_id": w.id, "fire_at": w.fire_at}+def sleep_until(when_iso: str, note: str = "") -> dict:"""Suspend and wake this session at an ISO-8601 timestamp (timezone-aware; bare- timestamps are read as UTC). Use it for polling/waiting without burning context- while idle — for a relative wait ("check again in 5 minutes"), compute the- timestamp from the `Now:` line in your context."""+ timestamps are read as UTC) — for an absolute time ("at 09:00 tomorrow"). Call+ `current_time` first if you need today's date or the timezone; for a relative wait+ use sleep_for instead."""when = datetime.fromisoformat(when_iso)if when.tzinfo is None:when = when.replace(tzinfo=timezone.utc)@@ -177,4 +188,4 @@ def selfwake_tools(store: WakeStore, session_id: str) -> list:w = store.add_event(session_id, event_key, note=note)return {"ok": True, "wake_id": w.id, "event_key": event_key}- return [sleep_until, wake_on, wake_on_event]+ return [sleep_for, sleep_until, wake_on, wake_on_event]diff --git a/coworker/server/manager.py b/coworker/server/manager.pyindex cf9b740f..65928eb7 100644--- a/coworker/server/manager.py+++ b/coworker/server/manager.py@@ -2350,7 +2350,7 @@ class SessionManager:delivered += await self._maybe_backstop_lead(team)return delivered- # The lead owns its cadence (sleep_until, stretch-when-quiet); this backstop only+ # The lead owns its cadence (sleep_for, stretch-when-quiet); this backstop only# exists because prompts aren't guarantees. A forgotten timer must never orphan# a running team — and it de-facto covers a worker dying without a transition# (its item goes stale; the backstop wake surfaces it in the digest).@@ -2386,7 +2386,7 @@ class SessionManager:" set.\n\n"+ (self.team_staleness_digest(sid) or "Board state unavailable.")+ "\n\nGlance, act only if something needs you, and set your next"- " check-in with sleep_until (start 3–5 minutes out; stretch when quiet)."+ " check-in with sleep_for (start 3–5 minutes; stretch when quiet).")self._team_inflight.add(sid)@@ -4609,7 +4609,7 @@ class SessionManager:async def resume_due_wakes(self) -> int:"""Resume sessions whose self-wakes are due (called each scheduler tick). A suspended- agent (it called sleep_until / wake_on / wake_on_event and ended its turn) is re-invoked on+ agent (it called sleep_for / sleep_until / wake_on / wake_on_event and ended its turn) is re-invoked onits own session with a wake message so it continues where it left off. Returns the count."""resumed = 0@@ -4894,8 +4894,12 @@ class SessionManager:f"⏰ Wake — the event `{wake.event_key}` you were waiting on has fired{note}. ""Continue where you left off.")+ # The fire time rides along so a woken session knows what time it is without a+ # tool call (the per-turn context carries no clock — OPE-192).+ fired = getattr(wake, "fire_at", None)+ at = f" at {fired}" if fired else ""return (- f"⏰ Wake — the timer you set has fired{note}. Continue where you left off."+ f"⏰ Wake — the timer you set has fired{at}{note}. Continue where you left off.")async def _run_scheduled_task(self, task, trigger: str) -> TaskRun:diff --git a/tests/test_attachments.py b/tests/test_attachments.pyindex d755c340..9b5175e6 100644--- a/tests/test_attachments.py+++ b/tests/test_attachments.py@@ -123,9 +123,9 @@ async def test_image_reaches_provider_unmodified():user_msgs = [m for m in (spy.captured or []) if m.get("role") == "user"]assert user_msgs, "no user message reached the provider"- # The last user message on the wire is the engine's per-turn `<system-context>` note- # (OPE-192: sent as its own trailing message); the attachment rides the one before it.- parts = [m for m in user_msgs if not str(m.get("content", "")).startswith("<system-context>")][-1]["content"]+ # The engine's per-turn `<system-context>` block is glued onto this same message as a+ # trailing text part; the image part before it is untouched.+ parts = user_msgs[-1]["content"]assert isinstance(parts, list)images = [p for p in parts if p.get("type") == "image_url"]assert images and images[0]["image_url"]["url"] == url # byte-for-byte intactdiff --git a/tests/test_cache_breakpoint_placement.py b/tests/test_cache_breakpoint_placement.pyindex 50b8097f..d4971b7c 100644--- a/tests/test_cache_breakpoint_placement.py+++ b/tests/test_cache_breakpoint_placement.py@@ -1,68 +1,69 @@-"""OPE-192, Anthropic side. The engine sends its per-turn `<system-context>` note as a-trailing user message. On the Anthropic wire that shape defeats the prompt cache outright-(a cache entry made mid-message never matches a later request where the message ends-there — 27/27 misses measured), so this provider relocates the note onto the last user-message before it, i.e. exactly its previous shape, and keeps the breakpoint on the last-block of the final message. With `live_clock` off that shape is fully cacheable."""+"""OPE-192, Anthropic side. The engine glues its per-turn `<system-context>` block onto the+last user message (the same shape every provider gets) and this provider puts its cache+breakpoint on the last block of the final message. In a tool loop the final message is+pure tool results, so the breakpoint sits on a block that is identical next turn and the+whole conversation prefix is reused. Nothing is relocated any more: the converter sees+exactly what the engine sends."""from __future__ import annotationsfrom coworker.providers.anthropic_provider import _add_cache_breakpoints, convert_messages-NOTE = "<system-context>\n(automatic per-turn context, not a message from the user)\nNow: 07:04\n</system-context>"+BLOCK = "\n\n<system-context>\n(automatic per-turn context, not part of the user's message)\nAvailable directories: /app\n</system-context>"def _tool_loop():return [- {"role": "user", "content": "task"},+ {"role": "user", "content": "task" + BLOCK},{"role": "assistant", "content": "", "tool_calls": [{"id": "c1", "function": {"name": "run_shell", "arguments": "{}"}}]},{"role": "tool", "tool_call_id": "c1", "content": "out"},]-def test_trailing_note_is_glued_onto_the_last_user_message_in_a_tool_loop():- system, conv = convert_messages(_tool_loop() + [{"role": "user", "content": NOTE}])+def test_tool_loop_breakpoint_sits_on_the_tool_result_not_the_block():+ system, conv = convert_messages(_tool_loop())assert [m["role"] for m in conv] == ["user", "assistant", "user"]- # The task prompt carries the note (previous shape); the final message is pure tool- # results, so the breakpoint sits on a block that is identical next turn.- assert conv[0]["content"][0]["text"] == "task\n\n" + NOTE+ assert conv[0]["content"][0]["text"] == "task" + BLOCK # sent as the engine built itassert [b["type"] for b in conv[-1]["content"]] == ["tool_result"]kw = {"system": system or "s", "messages": conv}_add_cache_breakpoints(kw)assert "cache_control" in kw["messages"][-1]["content"][-1]+ assert "cache_control" not in kw["messages"][0]["content"][0]+++def test_same_history_converts_identically_twice():+ """Byte-stable input, byte-stable request: the converter adds nothing of its own."""+ assert convert_messages(_tool_loop()) == convert_messages(_tool_loop())-def test_trailing_note_is_glued_onto_the_newest_user_text_in_a_chat():+def test_chat_block_stays_on_the_newest_user_message():system, conv = convert_messages([{"role": "user", "content": "draft"},{"role": "assistant", "content": "ok"},- {"role": "user", "content": "shorter"},- {"role": "user", "content": NOTE},+ {"role": "user", "content": "shorter" + BLOCK},])assert [m["role"] for m in conv] == ["user", "assistant", "user"]- assert conv[-1]["content"][0]["text"] == "shorter\n\n" + NOTE+ assert conv[-1]["content"][0]["text"] == "shorter" + BLOCKassert conv[0]["content"][0]["text"] == "draft" # earlier turns untouched+ kw = {"system": system or "s", "messages": conv}+ _add_cache_breakpoints(kw)+ assert "cache_control" in kw["messages"][-1]["content"][-1]-def test_content_parts_get_the_note_as_a_trailing_text_part():+def test_content_parts_keep_the_block_as_the_trailing_text_block():system, conv = convert_messages([- {"role": "user", "content": [{"type": "text", "text": "look"}, {"type": "text", "text": "closely"}]},- {"role": "user", "content": NOTE},+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "look"},+ {"type": "text", "text": "closely"},+ {"type": "text", "text": BLOCK},+ ],+ },])assert len(conv) == 1- assert [b["text"] for b in conv[0]["content"]] == ["look", "closely", "\n\n" + NOTE]---def test_without_a_trailing_note_nothing_moves():- system, conv = convert_messages(_tool_loop())- assert conv[0]["content"][0]["text"] == "task"- assert [b["type"] for b in conv[-1]["content"]] == ["tool_result"]---def test_a_lone_note_with_no_user_message_is_left_alone():- system, conv = convert_messages([{"role": "user", "content": NOTE}])- assert conv[0]["content"][0]["text"] == NOTE+ assert [b["text"] for b in conv[0]["content"]] == ["look", "closely", BLOCK]diff --git a/tests/test_clock_tool.py b/tests/test_clock_tool.pynew file mode 100644index 00000000..60d0ce58--- /dev/null+++ b/tests/test_clock_tool.py@@ -0,0 +1,63 @@+"""OPE-192: the time is a tool (`current_time`), not a line in the per-turn context block.+The block must be byte-identical turn to turn so the provider's prompt cache keeps+working; a value that changes by itself has no place in it."""++from __future__ import annotations++from datetime import datetime, timezone++from coworker.clock import clock_tools, current_time+++def test_current_time_reports_local_and_utc_for_the_same_instant():+ before = datetime.now(timezone.utc)+ out = current_time()+ after = datetime.now(timezone.utc)+ local = datetime.fromisoformat(out["local"])+ utc = datetime.fromisoformat(out["utc"].replace("Z", "+00:00"))+ assert local.tzinfo is not None and utc.tzinfo is not None+ assert local == utc # same instant, two renderings+ assert before.replace(microsecond=0) <= utc <= after+ assert out["weekday"] == local.strftime("%A")+ assert isinstance(out["timezone"], str)+++def test_clock_tools_exposes_exactly_current_time():+ assert [t.__name__ for t in clock_tools()] == ["current_time"]+++def test_current_time_is_registered_for_every_persona(tmp_path, monkeypatch):+ from coworker.agent import build_engine+ from coworker.agents.registry import get_agent+ from coworker.permissions import Mode++ monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path / "state"))+ monkeypatch.setenv("COWORKER_SCRATCH_BASE", str(tmp_path / "scratch"))+ ws = tmp_path / "ws"+ ws.mkdir()+ for persona in ("cowork", "code"):+ engine = build_engine(agent=get_agent(persona), workspace=ws, model="gpt-5.5", mode=Mode("bypass-approvals"))+ assert "current_time" in set(engine.registry.names()), persona+++def test_context_block_carries_no_clock_and_is_byte_stable(tmp_path, monkeypatch):+ from coworker.agent import build_engine+ from coworker.agents.registry import get_agent+ from coworker.permissions import Mode++ monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path / "state"))+ monkeypatch.setenv("COWORKER_SCRATCH_BASE", str(tmp_path / "scratch"))+ ws = tmp_path / "ws"+ ws.mkdir()+ engine = build_engine(agent=get_agent("cowork"), workspace=ws, model="gpt-5.5", mode=Mode("bypass-approvals"))+ first = engine.context_provider()+ assert "Now:" not in first+ assert str(ws) in first # the folders are still there+ assert engine.context_provider() == first # byte-identical turn to turn+++def test_environment_block_points_at_the_tool(tmp_path):+ from coworker.environment import environment_context++ block = environment_context(tmp_path)+ assert "Today's date:" in block and "current_time" in blockdiff --git a/tests/test_context_block_placement.py b/tests/test_context_block_placement.pyindex 8881b4ca..4f1d02d4 100644--- a/tests/test_context_block_placement.py+++ b/tests/test_context_block_placement.py@@ -1,7 +1,9 @@-"""OPE-192: the per-turn `<system-context>` block (live clock, folders, skills) must land on-the NEWEST outbound message. Attaching it to the last *user* message put it on the task-prompt in every tool loop, so each minute crossing changed message one and the provider-could reuse none of its cached prefix. No engine loop here: `_outbound_messages` alone."""+"""OPE-192: the per-turn `<system-context>` block (folders, skill menu, mode notices) rides+on the last user message — one shape for every provider — and must hold nothing that moves+on its own. In a tool loop that message is the task prompt, message one; a provider's+prompt cache is reusable only up to the first byte that differs, so a self-changing value+there (the live clock this block used to carry) re-processed the whole conversation on+every turn. No engine loop here: `_outbound_messages` alone."""from __future__ import annotations@@ -10,14 +12,14 @@ from coworker.permissions import PermissionEnginefrom coworker.tools import ToolRegistry-def _engine(tmp_path, messages, clock):+def _engine(tmp_path, messages, ctx):return TurnEngine(provider=object(),registry=ToolRegistry(),permissions=PermissionEngine(workspace_root=tmp_path),model="x",messages=messages,- context_provider=lambda: f"Now: 2026-09-17 {clock[0]} (UTC)\nAvailable directories: /app",+ context_provider=lambda: ctx[0],)@@ -38,102 +40,78 @@ def _tool_loop(turns=3):return msgs-def test_tool_loop_block_rides_as_trailing_message_not_on_the_task_prompt(tmp_path):- clock = ["07:03"]- eng = _engine(tmp_path, _tool_loop(), clock)+FOLDERS = "Available directories: /app"+++def test_tool_loop_block_rides_on_the_task_prompt_and_nowhere_else(tmp_path):+ eng = _engine(tmp_path, _tool_loop(), [FOLDERS])out = eng._outbound_messages()- # The task prompt is exactly what the user wrote — no clock glued onto message one.- assert out[1]["content"] == "Reconstruct the scene file from this image."- assert "<system-context>" not in out[1]["content"]- # The block is the final message, framed as automatic context.- assert out[-1]["role"] == "user"- assert out[-1]["content"].startswith("<system-context>\n(automatic per-turn context")- assert "Now: 2026-09-17 07:03" in out[-1]["content"]- # Everything the model actually said and ran is untouched and in place before it.- assert out[-2]["role"] == "tool" and out[-2]["content"] == "output 2"- # Ephemeral: the canonical history has no such message.- assert eng.messages[-1]["role"] == "tool"---def test_tool_loop_prefix_is_byte_stable_when_only_the_clock_changes(tmp_path):- """The property that keeps the prompt cache warm: two consecutive turns differ only in- the trailing block, however the clock moves."""- clock = ["07:03"]- eng = _engine(tmp_path, _tool_loop(), clock)- first = eng._outbound_messages()- clock[0] = "07:04" # the minute ticks over between requests- second = eng._outbound_messages()- assert first[:-1] == second[:-1] # identical prefix, byte for byte- assert first[-1] != second[-1] # only the ephemeral tail moved- assert "07:03" in first[-1]["content"] and "07:04" in second[-1]["content"]+ assert len(out) == len(eng.messages) # no extra message+ assert out[1]["content"].startswith("Reconstruct the scene file from this image.\n\n<system-context>\n(automatic per-turn context")+ assert out[1]["content"].endswith(f"\n{FOLDERS}\n</system-context>")+ # Everything the model said and ran is untouched; the final message is the tool result.+ assert out[-1]["role"] == "tool" and out[-1]["content"] == "output 2"+ assert "<system-context>" not in str(out[2:])+ # Ephemeral: the canonical history never carries the block.+ assert eng.messages[1]["content"] == "Reconstruct the scene file from this image."++def test_tool_loop_request_is_byte_identical_turn_to_turn(tmp_path):+ """The property that keeps the prompt cache warm: with nothing self-changing in the+ block, two consecutive requests over the same history are equal, byte for byte."""+ eng = _engine(tmp_path, _tool_loop(), [FOLDERS])+ assert eng._outbound_messages() == eng._outbound_messages()-def test_tool_loop_next_turn_keeps_the_previous_turns_verbatim(tmp_path):- """After the loop appends a reply and a new tool result, the earlier turns still match- what was sent before — the previous trailing block does not linger anywhere."""- clock = ["07:03"]- eng = _engine(tmp_path, _tool_loop(turns=2), clock)++def test_tool_loop_next_turn_keeps_the_previous_request_as_a_prefix(tmp_path):+ eng = _engine(tmp_path, _tool_loop(turns=2), [FOLDERS])before = eng._outbound_messages()eng.messages.append({"role": "assistant", "content": "", "tool_calls": [{"id": "c9", "function": {"name": "run_shell", "arguments": "{}"}}]})eng.messages.append({"role": "tool", "tool_call_id": "c9", "content": "output 9"})- clock[0] = "07:04"after = eng._outbound_messages()- # Everything sent last time, minus its ephemeral tail, is a prefix of this request.- assert after[: len(before) - 1] == before[:-1]- assert after[-1]["content"].startswith("<system-context>")- assert after[-2]["content"] == "output 9"+ assert after[: len(before)] == before # the whole previous request is a prefix+ assert after[-1]["content"] == "output 9"+++def test_a_block_change_touches_only_the_message_it_rides_on(tmp_path):+ """When the user grants a folder or flips a mode the block changes — once, and only+ the message carrying it differs. That is the cost of a user action, not of time."""+ ctx = [FOLDERS]+ eng = _engine(tmp_path, _tool_loop(), ctx)+ first = eng._outbound_messages()+ ctx[0] = FOLDERS + "\nAvailable directories: /data"+ second = eng._outbound_messages()+ assert first[0] == second[0] and first[2:] == second[2:]+ assert first[1] != second[1]-def test_chat_shape_unchanged_block_still_on_the_newest_user_message(tmp_path):- clock = ["07:03"]+def test_chat_block_rides_on_the_newest_user_message(tmp_path):msgs = [{"role": "system", "content": "be helpful"},{"role": "user", "content": "draft an email"},{"role": "assistant", "content": "draft"},{"role": "user", "content": "make it shorter"},]- eng = _engine(tmp_path, msgs, clock)+ eng = _engine(tmp_path, msgs, [FOLDERS])out = eng._outbound_messages()- # In a chat too, the user's newest message is sent exactly as typed and the note- # follows as its own message: a provider then caches through the user's text and- # keeps only the note outside the prefix (the Anthropic converter folds the two into- # one user message on the wire, so the model sees what it always saw).- assert len(out) == len(msgs) + 1- assert out[-2]["content"] == "make it shorter"- assert out[-1]["role"] == "user"- assert out[-1]["content"].startswith("<system-context>\n(automatic per-turn context")- assert "Now: 2026-09-17 07:03" in out[-1]["content"]+ assert len(out) == len(msgs)+ assert out[-1]["content"].startswith("make it shorter\n\n<system-context>")assert out[1]["content"] == "draft an email" # earlier user turns untouched+ assert eng.messages[-1]["content"] == "make it shorter"-def test_chat_prefix_is_byte_stable_when_only_the_clock_changes(tmp_path):- clock = ["07:03"]- msgs = [- {"role": "user", "content": "draft an email"},- {"role": "assistant", "content": "draft"},- {"role": "user", "content": "make it shorter"},- ]- eng = _engine(tmp_path, msgs, clock)- first = eng._outbound_messages()- clock[0] = "07:04"- second = eng._outbound_messages()- assert first[:-1] == second[:-1] and first[-1] != second[-1]---def test_chat_shape_with_content_parts_left_untouched(tmp_path):- clock = ["07:03"]- # Text-only parts: an image part would route through the provider's capability check,- # which is a separate concern from placement.+def test_content_parts_get_the_block_as_a_trailing_text_part(tmp_path):msgs = [{"role": "user", "content": [{"type": "text", "text": "look"}, {"type": "text", "text": "closely"}]},]- eng = _engine(tmp_path, msgs, clock)+ eng = _engine(tmp_path, msgs, [FOLDERS])out = eng._outbound_messages()- assert len(out) == 2- assert out[0]["content"] == msgs[0]["content"] # parts message sent as is- assert out[1]["content"].startswith("<system-context>")+ assert len(out) == 1+ parts = out[0]["content"]+ assert parts[:2] == msgs[0]["content"]+ assert parts[2]["type"] == "text" and parts[2]["text"].startswith("\n\n<system-context>")def test_no_context_means_no_block_anywhere(tmp_path):@@ -146,4 +124,4 @@ def test_no_context_means_no_block_anywhere(tmp_path):context_provider=lambda: "",)out = eng._outbound_messages()- assert out[-1]["role"] == "tool" and "<system-context>" not in str(out)+ assert out == eng.messages and "<system-context>" not in str(out)diff --git a/tests/test_live_clock.py b/tests/test_live_clock.pydeleted file mode 100644index 052d1f27..00000000--- a/tests/test_live_clock.py+++ /dev/null@@ -1,49 +0,0 @@-"""OPE-192: `live_clock` (config.toml / COWORKER_LIVE_CLOCK) controls the per-turn clock-line. On, the block changes every minute; off, it is static so a provider's prompt cache-stays reusable wherever the block lands. Default on: the owner ruling for scheduling stands."""--from __future__ import annotations--from coworker.config import LIVE_CLOCK_ENV, load_config---def test_live_clock_default_config_and_env(tmp_path, monkeypatch):- monkeypatch.delenv(LIVE_CLOCK_ENV, raising=False)- (tmp_path / ".coworker").mkdir()- cfg = load_config(tmp_path, global_path=tmp_path / "no-global.toml")- assert cfg.live_clock is True- (tmp_path / ".coworker" / "config.toml").write_text("live_clock = false\n", encoding="utf-8")- cfg = load_config(tmp_path, global_path=tmp_path / "no-global.toml")- assert cfg.live_clock is False- monkeypatch.setenv(LIVE_CLOCK_ENV, "1")- cfg = load_config(tmp_path, global_path=tmp_path / "no-global.toml")- assert cfg.live_clock is True # env wins- monkeypatch.setenv(LIVE_CLOCK_ENV, "maybe")- try:- load_config(tmp_path, global_path=tmp_path / "no-global.toml")- except ValueError as exc:- assert "live_clock" in str(exc)- else:- raise AssertionError("a non-boolean live_clock must be rejected")---def test_context_block_has_a_clock_only_when_live(tmp_path, monkeypatch):- from coworker.agent import build_engine- from coworker.agents.registry import get_agent- from coworker.permissions import Mode-- monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path / "state"))- monkeypatch.setenv("COWORKER_SCRATCH_BASE", str(tmp_path / "scratch"))- ws = tmp_path / "ws"- ws.mkdir()-- monkeypatch.setenv(LIVE_CLOCK_ENV, "0")- engine = build_engine(agent=get_agent("cowork"), workspace=ws, model="gpt-5.5", mode=Mode("bypass-approvals"))- first = engine.context_provider()- assert "Now:" not in first- assert str(ws) in first # the folders are still there- assert engine.context_provider() == first # byte-identical turn to turn-- monkeypatch.setenv(LIVE_CLOCK_ENV, "1")- engine = build_engine(agent=get_agent("cowork"), workspace=ws, model="gpt-5.5", mode=Mode("bypass-approvals"))- assert engine.context_provider().startswith("Now: ")diff --git a/tests/test_message_source.py b/tests/test_message_source.pyindex cc705123..9b669ca7 100644--- a/tests/test_message_source.py+++ b/tests/test_message_source.py@@ -134,10 +134,7 @@ def test_message_source_persisted_and_stripped(tmp_path):# the provider was called and saw the framed text with NO source / unknown keysassert provider.calls, "provider should have been invoked"- # The last user message on the wire is the engine's per-turn `<system-context>` note- # (OPE-192: sent as its own trailing message); the delivered text is the one before it.- sent_users = [m for m in provider.calls[0] if m.get("role") == "user"]- sent_user = [m for m in sent_users if not str(m.get("content", "")).startswith("<system-context>")][-1]+ sent_user = [m for m in provider.calls[0] if m.get("role") == "user"][-1]assert "source" not in sent_userassert "subscribed" in sent_user["content"] # framed, not raw# NO message handed to ANY provider call carries a source keydiff --git a/tests/test_multiroot.py b/tests/test_multiroot.pyindex 3cefb8dd..85c48d66 100644--- a/tests/test_multiroot.py+++ b/tests/test_multiroot.py@@ -153,11 +153,10 @@ def test_outbound_messages_appends_context_to_last_user_message():out = eng._outbound_messages()# ephemeral: the persisted history is untouchedassert eng.messages[-1]["content"] == "do it"- # OPE-192: the block is its own trailing message — the user's text is sent unchanged,- # and the note sits after it so a provider can cache everything before it.- assert out[-2]["content"] == "do it"+ # the block is glued onto the newest user message, framed as automatic context+ assert len(out) == len(eng.messages)assert out[-1]["role"] == "user"- assert out[-1]["content"].startswith("<system-context>\n(automatic per-turn context")+ assert out[-1]["content"].startswith("do it\n\n<system-context>\n(automatic per-turn context")assert out[-1]["content"].endswith("\nDIRS\n</system-context>")assert out[1]["content"] == "hello"diff --git a/tests/test_self_wake.py b/tests/test_self_wake.pyindex fdaaf405..3106fde0 100644--- a/tests/test_self_wake.py+++ b/tests/test_self_wake.py@@ -54,7 +54,7 @@ def test_event_due_only_after_event_fires(tmp_path):def test_selfwake_tools(tmp_path):store = WakeStore(tmp_path / "wakes.json")- sleep_until, wake_on, wake_on_event = selfwake_tools(store, "s1")+ sleep_for, sleep_until, wake_on, wake_on_event = selfwake_tools(store, "s1")assert wake_on("job-9")["job_id"] == "job-9"assert sleep_until((_now() + timedelta(minutes=5)).isoformat())["fire_at"]diff --git a/tests/test_wake_resume.py b/tests/test_wake_resume.pyindex 39ed3cef..1674d2cf 100644--- a/tests/test_wake_resume.py+++ b/tests/test_wake_resume.py@@ -49,7 +49,7 @@ def test_selfwake_tools_registered_for_knowledge(tmp_path):session_id="s1",)names = set(engine.registry.names())- assert {"sleep_until", "wake_on", "wake_on_event"} <= names+ assert {"sleep_for", "sleep_until", "wake_on", "wake_on_event"} <= namesdef test_selfwake_tools_absent_for_code(tmp_path):