Skip to content
Python

Keep the per-turn context block out of the cached prompt prefix (OPE-192)

Devika Vermac32e4b1274f5
diff --git a/coworker/agent.py b/coworker/agent.py
index 311113cb..b8ad3476 100644
--- a/coworker/agent.py
+++ b/coworker/agent.py
@@ -534,8 +534,13 @@ def build_engine(
# "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.
- now = datetime.now().astimezone()
- parts = [f"Now: {now.strftime('%Y-%m-%d %H:%M')} ({now.tzname()})"]
+ 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/config.py b/coworker/config.py
index ee9c018c..a79d718e 100644
--- a/coworker/config.py
+++ b/coworker/config.py
@@ -66,6 +66,12 @@ 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 = True
allowed_commands: list[str] = field(
default_factory=lambda: list(DEFAULT_ALLOWED_COMMANDS)
)
@@ -118,6 +124,7 @@ _FIELDS = {
"tool_result_max_bytes",
"compaction_cap_tokens",
"compaction_summary_max_tokens",
+ "live_clock",
"allowed_commands",
"auto_allow",
"allowed_domains",
@@ -173,6 +180,7 @@ 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]:
@@ -276,6 +284,13 @@ 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.py
index 13ce8f72..cd8a9c0a 100644
--- a/coworker/engine.py
+++ b/coworker/engine.py
@@ -47,6 +47,10 @@ TRUNCATION_NUDGE = (
# no signature (Anthropic rejects it on replay) and its content is empty or a fragment;
# the transcript keeps the original, the outbound view sends this.
TRUNCATION_STUB = "(reply cut off at the output-token limit before any action)"
+# OPE-192: the per-turn context block is ephemeral and volatile (it carries a clock). It is
+# sent as its own trailing message opening with this tag, so a provider can keep its cache
+# breakpoint on the last STABLE block and leave the note outside the cached prefix.
+EPHEMERAL_CONTEXT_OPEN = "<system-context>"
_REVIEWER_TRIP = 5
_REVIEWER_PAUSED_TEXT = (
@@ -2264,20 +2268,41 @@ class TurnEngine:
) or ""
if not context:
return out
- block = f"\n\n<system-context>\n{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
- break
+ # 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>"
+ ),
+ }
+ )
return out
diff --git a/coworker/providers/anthropic_provider.py b/coworker/providers/anthropic_provider.py
index 6187ccca..7197f5a0 100644
--- a/coworker/providers/anthropic_provider.py
+++ b/coworker/providers/anthropic_provider.py
@@ -22,6 +22,7 @@ from __future__ import annotations
import logging
import json
+import os
import re
from typing import Any, Optional
@@ -95,6 +96,37 @@ _FALLBACK_BETA = "server-side-fallback-2026-06-01"
_FALLBACK_MODEL = "claude-opus-4-8"
+# DIAGNOSTIC INSTRUMENT, off unless COWORKER_CACHE_DIAGNOSTICS=1 in the environment.
+# In one long Fable 5.1 session, one call in six failed to reuse the conversation
+# cache and rewrote the whole prompt at 1.25x input — three quarters of the session's cost.
+# Replaying those exact requests off-container caches perfectly, so the cause is not the
+# content we send and cannot be found from the recorded data. This asks Anthropic directly:
+# each request carries the previous response's id, and the reply names the reason the cache
+# prefix could not be reused. Never enabled in a normal run — it changes the request.
+_CACHE_DIAGNOSTICS_BETA = "cache-diagnosis-2026-04-07"
+
+
+def _outbound_fingerprints(kwargs: dict[str, Any]) -> dict[str, Any]:
+ """Diagnostic only: a short hash per outbound message (plus system and tools), so two
+ consecutive requests can be diffed offline to find the first message that changed."""
+ import hashlib
+
+ def h(obj: Any) -> str:
+ return hashlib.sha1(
+ json.dumps(obj, sort_keys=True, default=str).encode("utf-8")
+ ).hexdigest()[:12]
+
+ return {
+ "system": h(kwargs.get("system")),
+ "tools": h(kwargs.get("tools")),
+ "messages": [h(m) for m in kwargs.get("messages") or []],
+ }
+
+
+def _cache_diagnostics_on() -> bool:
+ return (os.environ.get("COWORKER_CACHE_DIAGNOSTICS") or "").strip() not in ("", "0")
+
+
def _needs_refusal_fallback(model: str) -> bool:
return model.startswith(("claude-fable", "claude-mythos"))
@@ -242,6 +274,43 @@ 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]]]:
@@ -251,6 +320,7 @@ def convert_messages(
into one message — this is what collapses a run of `role:"tool"` results (one per parallel
call) into the single user message Anthropic requires, with any steering user text after.
"""
+ messages = _relocate_ephemeral_note(messages)
system_parts: list[str] = []
index = 0
while index < len(messages) and messages[index].get("role") == "system":
@@ -347,6 +417,11 @@ 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).
@@ -390,7 +465,11 @@ def _effort_record(plan: Optional[EffortPlan], fallback_note: Optional[str]) ->
def _anthropic_extras(
- thinking_blocks: list[dict[str, Any]], stop_reason: Any = None
+ thinking_blocks: list[dict[str, Any]],
+ stop_reason: Any = None,
+ *,
+ cache_diagnostics: Optional[dict[str, Any]] = None,
+ outbound_hashes: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
"""The `_anthropic` sidecar persisted on the assistant message (empty when nothing
to keep): raw thinking blocks, which convert_messages replays verbatim, and the raw
@@ -402,6 +481,12 @@ def _anthropic_extras(
sidecar["blocks"] = thinking_blocks
if stop_reason:
sidecar["stop_reason"] = stop_reason
+ # Diagnostic only: Anthropic's reason for not reusing the prompt cache on this call,
+ # recorded on the message so it can be read back from a finished run.
+ if cache_diagnostics:
+ sidecar["cache_diagnostics"] = cache_diagnostics
+ if outbound_hashes:
+ sidecar["outbound_hashes"] = outbound_hashes
return {"_anthropic": sidecar} if sidecar else {}
@@ -415,6 +500,9 @@ class AnthropicProvider(ProviderClient):
secrets: Any = None,
thinking_budget: Optional[int] = None,
):
+ # Diagnostic only (see _cache_diagnostics_on): the id of the previous response, so
+ # the next request can ask why the cache prefix was not reused.
+ self._last_message_id: Optional[str] = None
# Mirrors OpenAIProvider: the SDK client is built lazily so engines can be assembled
# before any key exists; the key resolves at call time (explicit → env → SecretStore).
# Tests inject a `client` directly. `thinking_budget` (tokens, from the provider
@@ -630,12 +718,29 @@ class AnthropicProvider(ProviderClient):
)
kwargs["stream"] = True
client = self._ensure_client()
+ diagnosing = _cache_diagnostics_on()
+ outbound_hashes = _outbound_fingerprints(kwargs) if diagnosing else None
+
def _open(kw: dict[str, Any]) -> Any:
if _needs_refusal_fallback(model):
+ extra: dict[str, Any] = {}
+ betas = [_FALLBACK_BETA]
+ if diagnosing:
+ betas.append(_CACHE_DIAGNOSTICS_BETA)
+ extra["diagnostics"] = {
+ "previous_message_id": self._last_message_id
+ }
return client.beta.messages.create(
**kw,
- betas=[_FALLBACK_BETA],
+ betas=betas,
fallbacks=[{"model": _FALLBACK_MODEL}],
+ **extra,
+ )
+ if diagnosing:
+ return client.beta.messages.create(
+ **kw,
+ betas=[_CACHE_DIAGNOSTICS_BETA],
+ diagnostics={"previous_message_id": self._last_message_id},
)
return client.messages.create(**kw)
@@ -650,14 +755,23 @@ class AnthropicProvider(ProviderClient):
usage: Optional[TokenUsage] = None
last_message_delta: Any = None
+ cache_diagnostics: Optional[dict[str, Any]] = None
for event in events:
kind = getattr(event, "type", None)
if kind == "message_start":
# Prompt-side counts (input + cache split) ride the opening event.
- usage = (
- _usage_from(getattr(getattr(event, "message", None), "usage", None))
- or usage
- )
+ started = getattr(event, "message", None)
+ usage = _usage_from(getattr(started, "usage", None)) or usage
+ if diagnosing and started is not None:
+ self._last_message_id = getattr(started, "id", None)
+ diag = getattr(started, "diagnostics", None)
+ if diag is not None:
+ try:
+ cache_diagnostics = (
+ diag if isinstance(diag, dict) else diag.model_dump()
+ )
+ except Exception: # noqa: BLE001
+ cache_diagnostics = {"raw": str(diag)}
elif kind == "content_block_start":
block = getattr(event, "content_block", None)
block_kind = getattr(block, "type", None)
@@ -733,7 +847,12 @@ class AnthropicProvider(ProviderClient):
tool_calls=tool_calls,
finish_reason=_STOP_REASON_MAP.get(stop_reason, stop_reason),
reasoning=_reasoning_text(thinking_blocks),
- extras=_anthropic_extras(thinking_blocks, stop_reason),
+ extras=_anthropic_extras(
+ thinking_blocks,
+ stop_reason,
+ cache_diagnostics=cache_diagnostics,
+ outbound_hashes=outbound_hashes,
+ ),
usage=usage,
output_limit=kwargs.get("max_tokens"),
effort=_effort_record(plan, fallback_note),
diff --git a/tests/test_attachments.py b/tests/test_attachments.py
index c931a78a..d755c340 100644
--- a/tests/test_attachments.py
+++ b/tests/test_attachments.py
@@ -123,7 +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"
- parts = user_msgs[-1]["content"]
+ # 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"]
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 intact
diff --git a/tests/test_cache_breakpoint_placement.py b/tests/test_cache_breakpoint_placement.py
new file mode 100644
index 00000000..50b8097f
--- /dev/null
+++ b/tests/test_cache_breakpoint_placement.py
@@ -0,0 +1,68 @@
+"""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."""
+
+from __future__ import annotations
+
+from 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>"
+
+
+def _tool_loop():
+ return [
+ {"role": "user", "content": "task"},
+ {"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}])
+ 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 [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]
+
+
+def test_trailing_note_is_glued_onto_the_newest_user_text_in_a_chat():
+ system, conv = convert_messages(
+ [
+ {"role": "user", "content": "draft"},
+ {"role": "assistant", "content": "ok"},
+ {"role": "user", "content": "shorter"},
+ {"role": "user", "content": NOTE},
+ ]
+ )
+ assert [m["role"] for m in conv] == ["user", "assistant", "user"]
+ assert conv[-1]["content"][0]["text"] == "shorter\n\n" + NOTE
+ assert conv[0]["content"][0]["text"] == "draft" # earlier turns untouched
+
+
+def test_content_parts_get_the_note_as_a_trailing_text_part():
+ system, conv = convert_messages(
+ [
+ {"role": "user", "content": [{"type": "text", "text": "look"}, {"type": "text", "text": "closely"}]},
+ {"role": "user", "content": NOTE},
+ ]
+ )
+ 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
diff --git a/tests/test_context_block_placement.py b/tests/test_context_block_placement.py
new file mode 100644
index 00000000..8881b4ca
--- /dev/null
+++ b/tests/test_context_block_placement.py
@@ -0,0 +1,149 @@
+"""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."""
+
+from __future__ import annotations
+
+from coworker.engine import TurnEngine
+from coworker.permissions import PermissionEngine
+from coworker.tools import ToolRegistry
+
+
+def _engine(tmp_path, messages, clock):
+ 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",
+ )
+
+
+def _tool_loop(turns=3):
+ msgs = [
+ {"role": "system", "content": "be helpful"},
+ {"role": "user", "content": "Reconstruct the scene file from this image."},
+ ]
+ for i in range(turns):
+ msgs.append(
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [{"id": f"c{i}", "function": {"name": "run_shell", "arguments": '{"command": "ls"}'}}],
+ }
+ )
+ msgs.append({"role": "tool", "tool_call_id": f"c{i}", "content": f"output {i}"})
+ 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)
+ 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"]
+
+
+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)
+ 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"
+
+
+def test_chat_shape_unchanged_block_still_on_the_newest_user_message(tmp_path):
+ clock = ["07:03"]
+ 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)
+ 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 out[1]["content"] == "draft an email" # earlier user turns untouched
+
+
+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.
+ msgs = [
+ {"role": "user", "content": [{"type": "text", "text": "look"}, {"type": "text", "text": "closely"}]},
+ ]
+ eng = _engine(tmp_path, msgs, clock)
+ 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>")
+
+
+def test_no_context_means_no_block_anywhere(tmp_path):
+ eng = TurnEngine(
+ provider=object(),
+ registry=ToolRegistry(),
+ permissions=PermissionEngine(workspace_root=tmp_path),
+ model="x",
+ messages=_tool_loop(),
+ context_provider=lambda: "",
+ )
+ out = eng._outbound_messages()
+ assert out[-1]["role"] == "tool" and "<system-context>" not in str(out)
diff --git a/tests/test_live_clock.py b/tests/test_live_clock.py
new file mode 100644
index 00000000..052d1f27
--- /dev/null
+++ b/tests/test_live_clock.py
@@ -0,0 +1,49 @@
+"""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.py
index 9b669ca7..cc705123 100644
--- a/tests/test_message_source.py
+++ b/tests/test_message_source.py
@@ -134,7 +134,10 @@ def test_message_source_persisted_and_stripped(tmp_path):
# the provider was called and saw the framed text with NO source / unknown keys
assert provider.calls, "provider should have been invoked"
- sent_user = [m for m in provider.calls[0] if m.get("role") == "user"][-1]
+ # 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]
assert "source" not in sent_user
assert "subscribed" in sent_user["content"] # framed, not raw
# NO message handed to ANY provider call carries a source key
diff --git a/tests/test_multiroot.py b/tests/test_multiroot.py
index ca2f9ec6..3cefb8dd 100644
--- a/tests/test_multiroot.py
+++ b/tests/test_multiroot.py
@@ -153,8 +153,12 @@ def test_outbound_messages_appends_context_to_last_user_message():
out = eng._outbound_messages()
# ephemeral: the persisted history is untouched
assert eng.messages[-1]["content"] == "do it"
- # only the LAST user message carries the block
- assert out[-1]["content"] == "do it\n\n<system-context>\nDIRS\n</system-context>"
+ # 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"
+ assert out[-1]["role"] == "user"
+ assert out[-1]["content"].startswith("<system-context>\n(automatic per-turn context")
+ assert out[-1]["content"].endswith("\nDIRS\n</system-context>")
assert out[1]["content"] == "hello"