Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(agent-core): context management core (C-9) (#2360)

Call White748d6202e8d4
diff --git a/core/agent_core/agent/README.md b/core/agent_core/agent/README.md
index 7a271ef1b..30e349a47 100644
--- a/core/agent_core/agent/README.md
+++ b/core/agent_core/agent/README.md
@@ -1,7 +1,8 @@
-# Agent loop (P1)
+# Agent loop (P1, C-9 in P3)
-The change contract is C-3 plus C-5 projection steps 1, 2, 5, and 6 from
-`docs/plans/agent-core-contracts/`. Foundation types are unchanged.
+The change contract is C-3 plus C-5 projection from `docs/plans/agent-core-contracts/`,
+and C-9 context management (`context.md`) when the Agent has a `ContextConfig`.
+Foundation types are unchanged.
## Integration
@@ -24,6 +25,23 @@ async for event in agent.run(AgentInput(message_id, rendered_input), turn_id=tur
pending = await agent.take_pending_inputs()
```
+C-9 is on when the adapter passes `context=ContextConfig(host=..., scratch_dir=...)`
+(`harness/context.py`); in v1 such an Agent takes no user hooks (a configuration
+error). Every conversation request then goes through one pipeline: projection,
+`budget()` on that request, the C-9 stage (stop, clear, checkpoint at T, overflow
+ladder), and the provider;
+a stage step that changes the context rebuilds the request. `agent.compact(turn_id=...,
+focus=...)` is `/compact`, refused while a run is active. Without a config nothing
+changes and an overflow ends the run `context_exhausted`. The `ContextHost` renders
+the `<earlier-record>` lookup and the state a checkpoint carries; the store adds
+`append_audit` (non-context audit rows), `append_payloads` (one transaction per C-9
+transition), `append_response(request=...)` (the estimate anchor), and each row's
+`created_at`. The SQLite and adapter stores implement all of it, and
+`tests/test_transcript_store_contract.py` runs the same tests on them and on the
+in-memory store. Every response, a checkpoint turn's included, is admitted in the
+model call before anything acts on it. The ordering and ownership invariants are in
+`context.md` section 10.
+
`steer` and `follow_up` are async and return whether the active run accepted the
input. `False` means the adapter keeps the persisted input in the P3 queue.
An accepted input remains owned by the Agent until consumed or returned by
@@ -44,8 +62,10 @@ input consumption. The run yields a clear error and terminal event without a
provider request. Unknown tool support still sends tools. Unknown/false image
and reasoning support is disabled; reasoning also requires a declared effort.
The configured output budget defaults to 8,192 and is capped by the provider's
-maximum (8,192 when unknown). `ModelSelection.context_window` exposes the C-9
-budget (128,000 when unknown); context management itself remains P3.
+maximum (8,192 when unknown); that cap is C-9's `O`, the request's `max_tokens`.
+The other C-9 limits (`W` is 128,000 when unknown) and the estimate come from
+`harness.context.budget`, evaluated on each final request on the route resolved
+for it.
The shared nullable source capabilities are not changed into guessed values.
Before-model rewrites affect a detached request only, including endpoint headers.
The router's cached selection is never mutated. Tools execute against the
@@ -135,11 +155,17 @@ localize that error rather than deliver a silent success.
budget ends with the original error, including when delay or route resolution
crosses the deadline. Route resolution precedes request admission: expiry is
checked before route validation, projection, rehydration or hooks can run.
- Any streamed event or partial forbids retry. Overflow emits an error and ends
- as `context_exhausted`.
+ Whether to retry is `ProviderError.retryable`, the provider boundary's decision.
+ An attempt that did not become a response row is never context; its usage is
+ one `ModelAttempt` audit row (`context.md` §10, invariant 4). Without a
+ `ContextConfig`, overflow emits an error and ends as `context_exhausted`; with
+ one, an overflow before anything was streamed and with no content in its
+ partial enters the C-9 overflow ladder, which stops as `context.md` §8 (d) says.
- Projection consumes store-resolved ancestry, sorts by sequence, restores hook
- state, and answers orphans with deterministic interrupted text. It has no job
- host or external settler. The caller supplies rebuilt system/state messages.
+ and guard state, applies the latest checkpoint and every context edit, and
+ answers orphans with deterministic interrupted text. It has no job host or
+ external settler. The caller supplies the system prompt and hook-rehydrated
+ messages; a checkpoint's state is in its row.
- Before resume, the adapter calls `agent.recovery.settle_open_calls` under its
Session writer lock. It appends a governed result for each open call: exited
output, a running job handed to Watch, or synthetic interrupted text.
@@ -169,13 +195,20 @@ Valid-then-mutated argument cases cover Done and partial responses, with a
separate loaded-ancestry check. The final-reply table covers empty, whitespace,
thinking-only and visible replies across stop/length/refusal/safety and
pending-input continuation. The primary/cleanup table includes empty_response.
-These are in-memory engine checks; production provider/store/Watch integration
-is a later layer.
+These are in-memory engine checks. The store contract suite runs the same store
+tests, and C-9 across a restart, on the SQLite store too; production provider and
+Watch integration is a later layer.
## Known by design
-- No compaction, context edits, overflow recovery, or provider transport here.
- A P3 row raises `ProjectionError`; it is never silently ignored.
+- No provider transport here. Checkpoint rows are projected from the text and
+ state fixed when they were written; a malformed `context_compaction` or
+ `context_edit` row raises `ProjectionError` and is never silently ignored.
+- An Agent with a `ContextConfig` takes no user hooks in v1 (`Agent(...)`
+ raises a configuration error), so no hook runs in a checkpoint turn: its
+ tool calls take the tool pipeline of `context.md` §10, invariant 2. Its
+ responses and results are never committed, and it emits nothing but the
+ compaction events.
- Store operations remain separate transactions under the queue lock (approved
for v1 by the orchestrator). A crash between a non-final response and input
consumption leaves that input queued for adapter recovery.
diff --git a/core/agent_core/agent/checkpoint.py b/core/agent_core/agent/checkpoint.py
new file mode 100644
index 000000000..2a1392601
--- /dev/null
+++ b/core/agent_core/agent/checkpoint.py
@@ -0,0 +1,106 @@
+"""The checkpoint turn's tool policy (C-9 ``context.md`` sections 6 and 10).
+
+"Dreaming": a checkpoint turn may think with the tools that only look, and
+write only into its own scratch space; anything that acts on the world is
+denied and never executed. The loop's checkpoint tool pipeline asks it once
+per call, after the turn's budget (``open``). Scratch is flat and is reached
+only through the root's directory descriptor, which the policy opens when the
+turn starts (``agent.scratch``): a write or edit is authorized only for a
+single name directly inside the root, and runs relative to that descriptor.
+"""
+
+from __future__ import annotations
+
+import os
+from dataclasses import dataclass
+from types import MappingProxyType
+from typing import Literal, Mapping, Optional
+
+from core.agent_core.agent.scratch import ScratchRoot, valid_name
+from core.agent_core.messages import ToolCallBlock
+from core.agent_core.tools.args import ToolInputError, str_arg
+from core.agent_core.tools.base import ToolResult
+from core.agent_core.tools.edit import prepare_edit_arguments
+from core.agent_core.tools.paths import resolve_to_cwd
+
+Rule = Literal["allow", "scratch"]
+
+#: Tools a checkpoint turn may call; every other tool is denied.
+CHECKPOINT_TOOL_POLICY: Mapping[str, Rule] = MappingProxyType(
+ {
+ "read": "allow",
+ "write": "scratch",
+ "edit": "scratch",
+ # Memory-read tools join here as "allow" once they exist.
+ }
+)
+
+DENIED = (
+ "This is a checkpoint turn: tools that act outside your own scratch space are unavailable. "
+ "Write the checkpoint now."
+)
+BUDGET_USED = "This is a checkpoint turn and its tool budget is used up. Write the checkpoint now."
+
+
+@dataclass(frozen=True)
+class Decision:
+ """The table's answer for one call: a denial text, or allowed (``scratch``: the name in the scratch root)."""
+
+ denial: Optional[str] = None
+ scratch: Optional[str] = None
+
+
+class CheckpointPolicy:
+ """The table for one checkpoint turn; ``open`` is the turn's budget, which the loop closes.
+
+ Opening the policy opens the scratch root; ``close`` releases it when the turn ends.
+ """
+
+ def __init__(
+ self, *, cwd: str, scratch_dir: Optional[str], table: Mapping[str, Rule] = CHECKPOINT_TOOL_POLICY
+ ) -> None:
+ self._cwd = cwd
+ self._table = table
+ self._root = ScratchRoot.open(scratch_dir) if scratch_dir else None
+ # How a call may address the root: the configured path, or the real path it named when it was opened.
+ self._addresses = (
+ {os.path.normpath(os.path.abspath(scratch_dir)), os.path.realpath(scratch_dir)}
+ if self._root is not None
+ else set()
+ )
+ self.open = True
+
+ def decide(self, call: ToolCallBlock) -> Decision:
+ """The table on ``call``'s arguments (the budget is the pipeline's first check, not this)."""
+ rule = self._table.get(call.name)
+ if rule == "allow":
+ return Decision()
+ name = self._scratch_name(call) if rule == "scratch" else None
+ return Decision(scratch=name) if name is not None else Decision(denial=DENIED)
+
+ def run(self, call: ToolCallBlock, name: str) -> ToolResult:
+ """An authorized scratch ``write`` or ``edit``, relative to the root's descriptor."""
+ assert self._root is not None
+ return self._root.write(name, call.arguments) if call.name == "write" else self._root.edit(name, call.arguments)
+
+ def close(self) -> None:
+ if self._root is not None:
+ self._root.close()
+ self._root = None
+
+ def _scratch_name(self, call: ToolCallBlock) -> Optional[str]:
+ """The single file name a call addresses directly inside the scratch root, or None."""
+ if self._root is None:
+ return None
+ try:
+ arguments = prepare_edit_arguments(call.arguments) if call.name == "edit" else call.arguments
+ raw = str_arg(arguments, "path")
+ target = resolve_to_cwd(raw, self._cwd)
+ except (ToolInputError, ValueError):
+ return None
+ name = os.path.basename(target)
+ # Lexical only: nothing is resolved, because the write never goes through this pathname.
+ if os.path.dirname(target) not in self._addresses or not valid_name(name):
+ return None
+ last = raw.replace(os.altsep or os.sep, os.sep).rstrip(os.sep).rsplit(os.sep, 1)[-1]
+ return name if last == name else None
diff --git a/core/agent_core/agent/events.py b/core/agent_core/agent/events.py
index c2b7843ff..1a31c3db4 100644
--- a/core/agent_core/agent/events.py
+++ b/core/agent_core/agent/events.py
@@ -13,6 +13,7 @@ from typing import Literal, Optional, Union
RunEndReason = Literal["completed", "aborted", "error", "ended_by_hook", "context_exhausted"]
CompactionReason = Literal["manual", "threshold", "overflow"]
+CompactionMode = Literal["normal", "rolling", "dropped"]
@dataclass(frozen=True)
@@ -92,6 +93,7 @@ class CompactionFinished:
seq: int
event_id: str
reason: CompactionReason
+ mode: CompactionMode
tokens_before: int
tokens_after_estimate: int
@@ -104,6 +106,40 @@ class CompactionFailed:
error: str
+@dataclass(frozen=True)
+class CompactionSkipped:
+ """A manual compaction found nothing older than the kept tail to summarize (C-9 section 10)."""
+
+ turn_id: str
+ seq: int
+ reason: CompactionReason
+
+
+@dataclass(frozen=True)
+class CompactionPaused:
+ """Auto-compaction paused for the Session (C-9 section 10); emitted once, at the transition."""
+
+ turn_id: str
+ seq: int
+ cause: Literal["failures", "ineffective"]
+
+
+@dataclass(frozen=True)
+class ContextPart:
+ name: Literal["system", "tools", "history", "current_request", "latest_tool_batch", "output"]
+ tokens: int
+
+
+@dataclass(frozen=True)
+class ContextExhausted:
+ """What fills a context the overflow ladder could not make fit (C-9 section 8 d)."""
+
+ turn_id: str
+ seq: int
+ limit: int
+ parts: tuple[ContextPart, ...]
+
+
@dataclass(frozen=True)
class RunEnded:
turn_id: str
@@ -131,6 +167,9 @@ AgentEvent = Union[
CompactionStarted,
CompactionFinished,
CompactionFailed,
+ CompactionSkipped,
+ CompactionPaused,
+ ContextExhausted,
RunEnded,
AgentError,
]
diff --git a/core/agent_core/agent/loop.py b/core/agent_core/agent/loop.py
index eb76310fe..6488597c1 100644
--- a/core/agent_core/agent/loop.py
+++ b/core/agent_core/agent/loop.py
@@ -2,6 +2,9 @@
Queue semantics informed by Pi (MIT), packages/agent/src/agent-loop.ts, and the
bare-loop control experiment. This is an Avibe implementation, not a port.
+With a ``ContextConfig`` the loop also applies C-9 before every model request:
+clearing, the forked checkpoint turn, and the overflow ladder
+(``agent-core-contracts/context.md``).
"""
from __future__ import annotations
@@ -13,14 +16,22 @@ import time
from collections import deque
from contextlib import asynccontextmanager, suppress
from copy import deepcopy
-from dataclasses import replace
-from typing import Any, AsyncIterator, Awaitable, Callable, Mapping, Optional, Sequence, TypeVar
+from dataclasses import dataclass, replace
+from typing import Any, AsyncIterator, Awaitable, Callable, Literal, Mapping, Optional, Sequence, TypeVar
+from core.agent_core.agent.checkpoint import BUDGET_USED, DENIED, CheckpointPolicy, Decision
from core.agent_core.agent.events import (
AgentError,
AgentEvent,
AssistantTextDelta,
AssistantThinkingDelta,
+ CompactionFailed,
+ CompactionFinished,
+ CompactionPaused,
+ CompactionSkipped,
+ CompactionStarted,
+ ContextExhausted,
+ ContextPart,
MessageCommitted,
RunEnded,
RunEndReason,
@@ -44,7 +55,7 @@ from core.agent_core.agent.hooks import (
)
from core.agent_core.agent.jobs import TrackingJobHost
from core.agent_core.agent.lifecycle import RunAborted as _Aborted, RunScope
-from core.agent_core.agent.models import DEFAULT_MAX_OUTPUT_TOKENS, ModelRouter, ModelSelection, RetryPolicy
+from core.agent_core.agent.models import ModelRouter, ModelSelection, RetryPolicy
from core.agent_core.agent.outcome import OutcomeOwner
from core.agent_core.agent.state import HookStateError, state_representation
from core.agent_core.ai.provider import (
@@ -55,10 +66,67 @@ from core.agent_core.ai.provider import (
ThinkingDelta,
)
from core.agent_core.cancel import CancelToken
-from core.agent_core.harness.projection import ProjectionError, project, validate_message_append
-from core.agent_core.harness.store import ContextEntry, TranscriptStore
-from core.agent_core.messages import AssistantMessage, Message, TextBlock, ToolCallBlock, ToolResultMessage, text
+from core.agent_core.harness.context import (
+ CHECKPOINT_TOOL_FLOOR,
+ CHECKPOINT_TOOL_ROUNDS,
+ CHECKPOINT_TOOL_SLACK,
+ CLEAR_SOFT_RATIO,
+ DEFAULT_MAX_OUTPUT_TOKENS,
+ INEFFECTIVE_RATIO,
+ MAX_OVERFLOWS,
+ MAX_ROLLS,
+ PAUSE_AFTER,
+ PROMPT_VERSION,
+ Anchor,
+ Budget,
+ ContextConfig,
+ StateRequest,
+ add_usage,
+ budget,
+ carried_skills,
+ checkpoint_max_tokens,
+ checkpoint_request,
+ checkpoint_text,
+ clear_edit,
+ clearable_results,
+ compaction_payload,
+ fit_result,
+ half_cut,
+ last_anchor,
+ message_tokens,
+ messages_tokens,
+ normal_cut,
+ output_tokens,
+ request_facts,
+ request_tokens,
+ rolling_cut,
+ sent_tokens,
+ summarized_to_seq,
+ text_tokens,
+ unit_tokens,
+)
+from core.agent_core.harness.projection import (
+ ContextView,
+ ProjectionError,
+ context_view,
+ project,
+ validate_message_append,
+)
+from core.agent_core.harness.store import ContextEntry, EntryKind, TranscriptStore
+from core.agent_core.messages import (
+ AssistantMessage,
+ Message,
+ TextBlock,
+ ToolCallBlock,
+ ToolResultMessage,
+ Usage,
+ UserMessage,
+ message_to_dict,
+ text,
+ usage_to_dict,
+)
from core.agent_core.tools.base import JobHost, Tool, ToolContext, ToolResult
+from core.agent_core.tools.paths import to_thread_joined
T = TypeVar("T")
logger = logging.getLogger(__name__)
@@ -76,6 +144,65 @@ class UnsupportedModelRoute(ValueError):
"""The selected model cannot provide the tools required by the agent."""
+class _Exhausted(Exception):
+ """C-9 section 8 (d): the run stops ``context_exhausted``, saying what fills the context."""
+
+ def __init__(self, limit: int, parts: tuple[ContextPart, ...]) -> None:
+ self.limit, self.parts = limit, parts
+ sizes = ", ".join(f"{part.name} ~{part.tokens}" for part in parts)
+ super().__init__(f"The context does not fit the model's input limit of {limit} tokens: {sizes}.")
+
+
+#: C-9 guard state (``AgentState.context``) before anything happened.
+_GUARD_DEFAULT: dict[str, Any] = {"failures": 0, "ineffective": 0, "paused": False}
+#: The checkpoint request without a focus, as the fit checks measure it.
+_CHECKPOINT_REQUEST = checkpoint_request()
+#: The most a checkpoint-turn call that does not run adds: one of the policy's two fixed texts (never cut).
+_FIXED_RESULT_TOKENS = max(text_tokens(DENIED), text_tokens(BUDGET_USED))
+
+
+async def _silent(*_: Any, **__: Any) -> None:
+ """The checkpoint turn's emit: it shows nothing (C-9 section 6)."""
+
+
+@dataclass
+class _Ladder:
+ """One model request's progress through C-9 sections 3 and 8."""
+
+ compacted: bool = False
+ summary_failed: bool = False
+ rolls: int = 0
+ overflows: int = 0
+ #: The provider refused the request as overflow: the next stage takes a ladder step whatever it measures.
+ refused: bool = False
+
+
+@dataclass
+class _Attempt:
+ """One model attempt of the run: the C-9 attempt ledger's entry (context.md section 10).
+
+ ``message`` is the response, or the partial a failed attempt carried. ``committed``: it became a response
+ row; ``audited``: its usage went to a ``ModelAttempt`` audit row (context.md section 10, invariant 4).
+ """
+
+ purpose: Literal["conversation", "checkpoint"]
+ request: ModelRequest
+ message: Optional[AssistantMessage]
+ error: Optional[ProviderError] = None
+ committed: bool = False
+ audited: bool = False
+
+
+@dataclass(frozen=True)
+class _Outcome:
+ ok: bool
+ overflow: bool = False
+
+
+class _ForkTooLarge(Exception):
+ """A checkpoint request that cannot fit the window; it is never sent."""
+
+
class Agent:
"""One Session's single writer. All methods run on the same asyncio loop.
@@ -101,6 +228,7 @@ class Agent:
reasoning_effort: Optional[str] = None,
retry: RetryPolicy = RetryPolicy(),
rehydrate: Optional[Callable[[Mapping[str, Any]], Sequence[Message]]] = None,
+ context: Optional[ContextConfig] = None,
) -> None:
self.session_id = session_id
self.models = models
@@ -114,6 +242,10 @@ class Agent:
self.max_tokens, self.reasoning_effort = max_tokens, reasoning_effort
self.retry = retry
self.rehydrate = rehydrate
+ if context is not None and self.hooks:
+ # Hooks with context management are a post-v1 design item (plan section 10).
+ raise ValueError("ContextConfig and user hooks are mutually exclusive in v1")
+ self.context = context
self._tools: dict[str, Tool] = {}
self._run_tools: Optional[dict[str, Tool]] = None
self.set_tools(tools)
@@ -129,6 +261,11 @@ class Agent:
self._rows: list[ContextEntry] = []
self._committed_state: dict[str, Any] = {}
self._committed_state_json = "{}"
+ self._guard: dict[str, Any] = dict(_GUARD_DEFAULT)
+ self._committed_guard: dict[str, Any] = dict(_GUARD_DEFAULT)
+ # The run's attempt ledger (C-9): every model attempt, in order.
+ self._attempts: list[_Attempt] = []
+ self._last_model_at: Optional[float] = None
self._seq = 0
def set_tools(self, tools: Sequence[Tool]) -> None:
@@ -180,13 +317,31 @@ class Agent:
seq = self._rows[-1].context_seq if self._rows else 0
return Snapshot(self.session_id, seq, deepcopy(self._committed_state))
- async def run(self, input: AgentInput, *, turn_id: str) -> AsyncIterator[AgentEvent]:
+ def run(self, input: AgentInput, *, turn_id: str) -> AsyncIterator[AgentEvent]:
+ input = deepcopy(input)
+ return self._pump(turn_id, lambda emit: self._drive(emit, input=input), admit=True)
+
+ def compact(self, *, turn_id: str, focus: Optional[str] = None) -> AsyncIterator[AgentEvent]:
+ """Manual ``/compact [focus]`` (C-9 section 10): clear the pause, then write a normal checkpoint.
+
+ Runs like a run without an input: it refuses while a run (or another
+ compaction) is active, admits no steer, and ends ``completed`` when the
+ checkpoint was written.
+ """
+ if self.context is None:
+ raise RuntimeError("context management is not configured for this Agent")
+ return self._pump(turn_id, lambda emit: self._drive(emit, focus=focus), admit=False)
+
+ async def _pump(
+ self, turn_id: str, drive: Callable[[Callable[..., Awaitable[None]]], Awaitable[None]], *, admit: bool
+ ) -> AsyncIterator[AgentEvent]:
async with self._lock:
if self._running:
raise RuntimeError("this Agent already has an active run")
if self._steers or self._follow_ups:
raise RuntimeError("return unconsumed inputs with take_pending_inputs() before starting another run")
- self._running = self._open = True
+ self._running = True
+ self._open = admit
self._consumer_closed = False
self._ctx = RunContext(self.session_id, turn_id, CancelToken())
self._scope = RunScope(self._ctx.cancel)
@@ -204,7 +359,7 @@ class Agent:
self._seq += 1
await events.put(event)
- worker = asyncio.create_task(self._drive(deepcopy(input), emit))
+ worker = asyncio.create_task(drive(emit))
receive: Optional[asyncio.Task] = None
try:
while True:
@@ -244,6 +399,7 @@ class Agent:
self._run_tools = None
async def _save_state(self, *, cleanup: bool = False) -> None:
+ """Hook state at a commit point. C-9 guard state is written only by ``_commit_context``."""
representation = state_representation(self._ctx.state)
if representation == self._committed_state_json:
return
@@ -273,23 +429,48 @@ class Agent:
)
self._rows.append(row)
- def _validate_response(self, message: AssistantMessage) -> None:
+ def _validate_response(self, message: AssistantMessage, *, after: Sequence[Message] = ()) -> None:
+ """A response is valid after the committed rows and then ``after`` (a checkpoint turn's own messages)."""
+ entries = list(self._rows)
+ seq = max((entry.context_seq for entry in entries), default=0)
+ for item in after:
+ seq += 1
+ kind: EntryKind = (
+ "input"
+ if isinstance(item, UserMessage)
+ else "response"
+ if isinstance(item, AssistantMessage)
+ else "tool_result"
+ )
+ entries.append(ContextEntry(self.session_id, seq, kind, f"uncommitted-{seq}", item))
try:
- validate_message_append(self._rows, session_id=self.session_id, kind="response", message=message)
+ validate_message_append(entries, session_id=self.session_id, kind="response", message=message)
except ProjectionError as error:
raise ProviderProtocolViolation(f"Provider protocol violation: {error}") from error
async def _response(self, message: AssistantMessage, *, final: bool) -> ContextEntry:
self._validate_response(message)
await self._save_state()
+ # The attempt this response answered: the ledger's latest conversation attempt (the C-9 anchor).
+ attempt = next((item for item in reversed(self._attempts) if item.purpose == "conversation"), None)
+ facts = {"request": request_facts(attempt.request)} if self.context is not None and attempt else {}
row = await self._scope.call(
- lambda: self.store.append_response(self.session_id, deepcopy(message), final=final),
+ lambda: self.store.append_response(self.session_id, deepcopy(message), final=final, **facts),
interruptible=False,
)
+ if attempt is not None:
+ attempt.committed = True
self._rows.append(row)
return row
- async def _drive(self, input: AgentInput, emit: Callable[..., Awaitable[None]]) -> None:
+ async def _drive(
+ self,
+ emit: Callable[..., Awaitable[None]],
+ *,
+ input: Optional[AgentInput] = None,
+ focus: Optional[str] = None,
+ ) -> None:
+ """One run of ``input``, or, without one, a manual compaction with ``focus``."""
loaded = False
try:
try:
@@ -303,23 +484,33 @@ class Agent:
self._ctx.state = deepcopy(dict(projection.state))
self._committed_state_json = state_representation(self._ctx.state)
self._committed_state = deepcopy(self._ctx.state)
+ self._guard = {**_GUARD_DEFAULT, **deepcopy(dict(projection.context_state))}
+ self._committed_guard = dict(self._guard)
+ self._attempts = []
loaded = True
system = self.system
self._run_tools = dict(self._tools)
- for hook in self.hooks:
- setup = await self._hook(lambda: hook.before_run(deepcopy(input), self._ctx))
- if setup is not None:
- if setup.system is not None:
- system = setup.system
- if setup.tools is not None:
- names = [tool.spec.name for tool in setup.tools]
- if len(names) != len(set(names)):
- raise ValueError("tool names must be unique")
- self._run_tools = dict(zip(names, setup.tools))
- await self._consume(input)
- self._outcome.primary(await self._loop(system, emit, selected))
+ if input is None:
+ self._outcome.primary(await self._manual_compaction(system, selected, focus, emit))
+ else:
+ for hook in self.hooks:
+ setup = await self._hook(lambda: hook.before_run(deepcopy(input), self._ctx))
+ if setup is not None:
+ if setup.system is not None:
+ system = setup.system
+ if setup.tools is not None:
+ names = [tool.spec.name for tool in setup.tools]
+ if len(names) != len(set(names)):
+ raise ValueError("tool names must be unique")
+ self._run_tools = dict(zip(names, setup.tools))
+ await self._consume(input)
+ self._outcome.primary(await self._loop(system, emit, selected))
except _Ended:
self._outcome.primary("ended_by_hook")
+ except _Exhausted as error:
+ self._outcome.primary("context_exhausted")
+ await emit(ContextExhausted, limit=error.limit, parts=error.parts)
+ await emit(AgentError, kind="context_exhausted", message=str(error))
except _Aborted:
self._outcome.primary("aborted")
except asyncio.CancelledError:
@@ -339,7 +530,7 @@ class Agent:
self._scope.stop()
# Cleanup is a separate joined task, outside cancelled admission.
# Consumer closure cannot interrupt commit/job ownership release.
- cleanup = asyncio.create_task(self._finish(loaded, emit))
+ cleanup = asyncio.create_task(self._finish(loaded, emit, run_hooks=input is not None))
try:
await asyncio.shield(cleanup)
except asyncio.CancelledError:
@@ -367,7 +558,7 @@ class Agent:
)
self._outcome.diagnostic(kind, f"Cleanup failed: {type(error).__name__}: {error}")
- async def _finish(self, loaded: bool, emit: Callable[..., Awaitable[None]]) -> None:
+ async def _finish(self, loaded: bool, emit: Callable[..., Awaitable[None]], *, run_hooks: bool) -> None:
async with self._lock:
self._open = False
await self._scope.close()
@@ -375,10 +566,13 @@ class Agent:
try:
if loaded:
await self._cleanup(lambda: self._save_state(cleanup=True))
- outcome = RunOutcome(self._ctx.turn_id, self._outcome.reason, self.snapshot())
- for hook in self.hooks:
- await self._cleanup(lambda: self._hook(lambda: hook.after_run(outcome, self._ctx), cleanup=True))
- await self._cleanup(lambda: self._save_state(cleanup=True))
+ if run_hooks:
+ outcome = RunOutcome(self._ctx.turn_id, self._outcome.reason, self.snapshot())
+ for hook in self.hooks:
+ await self._cleanup(
+ lambda: self._hook(lambda: hook.after_run(outcome, self._ctx), cleanup=True)
+ )
+ await self._cleanup(lambda: self._save_state(cleanup=True))
finally:
# Sweep on every terminal path, including failed tool cleanup and
# cleanup hooks. Handed-over handles are no longer foreground.
@@ -397,21 +591,48 @@ class Agent:
if selected.capabilities.supports_tools is False:
raise UnsupportedModelRoute("The selected model does not support tools; the agent requires tool support.")
- async def _request(self, system: str, selected: ModelSelection) -> tuple[ModelRequest, dict[str, Tool]]:
+ def _rehydrated(self) -> tuple[Message, ...]:
+ return tuple(self.rehydrate(deepcopy(self._ctx.state))) if self.rehydrate else ()
+
+ async def _request(
+ self,
+ system: str,
+ selected: ModelSelection,
+ *,
+ messages: Sequence[Message],
+ max_tokens: Optional[int] = None,
+ ) -> tuple[ModelRequest, dict[str, Tool]]:
+ """A request carrying ``messages``, after the user's ``before_model`` hooks: the first pipeline stage."""
+ request, tools = self._built(system, selected, messages=messages, max_tokens=max_tokens)
+ for hook in self.hooks:
+ decision = await self._hook(lambda: hook.before_model(request, self._ctx))
+ if isinstance(decision, End):
+ await self._save_state()
+ raise _Ended()
+ if decision is not None:
+ request = decision
+ allowed = {spec.name for spec in request.tools}
+ return request, {name: tool for name, tool in tools.items() if name in allowed}
+
+ def _built(
+ self,
+ system: str,
+ selected: ModelSelection,
+ *,
+ messages: Sequence[Message],
+ max_tokens: Optional[int] = None,
+ ) -> tuple[ModelRequest, dict[str, Tool]]:
+ """The request carrying ``messages`` on ``selected``, before any hook. C-9 composes its forks and the stop
+ check's minimal request from this alone, which holds because v1 takes no user hooks with a ContextConfig."""
self._check_model_route(selected)
capabilities = selected.capabilities
tools = dict(self._run_tools if self._run_tools is not None else self._tools)
- context = project(
- self._rows,
- system=system,
- rehydrated=self.rehydrate(deepcopy(self._ctx.state)) if self.rehydrate else (),
- )
request = ModelRequest(
endpoint=deepcopy(selected.endpoint),
- system=context.system,
- messages=context.messages,
+ system=system,
+ messages=tuple(deepcopy(messages)),
tools=tuple(deepcopy(tool.spec) for tool in tools.values()),
- max_tokens=min(self.max_tokens, selected.max_output_tokens),
+ max_tokens=output_tokens(capabilities, self.max_tokens) if max_tokens is None else max_tokens,
reasoning_effort=(
self.reasoning_effort
if capabilities.supports_reasoning is True and self.reasoning_effort in capabilities.reasoning_efforts
@@ -419,91 +640,175 @@ class Agent:
),
supports_images=capabilities.supports_images is True,
)
- for hook in self.hooks:
- decision = await self._hook(lambda: hook.before_model(request, self._ctx))
- if isinstance(decision, End):
- await self._save_state()
- raise _Ended()
- if decision is not None:
- request = decision
- allowed = {spec.name for spec in request.tools}
- return request, {name: tool for name, tool in tools.items() if name in allowed}
+ return request, tools
@asynccontextmanager
async def _model(
- self, system: str, emit: Callable[..., Awaitable[None]], selected: Optional[ModelSelection] = None
+ self,
+ system: str,
+ emit: Callable[..., Awaitable[None]],
+ selected: Optional[ModelSelection] = None,
+ *,
+ compose: Optional[Callable[[ModelSelection], Awaitable[tuple[ModelRequest, dict[str, Tool]]]]] = None,
+ purpose: Literal["conversation", "checkpoint"] = "conversation",
+ after: Sequence[Message] = (),
) -> AsyncIterator[tuple[Done | ProviderError, dict[str, Tool]]]:
- retries = 0
- started = time.monotonic()
- retry_error: Optional[ProviderError] = None
- while True:
- self._scope.check()
- if retry_error is not None and time.monotonic() - started >= self.retry.max_elapsed_s:
- yield retry_error, {}
- return
- if selected is None:
- selected = await self._scope.call(self.models.resolve)
- # Resolution is the last async stage before request admission.
- # Expiry wins before route validation, projection, rehydration or
- # hooks can replace the original error or persist new side effects.
- if retry_error is not None and time.monotonic() - started >= self.retry.max_elapsed_s:
- yield retry_error, {}
- return
- request, tools = await self._request(system, selected)
- selected = None
- if retry_error is not None and time.monotonic() - started >= self.retry.max_elapsed_s:
- yield retry_error, tools
- return
- self._scope.check()
- stream = self.models.provider_for(request.endpoint.protocol).stream(request, self._ctx.cancel)
- streamed = False
- terminal = None
- try:
- while True:
- try:
- event = await self._scope.call(lambda: anext(stream))
- except StopAsyncIteration:
- break
- if isinstance(event, (Done, ProviderError)):
- terminal = event
- break
- streamed = True
- if isinstance(event, TextDelta):
- await emit(AssistantTextDelta, delta=event.delta)
- elif isinstance(event, ThinkingDelta):
- await emit(AssistantThinkingDelta, delta=event.delta)
- if terminal is None:
- terminal = ProviderError("unknown", "Provider stream ended without a terminal event.", False)
- delay = (
- self.retry.delay(terminal, retries=retries, streamed=streamed, elapsed_s=time.monotonic() - started)
- if isinstance(terminal, ProviderError)
- else None
- )
- if delay is None:
- # The caller admits and commits this terminal inside the
- # scope, BEFORE aclose. Never retry an accepted terminal.
- yield terminal, tools
+ """One model request with its transient retries.
+
+ ``compose(selection)`` is the request pipeline: it returns the final request, which is sent unchanged.
+ A conversation request's pipeline is ``_compose``. Every attempt enters the run's attempt ledger. A
+ conversation request the provider rejects as overflow goes back through the pipeline with the ladder
+ told to shrink (C-9 section 8). A checkpoint attempt is never context.
+
+ Admission is here, for every purpose: the response the caller receives (or a partial with content) is
+ valid after the committed rows and ``after``, the messages the request carried beyond them (a checkpoint
+ turn's request and its own turn), or ``ProviderProtocolViolation`` is raised before anyone acts on it.
+ """
+ ladder = _Ladder()
+ if compose is None:
+
+ async def compose(selection: ModelSelection) -> tuple[ModelRequest, dict[str, Tool]]:
+ return await self._compose(system, selection, emit, ladder)
+
+ first = len(self._attempts)
+ failure: Optional[BaseException] = None
+ aborted = False
+ try:
+ retries = 0
+ started = time.monotonic()
+ retry_error: Optional[ProviderError] = None
+ while True:
+ self._scope.check()
+ if retry_error is not None and time.monotonic() - started >= self.retry.max_elapsed_s:
+ yield retry_error, {}
return
- finally:
- close = getattr(stream, "aclose", None)
- if close is not None:
- await self._cleanup(close, stream=True)
- if terminal.partial is not None and terminal.partial.usage is not None and not terminal.partial.content:
- row = await self._response(terminal.partial, final=False)
- if not self._consumer_closed:
- await emit(
- MessageCommitted,
- message_id=row.row_id,
- context_seq=row.context_seq,
- final=False,
+ if selected is None:
+ selected = await self._scope.call(self.models.resolve)
+ # Resolution is the last async stage before request admission.
+ # Expiry wins before route validation, projection, rehydration or
+ # hooks can replace the original error or persist new side effects.
+ if retry_error is not None and time.monotonic() - started >= self.retry.max_elapsed_s:
+ yield retry_error, {}
+ return
+ route = selected
+ request, tools = await compose(selected)
+ selected = None
+ if retry_error is not None and time.monotonic() - started >= self.retry.max_elapsed_s:
+ yield retry_error, tools
+ return
+ self._scope.check()
+ stream = self.models.provider_for(request.endpoint.protocol).stream(request, self._ctx.cancel)
+ streamed = False
+ terminal = None
+ relieve = False
+ try:
+ while True:
+ try:
+ event = await self._scope.call(lambda: anext(stream))
+ except StopAsyncIteration:
+ break
+ if isinstance(event, (Done, ProviderError)):
+ terminal = event
+ break
+ streamed = True
+ if isinstance(event, TextDelta):
+ await emit(AssistantTextDelta, delta=event.delta)
+ elif isinstance(event, ThinkingDelta):
+ await emit(AssistantThinkingDelta, delta=event.delta)
+ if self.context is not None:
+ self._last_model_at = self.context.clock()
+ if terminal is None:
+ terminal = ProviderError("unknown", "Provider stream ended without a terminal event.", False)
+ self._attempts.append(
+ _Attempt(
+ purpose,
+ request,
+ terminal.message if isinstance(terminal, Done) else terminal.partial,
+ None if isinstance(terminal, Done) else terminal,
+ )
)
- # This attempt has already been durably announced. Keep the
- # retry decision, but do not carry the same partial through a
- # later expiry path where _loop would commit it again.
+ relieve = (
+ purpose == "conversation"
+ and self.context is not None
+ and isinstance(terminal, ProviderError)
+ and terminal.kind == "overflow"
+ # Only an overflow before any output: once something was streamed, the user saw it.
+ and not streamed
+ and (terminal.partial is None or not terminal.partial.content)
+ )
+ delay = (
+ self.retry.delay(terminal, retries=retries, streamed=streamed, elapsed_s=time.monotonic() - started)
+ if isinstance(terminal, ProviderError) and not relieve
+ else None
+ )
+ if delay is None and not relieve:
+ # Admitted here; the caller commits it inside the scope,
+ # BEFORE aclose. Never retry an accepted terminal.
+ admitted = terminal.message if isinstance(terminal, Done) else terminal.partial
+ if isinstance(terminal, Done) or (admitted is not None and admitted.content):
+ self._validate_response(admitted, after=after)
+ yield terminal, tools
+ return
+ finally:
+ close = getattr(stream, "aclose", None)
+ if close is not None:
+ await self._cleanup(close, stream=True)
+ # The attempt is not the run's answer and is never context (invariant 4): it stays in the ledger and
+ # the audit. A retried request goes out again unchanged; one refused as overflow is rebuilt after a
+ # ladder step (section 8).
+ await self._settle_attempts(first)
terminal = replace(terminal, partial=None)
- retry_error = terminal
- retries += 1
- await self._scope.call(lambda: asyncio.sleep(delay))
+ if relieve:
+ ladder.overflows += 1
+ ladder.refused = True
+ if ladder.overflows >= MAX_OVERFLOWS:
+ view = context_view(self._rows)
+ plan = budget(
+ request, route.capabilities, transcript=view.messages, anchor=last_anchor(self._rows, view)
+ )
+ raise self._exhausted(request, view, plan)
+ retries, started, retry_error = 0, time.monotonic(), None
+ continue
+ retry_error = terminal
+ retries += 1
+ await self._scope.call(lambda: asyncio.sleep(delay))
+ except (_Aborted, asyncio.CancelledError, GeneratorExit):
+ aborted = True # the cancelled run scope admits no further store write
+ raise
+ except BaseException as error:
+ failure = error
+ raise
+ finally:
+ if not aborted:
+ # Invariant 4: the ledger, not each exit path, keeps the usage of attempts that did not become a
+ # response row: a retry, a relief, a usage-only terminal, a refusal at admission, a failed commit.
+ try:
+ await self._settle_attempts(first, error=failure)
+ except _Aborted:
+ if failure is None:
+ raise
+
+ async def _settle_attempts(self, first: int, *, error: Optional[BaseException] = None) -> None:
+ """Every conversation attempt since ``first`` that reported usage and did not become a response row:
+ exactly one non-context ``ModelAttempt`` audit row, in every mode, with or without ``ContextConfig``.
+
+ It is the one place that usage is kept. ``error`` is why the model call ended, for an attempt that
+ carries no provider error of its own (a response refused at admission, a failed commit).
+ """
+ for attempt in self._attempts[first:]:
+ message = attempt.message
+ if attempt.purpose != "conversation" or attempt.committed or attempt.audited:
+ continue
+ if message is None or message.usage is None:
+ continue
+ attempt.audited = True
+ cause = attempt.error
+ payload: dict[str, Any] = {
+ "version": 1,
+ "usage": usage_to_dict(message.usage),
+ "error": f"{cause.kind}: {cause.message}" if cause is not None else str(error) if error else None,
+ }
+ await self._audit("attempt", payload)
async def _commit_model_message(self, message: AssistantMessage, emit: Callable[..., Awaitable[None]]) -> bool:
"""Finality and queued-input admission share one lock with the commit."""
@@ -540,8 +845,9 @@ class Agent:
async with self._model(system, emit, first_selection) as (terminal, tools):
first_selection = None
if isinstance(terminal, ProviderError):
- if terminal.partial is not None:
- self._validate_response(terminal.partial)
+ if terminal.partial is not None and not terminal.partial.content:
+ # A usage-only partial is attempt data, never context; the ledger audits it.
+ terminal = replace(terminal, partial=None)
reason = (
"context_exhausted"
if terminal.kind == "overflow"
@@ -556,7 +862,6 @@ class Agent:
await emit(MessageCommitted, message_id=row.row_id, context_seq=row.context_seq, final=False)
return reason
message = terminal.message
- self._validate_response(message)
failed = message.stop_reason in {"error", "aborted"}
if not (message.tool_calls and message.stop_reason == "length"):
length_tool_retries = 0
@@ -668,6 +973,20 @@ class Agent:
for item in applied:
await emit(SteerApplied, message_id=item.message_id)
+ async def _gate(
+ self, call: ToolCallBlock, hooks: Sequence[Hooks]
+ ) -> tuple[ToolCallBlock, Optional[ToolResult], bool]:
+ """``before_tool``: the call as altered, the result when a hook denied or ended it, and whether one ended."""
+ for hook in hooks:
+ decision = await self._hook(lambda: hook.before_tool(call, self._ctx))
+ if isinstance(decision, Deny):
+ return call, ToolResult((text(decision.reason),), is_error=True), False
+ if isinstance(decision, End):
+ return call, ToolResult((text("[skipped by policy]"),), is_error=True), True
+ if isinstance(decision, AlterArgs):
+ call = replace(call, arguments=deepcopy(decision.arguments))
+ return call, None, False
+
async def _tool(
self,
original: ToolCallBlock,
@@ -683,17 +1002,7 @@ class Agent:
if skip:
result = ToolResult((text(skip_reason or "[skipped by policy]"),), is_error=True)
else:
- for hook in self.hooks:
- decision = await self._hook(lambda: hook.before_tool(call, self._ctx))
- if isinstance(decision, Deny):
- result = ToolResult((text(decision.reason),), is_error=True)
- break
- if isinstance(decision, End):
- result = ToolResult((text("[skipped by policy]"),), is_error=True)
- end = True
- break
- if isinstance(decision, AlterArgs):
- call = replace(call, arguments=deepcopy(decision.arguments))
+ call, result, end = await self._gate(call, self.hooks)
await emit(
ToolStarted,
tool_call_id=call.id,
@@ -780,3 +1089,572 @@ class Agent:
await self._cleanup(
lambda: self.jobs.kill_foreground(self.session_id, tool_call_id=call.id, reason=release_reason)
)
+
+ # --- C-9 context management (agent-core-contracts/context.md) ---------------
+ #
+ # The ordering and ownership invariants are context.md section 10 (1-6), the one statement of them. Their
+ # owners here: ``_compose``, ``_fork``, and ``_minimal`` (1, requests composed and budgeted; ``_compaction`` is
+ # the one builder of checkpoint rows), ``_checkpoint_tool`` (2), ``_commit_context`` (3), ``self._attempts``
+ # with ``_settle_attempts`` and ``_checkpoint``'s one audit (4), ``harness.context.budget`` (5), and ``_model``
+ # (6, admission).
+
+ def _cache_cold(self) -> bool:
+ """No model request for longer than the provider cache TTL (section 3)."""
+ last = self._last_model_at
+ for row in reversed(self._rows):
+ if row.kind == "response" and row.created_at is not None:
+ last = row.created_at if last is None else max(last, row.created_at)
+ break
+ return last is not None and self.context.clock() - last > self.context.cache_ttl_s
+
+ async def _compose(
+ self, system: str, selected: ModelSelection, emit: Callable[..., Awaitable[None]], ladder: _Ladder
+ ) -> tuple[ModelRequest, dict[str, Tool]]:
+ """The conversation request pipeline (invariant 1)."""
+ while True:
+ view = context_view(self._rows)
+ request, tools = await self._request(system, selected, messages=self._carried(view))
+ if self.context is None:
+ return request, tools
+ plan = budget(request, selected.capabilities, transcript=view.messages, anchor=last_anchor(self._rows, view))
+ if not await self._stage(system, selected, request, view, plan, emit, ladder):
+ return request, tools
+
+ async def _stage(
+ self,
+ system: str,
+ selected: ModelSelection,
+ request: ModelRequest,
+ view: ContextView,
+ plan: Budget,
+ emit: Callable[..., Awaitable[None]],
+ ladder: _Ladder,
+ ) -> bool:
+ """C-9 on the final request (sections 3 and 8); True when it changed the context."""
+ if not plan.can_fit and not (await self._minimal(system, selected, request, view, plan))[1].can_fit:
+ # (d): not even the request the drop would leave (its row and the last unit) can fit. The provider
+ # never sees it.
+ raise self._exhausted(request, view, plan)
+ shrink, ladder.refused = ladder.refused, False
+ if not shrink:
+ if self.context.clear_tool_results and (
+ plan.est >= CLEAR_SOFT_RATIO * plan.threshold or self._cache_cold()
+ ):
+ targets = clearable_results(view)
+ if targets:
+ await self._commit_context([("context_edit", clear_edit(target)) for target in targets], self._guard)
+ return True
+ if plan.est >= plan.threshold and not ladder.compacted and not self._guard["paused"]:
+ cut = normal_cut(view.units, plan.keep)
+ if cut is not None:
+ ladder.compacted = True
+ if not self._fork_fits(system, selected, view, "normal", cut):
+ shrink = True # no fork can take the whole context: the ladder from (b)
+ else:
+ outcome = await self._checkpoint(
+ system, selected, request, view, plan, cut, mode="normal", reason="threshold", emit=emit
+ )
+ if outcome.ok:
+ return True
+ # A checkpoint request that overflowed means the whole context cannot fit a fork (b).
+ shrink, ladder.summary_failed = outcome.overflow, not outcome.overflow
+ if not shrink and plan.fits:
+ return False
+ # With no checkpoint request left to try, a request that can fit at all is sent; the provider judges.
+ if not shrink and (ladder.summary_failed or self._guard["paused"]) and plan.can_fit:
+ return False
+ return await self._shrink(system, selected, request, view, plan, emit, ladder)
+
+ async def _minimal(
+ self, system: str, selected: ModelSelection, request: ModelRequest, view: ContextView, plan: Budget
+ ) -> tuple[ModelRequest, Budget]:
+ """Section 8 (d): the request that would remain with everything but the last unit moved out, and its budget.
+
+ The drop's own row for that cut (its ``<current-request>`` and state included), uncommitted, projected and
+ composed like the conversation's next request (invariant 1); budgeted with no anchor, whose history is gone.
+ """
+ if len(view.units) < 2:
+ return request, plan # nothing can move out
+ payload, after = await self._compaction(request, view, plan, len(view.units) - 1, **self._dropped(view))
+ minimal, _ = self._built(system, selected, messages=self._carried(after))
+ return minimal, budget(minimal, selected.capabilities, transcript=after.messages)
+
+ def _carried(self, view: ContextView) -> tuple[Message, ...]:
+ """What a conversation request carries for ``view``: the rehydrated state, then the projected context."""
+ return (*self._rehydrated(), *view.messages)
+
+ @staticmethod
+ def _dropped(view: ContextView) -> dict[str, Any]:
+ """A dropped row's fields (section 8 c): no model call, the previous checkpoint's text kept."""
+ previous = view.compaction
+ return {
+ "mode": "dropped",
+ "reason": "overflow",
+ "focus": None,
+ "checkpoint": previous.payload.get("checkpoint", "") if previous is not None else "",
+ "summarizer": None,
+ "usage": None,
+ "mid_turn": True,
+ }
+
+ def _fork_base(self, view: ContextView, mode: str, cut: int) -> tuple[Message, ...]:
+ """What a fork carries before the checkpoint request: the whole context, or for a rolling fork its prefix."""
+ if mode == "normal":
+ return tuple(view.messages)
+ head = (view.checkpoint,) if view.checkpoint is not None else ()
+ return (*head, *(message for unit in view.units[:cut] for message in unit.messages))
+
+ def _fork(
+ self,
+ system: str,
+ route: ModelSelection,
+ base: Sequence[Message],
+ prompt: UserMessage,
+ turn: Sequence[Message],
+ anchor: Optional[Anchor],
+ ) -> tuple[ModelRequest, dict[str, Tool], Budget]:
+ """A checkpoint turn's request on ``route`` (section 6) and its budget: ``base``, the checkpoint request,
+ and the turn so far. The stage's dry run and the turn itself compose it here, so they cannot differ."""
+ transcript = (*base, prompt, *turn)
+ request, tools = self._built(
+ system,
+ route,
+ messages=(*self._rehydrated(), *transcript),
+ max_tokens=checkpoint_max_tokens(route.capabilities, self.max_tokens),
+ )
+ return request, tools, budget(request, route.capabilities, transcript=transcript, anchor=anchor)
+
+ def _fork_fits(self, system: str, selected: ModelSelection, view: ContextView, mode: str, cut: int) -> bool:
+ """A dry compose of the first request the checkpoint turn would send, budgeted: a choice, not admission."""
+ fork = self._fork(
+ system, selected, self._fork_base(view, mode, cut), _CHECKPOINT_REQUEST, (), last_anchor(self._rows, view)
+ )
+ return fork[2].can_fit
+
+ async def _shrink(
+ self,
+ system: str,
+ selected: ModelSelection,
+ request: ModelRequest,
+ view: ContextView,
+ plan: Budget,
+ emit: Callable[..., Awaitable[None]],
+ ladder: _Ladder,
+ ) -> bool:
+ """One step of the overflow ladder (section 8); False when nothing can move and the provider judges."""
+ units = view.units
+ if not ladder.summary_failed and not self._guard["paused"] and not ladder.compacted:
+ ladder.compacted = True
+ cut = normal_cut(units, plan.keep)
+ if cut is not None and self._fork_fits(system, selected, view, "normal", cut):
+ outcome = await self._checkpoint(
+ system, selected, request, view, plan, cut, mode="normal", reason="overflow", emit=emit
+ )
+ if outcome.ok:
+ return True
+ ladder.summary_failed = not outcome.overflow
+ if not ladder.summary_failed and not self._guard["paused"] and ladder.rolls < MAX_ROLLS:
+ cut = rolling_cut(units, lambda cut: self._fork_fits(system, selected, view, "rolling", cut))
+ if cut is not None:
+ ladder.rolls += 1
+ outcome = await self._checkpoint(
+ system, selected, request, view, plan, cut, mode="rolling", reason="overflow", emit=emit
+ )
+ if outcome.ok:
+ return True
+ ladder.summary_failed = True
+ else:
+ ladder.rolls = MAX_ROLLS
+ cut = half_cut(units)
+ if cut is not None:
+ await self._drop(request, view, plan, cut, emit)
+ return True
+ if ladder.overflows or not plan.can_fit:
+ raise self._exhausted(request, view, plan)
+ return False
+
+ def _exhausted(self, request: ModelRequest, view: ContextView, plan: Budget) -> _Exhausted:
+ """Section 8 (d): what fills the request, for the user's stop message."""
+ last = view.units[-1] if view.units else None
+ last_tokens = unit_tokens(last) if last is not None else 0
+ parts = [
+ ContextPart("system", text_tokens(request.system)),
+ ContextPart("tools", request_tokens("", request.tools, ())),
+ ContextPart("history", max(0, messages_tokens(request.messages) - last_tokens)),
+ ]
+ if last is not None:
+ name = "current_request" if last.lead.kind == "input" else "latest_tool_batch"
+ parts.append(ContextPart(name, last_tokens))
+ parts.append(ContextPart("output", plan.output + plan.margin))
+ return _Exhausted(plan.input_limit, tuple(parts))
+
+ async def _manual_compaction(
+ self, system: str, selected: ModelSelection, focus: Optional[str], emit: Callable[..., Awaitable[None]]
+ ) -> RunEndReason:
+ """Section 10: clear the pause and both counters, then a normal checkpoint between runs."""
+ view = context_view(self._rows)
+ # Measured for the cut only; it is never sent.
+ request, _ = await self._request(system, selected, messages=self._carried(view))
+ plan = budget(request, selected.capabilities, transcript=view.messages, anchor=last_anchor(self._rows, view))
+ cut = normal_cut(view.units, plan.keep)
+ if cut is None:
+ # Everything is within the kept tail: the adapter tells the user there is nothing to compact yet.
+ await self._commit_context([], dict(_GUARD_DEFAULT))
+ await emit(CompactionSkipped, reason="manual")
+ return "completed"
+ self._guard = dict(_GUARD_DEFAULT) # the checkpoint's transition starts from a cleared pause
+ outcome = await self._checkpoint(
+ system, selected, request, view, plan, cut, mode="normal", reason="manual", emit=emit, focus=focus,
+ mid_turn=False,
+ )
+ return "completed" if outcome.ok else "error"
+
+ async def _checkpoint(
+ self,
+ system: str,
+ selected: ModelSelection,
+ request: ModelRequest,
+ view: ContextView,
+ plan: Budget,
+ cut: int,
+ *,
+ mode: str,
+ reason: str,
+ emit: Callable[..., Awaitable[None]],
+ focus: Optional[str] = None,
+ mid_turn: bool = True,
+ ) -> _Outcome:
+ """Sections 6 and 7: a forked checkpoint turn; on success its row joins the context."""
+ await emit(CompactionStarted, reason=reason)
+ prompt = checkpoint_request(focus)
+ base = self._fork_base(view, mode, cut)
+ anchor = last_anchor(self._rows, view)
+ policy = CheckpointPolicy(cwd=self.cwd, scratch_dir=self.context.scratch_dir)
+ turn: list[Message] = [] # what the turn's next request carries after the checkpoint request
+ produced: list[Message] = [] # the audit: every attempt's message from the ledger, and the tool results
+ start = mark = len(self._attempts)
+ measured: list[Budget] = [] # the budget of the turn's latest request, as sent
+ rounds = 0
+ error: Optional[str] = None
+ overflow = False
+ checkpoint = ""
+ origin = None
+ selection: Optional[ModelSelection] = selected
+
+ async def compose(route: ModelSelection) -> tuple[ModelRequest, dict[str, Tool]]:
+ fork, tools, fork_plan = self._fork(system, route, base, prompt, turn, anchor)
+ if not fork_plan.can_fit:
+ raise _ForkTooLarge()
+ measured[:] = [fork_plan]
+ return fork, tools
+
+ finished: dict[str, Any] = {"outcome": "failed", "error": None, "compaction_event_id": None}
+ aborted = False
+ try:
+ try:
+ while True:
+ try:
+ async with self._model(
+ system, _silent, selection, compose=compose, purpose="checkpoint", after=(prompt, *turn)
+ ) as (terminal, tools):
+ selection = None
+ except _ForkTooLarge:
+ overflow, error = True, "overflow: the checkpoint request does not fit the model's input limit."
+ break
+ except ProviderProtocolViolation as violation:
+ # Not admitted: a failed checkpoint, and none of its calls runs.
+ error = str(violation)
+ break
+ finally:
+ produced.extend(item.message for item in self._attempts[mark:] if item.message is not None)
+ mark = len(self._attempts)
+ if isinstance(terminal, ProviderError):
+ overflow = terminal.kind == "overflow"
+ error = f"{terminal.kind}: {terminal.message}"
+ break
+ message = terminal.message
+ self._scope.check()
+ turn.append(message)
+ origin = message.origin
+ if message.stop_reason == "stop" and not message.tool_calls:
+ checkpoint = checkpoint_text(message)
+ if not checkpoint:
+ error = "The checkpoint turn ended without checkpoint text."
+ break
+ if message.stop_reason != "tool_use" or not message.tool_calls:
+ # Only a stop with text and no call is a checkpoint, and only a tool-use stop carries calls.
+ error = f"The checkpoint turn stopped with {message.stop_reason} and no usable checkpoint."
+ break
+ if not policy.open:
+ # Its earlier calls were already answered with BUDGET_USED.
+ error = "The checkpoint turn kept calling tools after its tool budget was used up."
+ break
+ rounds += 1
+ sent = measured[0]
+ grown = sent.est + message_tokens(message)
+ calls = message.tool_calls
+ for index, call in enumerate(calls):
+ self._scope.check()
+ # The bound is the window of the turn's route: a tool runs only while the next request can
+ # still grow by the floor, after the fixed-text results every later call of the batch may
+ # need are reserved (section 6).
+ reserved = (len(calls) - index - 1) * _FIXED_RESULT_TOKENS
+ room = sent.input_limit - grown - sent.output - reserved
+ policy.open = policy.open and rounds <= CHECKPOINT_TOOL_ROUNDS and room >= CHECKPOINT_TOOL_FLOOR
+ result = await self._checkpoint_tool(call, tools, policy, limit=room - CHECKPOINT_TOOL_SLACK)
+ turn.append(result)
+ produced.append(result)
+ grown += message_tokens(result)
+ finally:
+ policy.close() # the scratch root's descriptor lives for this turn only
+ payload = None
+ if checkpoint:
+ summarizer = {
+ "origin": {"provider": origin.provider, "api": origin.api, "model": origin.model},
+ "prompt_version": PROMPT_VERSION,
+ "rounds": rounds,
+ }
+ try:
+ hosted = await self._hosted(view, cut, mid_turn)
+ except (_Aborted, asyncio.CancelledError):
+ raise
+ except Exception as failure:
+ # Only the host's part after the model answered (state, lookup) is a failed checkpoint,
+ # counted; an error building the row itself ends the run, like any engine error.
+ error = f"The checkpoint row could not be built: the host failed: {type(failure).__name__}: {failure}"
+ else:
+ payload, _ = await self._compaction(
+ request,
+ view,
+ plan,
+ cut,
+ mode=mode,
+ reason=reason,
+ focus=focus,
+ checkpoint=checkpoint,
+ summarizer=summarizer,
+ usage=self._turn_usage(start),
+ mid_turn=mid_turn,
+ hosted=hosted,
+ )
+ if payload is None:
+ finished["error"] = error
+ guard, paused = self._counted(ok=False)
+ await self._commit_context([], guard)
+ await emit(CompactionFailed, reason=reason, error=error)
+ if paused:
+ await emit(CompactionPaused, cause=paused)
+ return _Outcome(False, overflow)
+ row, paused = await self._commit_compaction(payload)
+ finished.update(outcome="completed", compaction_event_id=row.row_id)
+ await emit(
+ CompactionFinished,
+ event_id=row.row_id,
+ reason=reason,
+ mode=mode,
+ tokens_before=row.payload["tokens_before"],
+ tokens_after_estimate=row.payload["tokens_after_estimate"],
+ )
+ if paused:
+ await emit(CompactionPaused, cause=paused)
+ return _Outcome(True)
+ except (_Aborted, asyncio.CancelledError):
+ aborted = True # the cancelled run scope admits no further store write
+ raise
+ except BaseException as failure:
+ if finished["outcome"] != "completed" and finished["error"] is None:
+ finished["error"] = f"{type(failure).__name__}: {failure}" # a failed commit, or a failed compose
+ raise
+ finally:
+ if not aborted:
+ # Invariant 4 for checkpoint turns: one audit, from the ledger, on every exit but an abort.
+ await self._record_turn(self._turn_record(reason, mode, produced, start, finished))
+
+ def _turn_usage(self, start: int) -> Optional[Usage]:
+ """The usage every attempt of a checkpoint turn reported, from the ledger."""
+ usage = None
+ for item in self._attempts[start:]:
+ usage = add_usage(usage, item.message.usage if item.message is not None else None)
+ return usage
+
+ def _turn_record(
+ self, reason: str, mode: str, produced: Sequence[Message], start: int, finished: Mapping[str, Any]
+ ) -> dict[str, Any]:
+ """A checkpoint turn's audit (``CheckpointTurn``, section 6): its messages, usage, and outcome."""
+ messages = []
+ for message in produced:
+ try:
+ messages.append(message_to_dict(message))
+ except (ValueError, RecursionError) as invalid:
+ # Arguments a provider sent that are not JSON: refused at admission (the turn's error names
+ # them), and no JSON row can hold them either.
+ self._outcome.diagnostic(type(invalid).__name__, f"Checkpoint audit left out a message: {invalid}")
+ record: dict[str, Any] = {"version": 1, "reason": reason, "mode": mode, "messages": messages}
+ usage = self._turn_usage(start)
+ if usage is not None:
+ record["usage"] = usage_to_dict(usage)
+ return {**record, **finished}
+
+ def _counted(self, *, ok: bool, ineffective: Optional[bool] = None) -> tuple[dict[str, Any], Optional[str]]:
+ """The guard after one checkpoint attempt (section 10), and the pause cause when it pauses now."""
+ guard = dict(self._guard)
+ cause = None
+ if not ok:
+ guard["failures"] += 1
+ cause = "failures" if guard["failures"] >= PAUSE_AFTER else None
+ else:
+ guard["failures"] = 0
+ if ineffective is not None:
+ guard["ineffective"] = guard["ineffective"] + 1 if ineffective else 0
+ cause = "ineffective" if guard["ineffective"] >= PAUSE_AFTER else None
+ if cause is None or guard["paused"]:
+ return guard, None
+ guard["paused"] = True
+ return guard, cause
+
+ async def _checkpoint_tool(
+ self, original: ToolCallBlock, tools: Mapping[str, Tool], policy: CheckpointPolicy, *, limit: int
+ ) -> ToolResultMessage:
+ """The checkpoint turn's tool pipeline (invariant 2); nothing it produces is committed.
+
+ The budget first, then the table, then execution (a scratch write or edit through the root's
+ descriptor), then the bound on whatever result came out. No user hook runs under C-9 (v1).
+ """
+ call = deepcopy(original)
+ decision = policy.decide(call) if policy.open else Decision(denial=BUDGET_USED)
+ if decision.denial is not None:
+ # The policy's fixed texts are short and never cut: a truncation note would invite another call.
+ return ToolResultMessage(call.id, call.name, (text(decision.denial),), True)
+ if decision.scratch is not None:
+ # Relative to the scratch root's descriptor: no pathname is resolved again. Joined, never interrupted:
+ # the worker thread outlives a cancelled await, and the root closes only after it is done (section 6).
+ result = await self._scope.call(
+ lambda: to_thread_joined(policy.run, call, decision.scratch), interruptible=False
+ )
+ elif (tool := tools.get(call.name)) is None:
+ result = ToolResult((text(f"Tool {call.name} is not available."),), is_error=True)
+ else:
+ result = await self._execute(tool, call, _silent)
+ # Every other result that enters the turn is bounded to the room the window leaves (section 6).
+ return ToolResultMessage(call.id, call.name, fit_result(result.content, limit), result.is_error)
+
+ async def _drop(
+ self, request: ModelRequest, view: ContextView, plan: Budget, cut: int, emit: Callable[..., Awaitable[None]]
+ ) -> None:
+ """Section 8 (c): the earliest part moves out with no model call; the previous checkpoint stays."""
+ await emit(CompactionStarted, reason="overflow")
+ payload, _ = await self._compaction(request, view, plan, cut, **self._dropped(view))
+ row, _ = await self._commit_compaction(payload)
+ await emit(
+ CompactionFinished,
+ event_id=row.row_id,
+ reason="overflow",
+ mode="dropped",
+ tokens_before=row.payload["tokens_before"],
+ tokens_after_estimate=row.payload["tokens_after_estimate"],
+ )
+
+ async def _compaction(
+ self,
+ request: ModelRequest,
+ view: ContextView,
+ plan: Budget,
+ cut: int,
+ *,
+ mode: str,
+ reason: str,
+ focus: Optional[str],
+ checkpoint: str,
+ summarizer: Optional[Mapping[str, Any]],
+ usage: Optional[Usage],
+ mid_turn: bool,
+ hosted: Optional[tuple[tuple[str, ...], Optional[str]]] = None,
+ ) -> tuple[dict[str, Any], ContextView]:
+ """The checkpoint row for ``cut`` (section 7), uncommitted, and the context it would leave.
+
+ The one builder of a ``Compaction`` row: the drop, the checkpoint turn, and the stop check's dry run.
+ ``hosted`` is the host's part (``_hosted``) when the caller already has it.
+ """
+ skills = carried_skills(view, cut)
+ state, earlier = hosted if hosted is not None else await self._hosted(view, cut, mid_turn)
+ payload = compaction_payload(
+ view,
+ cut,
+ mode=mode,
+ reason=reason,
+ focus=focus,
+ checkpoint=checkpoint,
+ skills=skills,
+ state=state,
+ earlier_record=earlier,
+ tokens_before=plan.est,
+ threshold=plan.threshold,
+ summarizer=summarizer,
+ usage=usage,
+ )
+ seq = max((row.context_seq for row in self._rows), default=0) + 1
+ candidate = ContextEntry(self.session_id, seq, "compaction", "uncommitted-compaction", payload=payload)
+ after = context_view([*self._rows, candidate])
+ # What the next request would carry; it is budgeted for real when it is built.
+ payload["tokens_after_estimate"] = request_tokens(request.system, request.tools, self._carried(after))
+ return payload, after
+
+ async def _hosted(self, view: ContextView, cut: int, mid_turn: bool) -> tuple[tuple[str, ...], Optional[str]]:
+ """The host's part of a checkpoint row for ``cut``: the rendered ``state`` and the earlier-record lookup."""
+ host = self.context.host
+ if host is None:
+ return (), None
+ needed = StateRequest(self.session_id, carried_skills(view, cut), mid_turn)
+ state = tuple(await self._scope.call(lambda: host.render_state(needed)))
+ if not all(isinstance(item, str) for item in state):
+ raise TypeError("ContextHost.render_state must return strings")
+ return state, host.earlier_record(self.session_id, summarized_to_seq(view, cut))
+
+ async def _commit_compaction(self, payload: Mapping[str, Any]) -> tuple[ContextEntry, Optional[str]]:
+ """A built checkpoint row and, for a checkpoint request, the guard it moves, in one ``_commit_context``."""
+ guard, paused = self._guard, None
+ if payload["summarizer"] is not None:
+ ineffective = payload["tokens_after_estimate"] >= INEFFECTIVE_RATIO * payload["threshold"]
+ guard, paused = self._counted(ok=True, ineffective=ineffective if payload["mode"] == "normal" else None)
+ (row,) = await self._commit_context([("compaction", payload)], guard)
+ return row, paused
+
+ async def _commit_context(
+ self, rows: Sequence[tuple[Literal["compaction", "context_edit"], Mapping[str, Any]]], guard: Mapping[str, Any]
+ ) -> tuple[ContextEntry, ...]:
+ """The one writer of C-9 state (invariant 3).
+
+ Edits, a checkpoint, and the guard, with the hook state of this commit point, go in one transaction,
+ before any event announces the transition. A failed commit changes nothing, in memory or on disk.
+ """
+ entries: list[tuple[str, Mapping[str, Any]]] = []
+ representation = state_representation(self._ctx.state)
+ state = deepcopy(self._ctx.state)
+ if dict(guard) != self._committed_guard or representation != self._committed_state_json:
+ entries.append(("agent_state", {"version": 1, "state": state, "context": dict(guard)}))
+ entries.extend(rows)
+ if not entries:
+ return ()
+ committed = await self._scope.call(
+ lambda: self.store.append_payloads(self.session_id, deepcopy(entries)), interruptible=False
+ )
+ self._rows.extend(committed)
+ self._guard, self._committed_guard = dict(guard), dict(guard)
+ self._committed_state, self._committed_state_json = state, representation
+ return tuple(row for row in committed if row.kind != "agent_state")
+
+ async def _record_turn(self, payload: Mapping[str, Any]) -> None:
+ """The checkpoint turn's audit row (section 6)."""
+ await self._audit("checkpoint_turn", payload)
+
+ async def _audit(self, kind: Literal["checkpoint_turn", "attempt"], payload: Mapping[str, Any]) -> None:
+ """A non-context audit row; never context, so losing it never fails the run."""
+ try:
+ await self._scope.call(
+ lambda: self.store.append_audit(self.session_id, kind, deepcopy(dict(payload))),
+ interruptible=False,
+ )
+ except _Aborted:
+ raise
+ except Exception as error:
+ self._outcome.diagnostic(type(error).__name__, f"Audit write failed ({kind}): {error}")
diff --git a/core/agent_core/agent/models.py b/core/agent_core/agent/models.py
index 358b0770e..f35dd667d 100644
--- a/core/agent_core/agent/models.py
+++ b/core/agent_core/agent/models.py
@@ -14,26 +14,13 @@ from core.agent_core.ai.provider import (
)
from core.agent_core.messages import ProtocolName
-DEFAULT_CONTEXT_WINDOW = 128_000
-DEFAULT_MAX_OUTPUT_TOKENS = 8_192
-
-
@dataclass(frozen=True)
class ModelSelection:
+ """A resolved route; C-9 derives every limit from its ``capabilities`` (``harness.context.budget``)."""
+
endpoint: ModelEndpoint
capabilities: ModelCapabilities
- @property
- def context_window(self) -> int:
- """Effective C-9 budget; preserve nullable source capabilities."""
- value = self.capabilities.context_window
- return DEFAULT_CONTEXT_WINDOW if value is None else value
-
- @property
- def max_output_tokens(self) -> int:
- value = self.capabilities.max_output_tokens
- return DEFAULT_MAX_OUTPUT_TOKENS if value is None else value
-
class ModelRouter(Protocol):
async def resolve(self) -> ModelSelection:
diff --git a/core/agent_core/agent/scratch.py b/core/agent_core/agent/scratch.py
new file mode 100644
index 000000000..b398da3be
--- /dev/null
+++ b/core/agent_core/agent/scratch.py
@@ -0,0 +1,172 @@
+"""The checkpoint turn's scratch files, through one directory descriptor (C-9 ``context.md`` section 6).
+
+Scratch is flat: every file is a single name directly inside the Session's
+scratch root. The root is opened once, when the checkpoint turn starts
+(``O_DIRECTORY | O_NOFOLLOW``, then ``fstat``), and every read, temporary
+file, and publication is relative to that descriptor, never to a pathname.
+Renaming the root or swapping it, or a name in it, for a symlink after it was
+opened therefore cannot redirect anything: a name is never followed, and the
+descriptor keeps naming the directory that was opened.
+
+``write`` and ``edit`` keep the tools' names, arguments, and result texts
+(C-7); ``edit`` reuses ``edit_diff`` for matching, BOM, and line endings.
+Where the platform cannot open and rename relative to a directory descriptor
+(Windows), no scratch root is opened and the policy denies scratch writes.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import errno
+import os
+import secrets
+import stat
+from typing import Any, Mapping, Optional
+
+from core.agent_core.tools.args import ToolInputError, error_result, str_arg, text_result
+from core.agent_core.tools.base import ToolResult
+from core.agent_core.tools.edit import MAX_EDIT_BYTES, _edits_arg, prepare_edit_arguments
+from core.agent_core.tools.edit_diff import EditError, ResultTooLarge, apply_edits
+from core.agent_core.tools.text import decode_file, encode_file
+
+
+def supported() -> bool:
+ """Whether this platform can open and rename relative to a directory descriptor.
+
+ CPython lists ``renameat`` support under ``os.rename``; ``os.replace`` is the same call.
+ """
+ return os.open in os.supports_dir_fd and os.rename in os.supports_dir_fd and hasattr(os, "O_NOFOLLOW")
+
+
+def valid_name(name: str) -> bool:
+ """A single file name: no separator, and neither ``.`` nor ``..``."""
+ separators = {os.sep} | ({os.altsep} if os.altsep else set())
+ return bool(name) and name not in {".", ".."} and not any(separator in name for separator in separators)
+
+
+class ScratchRoot:
+ """The opened scratch root of one checkpoint turn; ``close`` releases the descriptor."""
+
+ def __init__(self, fd: int) -> None:
+ self._fd = fd
+
+ @classmethod
+ def open(cls, path: str) -> Optional["ScratchRoot"]:
+ """Create and open the root; None when the platform cannot, or it is not a real directory."""
+ if not supported():
+ return None
+ try:
+ os.makedirs(path, exist_ok=True)
+ fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
+ except OSError:
+ return None
+ if not stat.S_ISDIR(os.fstat(fd).st_mode):
+ os.close(fd)
+ return None
+ return cls(fd)
+
+ def close(self) -> None:
+ with contextlib.suppress(OSError):
+ os.close(self._fd)
+
+ # --- the tools -------------------------------------------------------------------------
+
+ def write(self, name: str, arguments: Mapping[str, Any]) -> ToolResult:
+ path = arguments.get("path")
+ try:
+ content = str_arg(arguments, "content")
+ except ToolInputError as exc:
+ return error_result(str(exc))
+ try:
+ refusal = self._replaceable(name)
+ if refusal:
+ return error_result(f"Cannot write {path}: {refusal}.")
+ self._publish(name, content.encode("utf-8"))
+ except OSError as exc:
+ return error_result(f"Cannot write {path}: {os.strerror(exc.errno) if exc.errno else exc}.")
+ return text_result(f"Successfully wrote to {path}")
+
+ def edit(self, name: str, arguments: Mapping[str, Any]) -> ToolResult:
+ try:
+ arguments = prepare_edit_arguments(arguments)
+ path = str_arg(arguments, "path")
+ edits = _edits_arg(arguments)
+ except ToolInputError as exc:
+ return error_result(str(exc))
+ try:
+ raw, identity = self._read(name)
+ if raw is None:
+ return error_result(f"Could not edit file: {path}. It is not a regular file.")
+ if len(raw) > MAX_EDIT_BYTES:
+ return error_result(f"File {path} is over the edit limit. Write it again instead.")
+ new_text, _, _ = apply_edits(decode_file(raw), edits, path, max_result_chars=MAX_EDIT_BYTES)
+ self._publish(name, encode_file(new_text), expected=identity)
+ except EditError as exc:
+ return error_result(str(exc))
+ except ResultTooLarge:
+ return error_result(f"File {path} would be over the edit limit after this edit.")
+ except _Changed:
+ return error_result(f"Could not edit file: {path}. It changed while the edit was being applied; read it again.")
+ except OSError as exc:
+ return error_result(f"Could not edit file: {path}. {os.strerror(exc.errno) if exc.errno else exc}.")
+ return text_result(f"Successfully replaced {len(edits)} block(s) in {path}.")
+
+ # --- descriptor-relative steps ------------------------------------------------------------
+
+ def _lstat(self, name: str) -> Optional[os.stat_result]:
+ try:
+ return os.stat(name, dir_fd=self._fd, follow_symlinks=False)
+ except FileNotFoundError:
+ return None
+
+ def _replaceable(self, name: str) -> Optional[str]:
+ info = self._lstat(name)
+ if info is None or stat.S_ISREG(info.st_mode):
+ return None
+ return "it is a directory" if stat.S_ISDIR(info.st_mode) else "it is not a regular file"
+
+ def _read(self, name: str) -> tuple[Optional[bytes], Optional[tuple[int, int, int]]]:
+ """The bytes of a regular file, never through a symlink, and its identity; None for anything else."""
+ try:
+ fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW, dir_fd=self._fd)
+ except OSError as exc:
+ if exc.errno == errno.ELOOP: # the name is a symlink: never followed
+ return None, None
+ raise
+ try:
+ info = os.fstat(fd)
+ if not stat.S_ISREG(info.st_mode):
+ return None, None
+ chunks, size = [], 0
+ while size <= MAX_EDIT_BYTES:
+ chunk = os.read(fd, 1 << 20)
+ if not chunk:
+ break
+ chunks.append(chunk)
+ size += len(chunk)
+ return b"".join(chunks), (info.st_ino, info.st_size, info.st_mtime_ns)
+ finally:
+ os.close(fd)
+
+ def _publish(self, name: str, data: bytes, *, expected: Optional[tuple[int, int, int]] = None) -> None:
+ """A private temp file beside ``name`` in the root, fsynced, then renamed over it; all by descriptor."""
+ tmp = f".avibe-{secrets.token_hex(6)}.tmp"
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=self._fd)
+ try:
+ with os.fdopen(fd, "wb") as handle:
+ handle.write(data)
+ handle.flush()
+ os.fsync(handle.fileno())
+ if expected is not None:
+ info = self._lstat(name)
+ if info is None or (info.st_ino, info.st_size, info.st_mtime_ns) != expected:
+ raise _Changed()
+ os.replace(tmp, name, src_dir_fd=self._fd, dst_dir_fd=self._fd)
+ except BaseException:
+ with contextlib.suppress(OSError):
+ os.unlink(tmp, dir_fd=self._fd)
+ raise
+
+
+class _Changed(Exception):
+ """The file is no longer the one an edit read; nothing was written."""
diff --git a/core/agent_core/harness/context.py b/core/agent_core/harness/context.py
new file mode 100644
index 000000000..2bc083aad
--- /dev/null
+++ b/core/agent_core/harness/context.py
@@ -0,0 +1,641 @@
+"""C-9 context management rules (``agent-core-contracts/context.md``).
+
+Pure functions over the projected ``ContextView``: the limits, the token
+estimate, which tool results to clear, where to cut, and the checkpoint's
+model-facing text and row. The loop applies them before every model request;
+the adapter supplies a ``ContextHost`` for what only it knows.
+
+The cut rule and cumulative file lists follow Pi (MIT, Copyright (c) 2025
+Mario Zechner, ``packages/coding-agent/src/core/compaction/`` at ``7fbbd5f``);
+the checkpoint request is the owner-approved prompt ``checkpoint-v2``.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import time
+from dataclasses import dataclass, field
+from typing import Any, Callable, Mapping, Optional, Protocol, Sequence
+
+from core.agent_core.ai._common import endpoint_origin
+from core.agent_core.ai.provider import ModelCapabilities, ModelRequest
+from core.agent_core.harness.projection import ContextView, Unit, context_view
+from core.agent_core.harness.store import ContextEntry
+from core.agent_core.messages import (
+ AssistantMessage,
+ ImageBlock,
+ Message,
+ TextBlock,
+ ThinkingBlock,
+ ToolCallBlock,
+ ToolResultMessage,
+ UserContent,
+ UserMessage,
+ Usage,
+ text,
+ usage_to_dict,
+)
+from core.agent_core.tools.base import ToolSpec
+
+# --- constants (context.md) -----------------------------------------------------
+
+DEFAULT_CONTEXT_WINDOW = 128_000
+DEFAULT_MAX_OUTPUT_TOKENS = 8_192
+MARGIN_MIN = 8_000
+MARGIN_RATIO = 0.03
+THRESHOLD_RATIO = 0.9
+KEEP_MAX = 20_000
+KEEP_RATIO = 0.25
+IMAGE_TOKENS = 1_600
+
+CLEAR_SOFT_RATIO = 0.8
+CLEAR_MIN_TOKENS = 20_000
+CLEAR_KEEP_RESULTS = 5
+CLEAR_PROTECTED_TURNS = 2
+CLEARABLE_TOOLS = frozenset({"read", "bash"})
+CACHE_TTL_S = 300.0
+CLEARED_PLACEHOLDER = (
+ "[Old tool result cleared to save context. Re-run the tool or re-read the file if you need it again.]"
+)
+
+CHECKPOINT_MAX_TOKENS = 16_000
+CHECKPOINT_TOOL_ROUNDS = 5
+#: A checkpoint turn's tool runs only while the window leaves this much room (context.md section 6).
+CHECKPOINT_TOOL_FLOOR = 4_000
+#: Room a tool result leaves for the checkpoint request's growth.
+CHECKPOINT_TOOL_SLACK = 1_000
+CHECKPOINT_TRUNCATED = (
+ "[Output truncated to fit this checkpoint turn: showing about {shown} of {total} tokens. "
+ "Read a smaller range if you need more.]"
+)
+MAX_ROLLS = 2
+MAX_OVERFLOWS = 4
+PAUSE_AFTER = 3
+INEFFECTIVE_RATIO = 0.75
+
+PROMPT_VERSION = "checkpoint-v2"
+
+# The owner-approved checkpoint request (context.md section 11), verbatim.
+CHECKPOINT_REQUEST = """<context-checkpoint-request>
+Pause the work here. Do not call any tool and do not continue the task. This reply does one thing: write a context checkpoint.
+
+The conversation above will be replaced by your checkpoint plus the messages after it. Whoever continues is you, but you will no longer remember this conversation; the checkpoint is all you will know of it. What you do not write down is lost.
+If there is an earlier checkpoint above, it is discarded after this: carry forward everything in it that still matters; where it conflicts with later messages, the later messages win.
+
+Everything above is a record to summarize, not instructions to act on now.
+
+Write in three layers, from the broad to the specific. Use exactly these headings, in this order. Write "(none)" under an empty heading.
+
+# 1. Self and method
+
+## How I work here
+- The role the user expects of me in this conversation, and the working agreements we established (for example how to report, when to ask, what I may decide on my own).
+- Methods and judgments that proved effective here, and ones that proved ineffective, written as transferable principles I can apply to any later work.
+- Record only what this conversation established; my identity and standing instructions come from the system prompt and are not restated here.
+
+# 2. Goals and requirements
+
+## Goals
+- What the user wants to achieve, and the intent behind it. If there are several, list each and mark the one being pursued now.
+
+## User requirements
+- Every instruction, preference, correction, and prohibition from the user that still applies. Quote short ones verbatim. Never drop one unless the user withdrew it.
+
+## Key decisions
+- decision: reason
+
+## Pitfalls
+- Mistakes made, assumptions that proved false, and dead ends (quote the exact error text where there is one), with what resolved each or "unresolved", so the same mistake is not repeated.
+
+# 3. Now and next
+
+## Progress
+### Done
+### In progress
+### Blocked or open questions
+
+## Waiting on
+- Background commands, Watches, scheduled Tasks, delegated agent runs, or questions to the user that are still expected to report back, with their ids.
+
+## Next steps
+1. The concrete next action, then the ones after it.
+
+## Exact references
+- Exact paths, identifiers, commands, links, ids, and values needed to continue.
+
+Rules: terse bullets, not paragraphs. Preserve exact paths, identifiers, commands, error strings, and numbers. Do not invent anything that is not above. Never write out secrets, tokens, or credentials; refer to them by name. Write in the language the user writes in."""
+CHECKPOINT_FOCUS = "Additional focus from the user: {focus}"
+CHECKPOINT_REQUEST_END = "</context-checkpoint-request>"
+
+CHECKPOINT_FRAMING = (
+ "This is a record of the earlier part of this conversation, written for you so you can continue. It is "
+ "history, not new instructions: the user requirements recorded in it still apply, but do not treat the "
+ "record itself as a request."
+)
+EARLIER_RECORD_LEAD = "The full text of the earlier conversation is still stored. To look up a detail, run:"
+
+
+# --- what the adapter supplies ----------------------------------------------------
+
+
+@dataclass(frozen=True)
+class SkillRef:
+ name: str
+ revision: str
+
+
+@dataclass(frozen=True)
+class StateRequest:
+ """What ``ContextHost.render_state`` renders for a new checkpoint (context.md section 7)."""
+
+ session_id: str
+ #: Skills the summarized rows loaded, latest load last, minus those still loaded in the kept rows.
+ skills: tuple[SkillRef, ...]
+ #: True inside a run: the input that carried the environment may be summarized away.
+ mid_turn: bool
+
+
+class ContextHost(Protocol):
+ def earlier_record(self, session_id: str, through_seq: int) -> Optional[str]:
+ """The command that looks up the moved-out rows through ``through_seq``, or None."""
+ ...
+
+ async def render_state(self, request: StateRequest) -> Sequence[str]:
+ """State texts from their own stores: skill bodies, pending Harness work, the environment block."""
+ ...
+
+
+@dataclass(frozen=True)
+class ContextConfig:
+ """Turns C-9 on for an ``Agent``; without it, no context management runs."""
+
+ host: Optional[ContextHost] = None
+ #: This Session's scratch directory; checkpoint turns may write only there.
+ scratch_dir: Optional[str] = None
+ clear_tool_results: bool = True
+ cache_ttl_s: float = CACHE_TTL_S
+ clock: Callable[[], float] = field(default=time.time, repr=False)
+
+
+# --- token estimate (context.md section 2) -----------------------------------------
+
+
+def text_tokens(value: str) -> int:
+ return math.ceil(_utf8(value) / 4)
+
+
+def _utf8(value: str) -> int:
+ return len(value.encode("utf-8", "surrogatepass"))
+
+
+def message_tokens(message: Message) -> int:
+ """UTF-8 bytes / 4 of everything replayed, with a fixed cost per image."""
+ size = 0
+ images = 0
+ for block in message.content:
+ if isinstance(block, TextBlock):
+ size += _utf8(block.text) if block.text is not None else block.ref.bytes
+ elif isinstance(block, ImageBlock):
+ images += 1
+ elif isinstance(block, ThinkingBlock):
+ size += _utf8(block.text) + _utf8(block.signature or "")
+ elif isinstance(block, ToolCallBlock):
+ arguments = json.dumps(block.arguments, ensure_ascii=False, separators=(",", ":"))
+ size += _utf8(block.name) + _utf8(arguments) + _utf8(block.signature or "")
+ return math.ceil(size / 4) + images * IMAGE_TOKENS
+
+
+def messages_tokens(messages: Sequence[Message]) -> int:
+ return sum(message_tokens(message) for message in messages)
+
+
+def request_tokens(system: str, tools: Sequence[ToolSpec], messages: Sequence[Message]) -> int:
+ """The whole request: system prompt, tool definitions, and messages."""
+ definitions = sum(
+ _utf8(json.dumps([spec.name, spec.description, dict(spec.input_schema)], ensure_ascii=False))
+ for spec in tools
+ )
+ return math.ceil((_utf8(system) + definitions) / 4) + messages_tokens(messages)
+
+
+def usage_total(usage: Usage) -> int:
+ return usage.input_tokens + usage.cache_read_tokens + usage.cache_write_tokens + usage.output_tokens
+
+
+def add_usage(total: Optional[Usage], usage: Optional[Usage]) -> Optional[Usage]:
+ """Sum every field; reasoning tokens are the sum of those reported, unknown only when none were."""
+ if usage is None:
+ return total
+ if total is None:
+ return usage
+ reasoning = (
+ None
+ if total.reasoning_tokens is None and usage.reasoning_tokens is None
+ else (total.reasoning_tokens or 0) + (usage.reasoning_tokens or 0)
+ )
+ return Usage(
+ input_tokens=total.input_tokens + usage.input_tokens,
+ output_tokens=total.output_tokens + usage.output_tokens,
+ cache_read_tokens=total.cache_read_tokens + usage.cache_read_tokens,
+ cache_write_tokens=total.cache_write_tokens + usage.cache_write_tokens,
+ reasoning_tokens=reasoning,
+ )
+
+
+# --- request accounting (context.md sections 1 and 2) ---------------------------------
+
+
+@dataclass(frozen=True)
+class Anchor:
+ """The latest response in the context with valid usage and request facts on its row (section 2).
+
+ Rebuilt from the rows, so it holds across a new Agent and a new Turn.
+ """
+
+ #: What its request carried from the transcript, before the response.
+ transcript: tuple[Message, ...]
+ response: AssistantMessage
+ #: UTF-8/4 of the whole request it answered, as sent (``ModelResponse.request.tokens``).
+ request_tokens: int
+
+
+def _valid_usage(message: Optional[Message]) -> bool:
+ return (
+ isinstance(message, AssistantMessage)
+ and message.stop_reason not in {"error", "aborted"}
+ and message.usage is not None
+ and usage_total(message.usage) > 0
+ )
+
+
+def sent_tokens(request: ModelRequest) -> int:
+ """UTF-8/4 of a whole request: system prompt, tool definitions, and messages."""
+ return request_tokens(request.system, request.tools, request.messages)
+
+
+def request_facts(request: ModelRequest) -> dict[str, int]:
+ """``ModelResponse.request``: what a response's row records about the request it answered."""
+ return {"tokens": sent_tokens(request)}
+
+
+def last_anchor(rows: Sequence[ContextEntry], view: ContextView) -> Optional[Anchor]:
+ """The anchor the rows hold: their latest response in the context with valid usage and request facts."""
+ for unit in reversed(view.units):
+ lead = unit.lead
+ facts = lead.payload.get("request") if lead.kind == "response" else None
+ if facts is None or not _valid_usage(lead.message):
+ continue
+ # Projection is pure: the rows before the response give exactly the transcript its request carried.
+ before = context_view([row for row in rows if row.context_seq < lead.context_seq]).messages
+ return Anchor(before, lead.message, facts["tokens"])
+ return None
+
+
+def output_tokens(capabilities: ModelCapabilities, configured: int) -> int:
+ """``O`` of a conversation request: the hop's ``max_output_tokens`` (8,192 when unknown), capped by the
+ Agent's output budget."""
+ hop = capabilities.max_output_tokens
+ return min(configured, DEFAULT_MAX_OUTPUT_TOKENS if hop is None else hop)
+
+
+def checkpoint_max_tokens(capabilities: ModelCapabilities, configured: int) -> int:
+ """A checkpoint request's ``max_tokens``: ``min(16,000, O)`` (section 6)."""
+ return min(CHECKPOINT_MAX_TOKENS, output_tokens(capabilities, configured))
+
+
+def _estimate(request: ModelRequest, transcript: Sequence[Message], anchor: Optional[Anchor]) -> int:
+ """The anchored usage while it holds, adjusted by the UTF-8/4 delta of everything else; else UTF-8/4.
+
+ The anchor holds while the request goes to the route that answered it and the transcript up to its response
+ is unchanged. A changed system prompt, tool set, or rehydrated state does not invalidate it: the request's
+ own UTF-8/4 size carries the delta.
+ """
+ whole = sent_tokens(request)
+ if anchor is not None and anchor.response.origin == endpoint_origin(request.endpoint):
+ sent = len(anchor.transcript)
+ if (
+ len(transcript) > sent
+ and transcript[sent] == anchor.response
+ and tuple(transcript[:sent]) == anchor.transcript
+ ):
+ usage = usage_total(anchor.response.usage)
+ return max(0, usage + whole - anchor.request_tokens - message_tokens(anchor.response))
+ return whole
+
+
+def fit_result(content: Sequence[UserContent], limit: int) -> tuple[UserContent, ...]:
+ """A checkpoint turn's tool result cut to ``limit`` tokens, head kept, saying what was cut (section 6)."""
+ total = message_tokens(ToolResultMessage("fit", "fit", tuple(content)))
+ if total <= limit:
+ return tuple(content)
+ note = CHECKPOINT_TRUNCATED.format(shown=max(0, limit), total=total)
+ room = max(0, limit - text_tokens(note) - 1) * 4
+ kept: list[UserContent] = []
+ for block in content:
+ if isinstance(block, TextBlock) and block.text is not None and room > 0:
+ data = block.text.encode("utf-8", "surrogatepass")[:room]
+ kept.append(TextBlock(text=data.decode("utf-8", "ignore")))
+ room -= len(data)
+ elif isinstance(block, ImageBlock) and room >= IMAGE_TOKENS * 4:
+ kept.append(block)
+ room -= IMAGE_TOKENS * 4
+ return (*kept, TextBlock(text=note))
+
+
+@dataclass(frozen=True)
+class Budget:
+ """One composed request measured against the route resolved for it (sections 1 and 2): the request to send,
+ or one the stage only considers (a dry fork, the stop check's minimal request)."""
+
+ window: int
+ input_limit: int
+ #: ``O``: the request's own ``max_tokens``.
+ output: int
+ margin: int
+ threshold: int
+ keep: int
+ est: int
+
+ @property
+ def fits(self) -> bool:
+ """A conversation request stays inside ``L_in`` with the margin."""
+ return self.est + self.output + self.margin <= self.input_limit
+
+ @property
+ def can_fit(self) -> bool:
+ """The request can fit at all, without the margin (a checkpoint request's admission test)."""
+ return self.est + self.output <= self.input_limit
+
+
+def budget(
+ request: ModelRequest,
+ capabilities: ModelCapabilities,
+ *,
+ transcript: Sequence[Message],
+ anchor: Optional[Anchor] = None,
+) -> Budget:
+ """``W, L_in, O, M, T, keep`` and ``est`` of a composed ``request`` on the route resolved for it.
+
+ Sections 1 and 2: it derives ``W, L_in, M, T, keep`` and ``est`` and reads ``O`` from ``request.max_tokens``,
+ which ``output_tokens`` or ``checkpoint_max_tokens`` set when the request was built. ``transcript`` is the part
+ of the request's messages that comes from the rows, which is what an anchor is checked against.
+ """
+ window = DEFAULT_CONTEXT_WINDOW if capabilities.context_window is None else capabilities.context_window
+ limit = window if capabilities.input_limit is None else capabilities.input_limit
+ output = request.max_tokens
+ margin = max(MARGIN_MIN, math.ceil(MARGIN_RATIO * window))
+ threshold = min(limit - output - margin, math.floor(THRESHOLD_RATIO * window))
+ keep = max(0, min(KEEP_MAX, math.floor(KEEP_RATIO * threshold)))
+ return Budget(window, limit, output, margin, threshold, keep, _estimate(request, transcript, anchor))
+
+
+# --- clearing (context.md section 4) ------------------------------------------------
+
+
+def _skill(entry: ContextEntry) -> Optional[SkillRef]:
+ details = entry.payload.get("details")
+ skill = details.get("skill") if isinstance(details, Mapping) else None
+ if isinstance(skill, Mapping) and isinstance(skill.get("name"), str) and isinstance(skill.get("revision"), str):
+ return SkillRef(skill["name"], skill["revision"])
+ return None
+
+
+def clearable_results(view: ContextView) -> tuple[ContextEntry, ...]:
+ """The tool results to clear now, or none when clearing them would free under 20,000 tokens."""
+ inputs = [index for index, unit in enumerate(view.units) if unit.lead.kind == "input"]
+ protected_from = inputs[-CLEAR_PROTECTED_TURNS] if len(inputs) >= CLEAR_PROTECTED_TURNS else 0
+ eligible: list[tuple[int, ContextEntry, ToolResultMessage]] = []
+ for index, unit in enumerate(view.units):
+ for entry, message in unit.entries[1:]:
+ if (
+ entry is not None
+ and isinstance(message, ToolResultMessage)
+ and message.tool_name in CLEARABLE_TOOLS
+ and entry.row_id not in view.edited
+ and _skill(entry) is None
+ ):
+ eligible.append((index, entry, message))
+ candidates = [item for item in eligible[: max(0, len(eligible) - CLEAR_KEEP_RESULTS)] if item[0] < protected_from]
+ placeholder = text_tokens(CLEARED_PLACEHOLDER)
+ freed = sum(message_tokens(message) - placeholder for _, _, message in candidates)
+ return tuple(entry for _, entry, _ in candidates) if freed >= CLEAR_MIN_TOKENS else ()
+
+
+def clear_edit(entry: ContextEntry) -> dict[str, Any]:
+ return {
+ "version": 1,
+ "target_event_id": entry.row_id,
+ "replacement": {"text": CLEARED_PLACEHOLDER},
+ "reason": "clear_old_tool_result",
+ }
+
+
+# --- cut points (context.md section 5) ----------------------------------------------
+
+
+def unit_tokens(unit: Unit) -> int:
+ return messages_tokens(unit.messages)
+
+
+def normal_cut(units: Sequence[Unit], keep: int) -> Optional[int]:
+ """Index of the first kept unit: the longest tail of whole units within ``keep``, at least the last.
+
+ None when the head would be empty.
+ """
+ if not units:
+ return None
+ cut = len(units) - 1
+ kept = unit_tokens(units[cut])
+ while cut > 0 and kept + unit_tokens(units[cut - 1]) <= keep:
+ cut -= 1
+ kept += unit_tokens(units[cut])
+ return cut or None
+
+
+def half_cut(units: Sequence[Unit]) -> Optional[int]:
+ """The cut nearest to half the tokens, never past the last unit; None when only one unit is left."""
+ if len(units) < 2:
+ return None
+ sizes = [unit_tokens(unit) for unit in units]
+ half = sum(sizes) / 2
+ best, before = 1, sizes[0]
+ best_distance = abs(before - half)
+ for cut in range(2, len(units)):
+ before += sizes[cut - 1]
+ if abs(before - half) < best_distance:
+ best, best_distance = cut, abs(before - half)
+ return best
+
+
+def rolling_cut(units: Sequence[Unit], fits: Callable[[int], bool]) -> Optional[int]:
+ """The largest cut at or before ``half_cut`` whose forked request over the head fits."""
+ cut = half_cut(units)
+ while cut is not None and cut > 0:
+ if fits(cut):
+ return cut
+ cut -= 1
+ return None
+
+
+# --- the checkpoint (context.md sections 6 and 7) ----------------------------------
+
+
+def checkpoint_request(focus: Optional[str] = None) -> UserMessage:
+ parts = [CHECKPOINT_REQUEST]
+ if focus and focus.strip():
+ parts.append(CHECKPOINT_FOCUS.format(focus=focus.strip()))
+ parts.append(CHECKPOINT_REQUEST_END)
+ return UserMessage((text("\n".join(parts)),))
+
+
+def checkpoint_text(message: AssistantMessage) -> str:
+ return "\n\n".join(
+ block.text.strip() for block in message.content if isinstance(block, TextBlock) and block.text and block.text.strip()
+ )
+
+
+def _input_text(message: UserMessage) -> str:
+ parts = []
+ for block in message.content:
+ if isinstance(block, TextBlock) and block.text is not None:
+ parts.append(block.text)
+ elif isinstance(block, ImageBlock):
+ parts.append(f"[image: {block.name or block.mime_type}]")
+ return "\n".join(parts)
+
+
+def _unique(items: Sequence[str]) -> list[str]:
+ return list(dict.fromkeys(items))
+
+
+def _files(previous: Mapping[str, Any], head: Sequence[Unit]) -> tuple[list[str], list[str]]:
+ """Cumulative artifacts: the path of each call that succeeded (no hook rewrites arguments under C-9)."""
+ read: list[str] = list(previous.get("files_read", ()))
+ modified: list[str] = list(previous.get("files_modified", ()))
+ for unit in head:
+ message = unit.lead.message
+ if not isinstance(message, AssistantMessage):
+ continue
+ for call, (entry, result) in zip(message.tool_calls, unit.entries[1:]):
+ path = call.arguments.get("path")
+ if entry is None or result.is_error or not isinstance(path, str) or not path:
+ continue
+ if call.name == "read":
+ read.append(path)
+ elif call.name in {"write", "edit"}:
+ modified.append(path)
+ modified = _unique(modified)
+ changed = set(modified)
+ return [path for path in _unique(read) if path not in changed], modified
+
+
+def carried_skills(view: ContextView, cut: int) -> tuple[SkillRef, ...]:
+ """Skills loaded before the cut (and carried by the previous checkpoint), minus those loaded after it."""
+ loaded: dict[str, str] = {}
+ previous = view.compaction.payload if view.compaction is not None else {}
+ for skill in previous.get("skills", ()):
+ loaded.pop(skill["name"], None)
+ loaded[skill["name"]] = skill["revision"]
+ for unit in view.units[:cut]:
+ for entry, _ in unit.entries[1:]:
+ skill = _skill(entry) if entry is not None else None
+ if skill is not None:
+ loaded.pop(skill.name, None)
+ loaded[skill.name] = skill.revision
+ for unit in view.units[cut:]:
+ for entry, _ in unit.entries[1:]:
+ skill = _skill(entry) if entry is not None else None
+ if skill is not None:
+ loaded.pop(skill.name, None)
+ return tuple(SkillRef(name, revision) for name, revision in loaded.items())
+
+
+def summarized_to_seq(view: ContextView, cut: int) -> int:
+ previous = view.compaction.payload.get("summarized_to_seq", 0) if view.compaction is not None else 0
+ seqs = [entry.context_seq for unit in view.units[:cut] for entry, _ in unit.entries if entry is not None]
+ return max([previous, *seqs])
+
+
+def render_summary(
+ *,
+ checkpoint: str,
+ files_read: Sequence[str],
+ files_modified: Sequence[str],
+ earlier_record: Optional[str],
+ current_request: Optional[str],
+) -> str:
+ lines = ["<context-checkpoint>"]
+ if checkpoint:
+ lines += [CHECKPOINT_FRAMING, "", checkpoint, ""]
+ lines.append("<artifacts>")
+ for label, paths in (("Read", files_read), ("Modified", files_modified)):
+ lines += [f"{label}:", *(f"- {path}" for path in paths)] if paths else [f"{label}: (none)"]
+ lines.append("</artifacts>")
+ if earlier_record:
+ lines += ["<earlier-record>", EARLIER_RECORD_LEAD, earlier_record, "</earlier-record>"]
+ if current_request is not None:
+ lines += ["<current-request>", current_request, "</current-request>"]
+ lines.append("</context-checkpoint>")
+ return "\n".join(lines)
+
+
+def compaction_payload(
+ view: ContextView,
+ cut: int,
+ *,
+ mode: str,
+ reason: str,
+ focus: Optional[str],
+ checkpoint: str,
+ skills: Sequence[SkillRef],
+ state: Sequence[str],
+ earlier_record: Optional[str],
+ tokens_before: int,
+ threshold: int,
+ summarizer: Optional[Mapping[str, Any]],
+ usage: Optional[Usage],
+) -> dict[str, Any]:
+ """The ``Compaction`` row for a cut before ``view.units[cut]``; ``tokens_after_estimate`` is the caller's."""
+ previous_row = view.compaction
+ previous = previous_row.payload if previous_row is not None else {}
+ head = view.units[:cut]
+ read, modified = _files(previous, head)
+ request_id: Optional[str] = None
+ request: Optional[str] = None
+ if view.units[cut].lead.kind != "input":
+ inputs = [unit.lead for unit in head if unit.lead.kind == "input"]
+ if inputs:
+ request_id, request = inputs[-1].row_id, _input_text(inputs[-1].message)
+ else:
+ request_id, request = previous.get("current_request_message_id"), previous.get("current_request")
+ payload: dict[str, Any] = {
+ "version": 1,
+ "mode": mode,
+ "reason": reason,
+ "focus": focus,
+ "summary": render_summary(
+ checkpoint=checkpoint,
+ files_read=read,
+ files_modified=modified,
+ earlier_record=earlier_record,
+ current_request=request,
+ ),
+ "checkpoint": checkpoint,
+ "state": list(state),
+ "first_kept_seq": view.units[cut].seq,
+ "summarized_to_seq": summarized_to_seq(view, cut),
+ "previous_compaction_id": previous_row.row_id if previous_row is not None else None,
+ "current_request": request,
+ "current_request_message_id": request_id,
+ "files_read": read,
+ "files_modified": modified,
+ "skills": [{"name": skill.name, "revision": skill.revision} for skill in skills],
+ "tokens_before": tokens_before,
+ "tokens_after_estimate": 0,
+ "threshold": threshold,
+ "summarizer": dict(summarizer) if summarizer is not None else None,
+ }
+ if usage is not None:
+ payload["usage"] = usage_to_dict(usage)
+ return payload
diff --git a/core/agent_core/harness/projection.py b/core/agent_core/harness/projection.py
index dc769dbef..bcfcabf3d 100644
--- a/core/agent_core/harness/projection.py
+++ b/core/agent_core/harness/projection.py
@@ -1,17 +1,20 @@
-"""C-5 projection before P3 context management.
+"""C-5 projection, with C-9 checkpoints and cleared tool results.
The store supplies rows including fork ancestry. Projection sorts and copies
-them, restores hook state, and repairs orphan calls without executing tools or
-writing rows. System text and rehydrated messages are supplied by the caller.
-No job host or external settler is consulted. Resume settlement is the separate
-write step in ``agent.recovery``; any remaining orphan gets deterministic text.
+them, restores loop state, applies the latest checkpoint and every context
+edit, and repairs orphan calls without executing tools or writing rows.
+System text and hook-rehydrated messages are supplied by the caller; a
+checkpoint's own text and state were fixed when its row was written, so the
+result is a pure function of the rows. No job host or external settler is
+consulted. Resume settlement is the separate write step in ``agent.recovery``;
+any remaining orphan gets deterministic text.
"""
from __future__ import annotations
from copy import deepcopy
-from dataclasses import dataclass, field
-from typing import Any, Literal, Mapping, Optional, Sequence
+from dataclasses import dataclass, field, replace
+from typing import Any, Callable, Literal, Mapping, Optional, Sequence
from core.agent_core.harness.store import ContextEntry
from core.agent_core.messages import (
@@ -20,8 +23,11 @@ from core.agent_core.messages import (
TextBlock,
ToolCallBlock,
ToolResultMessage,
+ UserMessage,
+ origin_from_dict,
require_json_value,
text,
+ usage_from_dict,
)
# C-1 cross-provider.md; also Pi (MIT), packages/ai/src/utils/transform-messages.ts.
@@ -38,6 +44,49 @@ class Projection:
messages: tuple[Message, ...]
context_seq: int
state: Mapping[str, Any] = field(default_factory=dict)
+ #: Context-management guard state (``AgentState.context``), restored like hook state.
+ context_state: Mapping[str, Any] = field(default_factory=dict)
+
+
+@dataclass(frozen=True)
+class Unit:
+ """An input, or a response with the results of its calls: what a cut keeps whole (C-9 section 5).
+
+ ``entries`` pairs every projected message with its row; a synthesized
+ interrupted result has none.
+ """
+
+ seq: int
+ entries: tuple[tuple[Optional[ContextEntry], Message], ...]
+
+ @property
+ def lead(self) -> ContextEntry:
+ entry = self.entries[0][0]
+ assert entry is not None
+ return entry
+
+ @property
+ def messages(self) -> tuple[Message, ...]:
+ return tuple(message for _, message in self.entries)
+
+
+@dataclass(frozen=True)
+class ContextView:
+ """The context after the latest checkpoint, in units, with what the C-9 rules read."""
+
+ compaction: Optional[ContextEntry]
+ checkpoint: Optional[UserMessage]
+ units: tuple[Unit, ...]
+ #: Row ids of tool results a ``context_edit`` replaced.
+ edited: frozenset[str]
+ context_seq: int
+ state: Mapping[str, Any]
+ context_state: Mapping[str, Any]
+
+ @property
+ def messages(self) -> tuple[Message, ...]:
+ head = (self.checkpoint,) if self.checkpoint is not None else ()
+ return head + tuple(message for unit in self.units for message in unit.messages)
def interrupted_result(call: ToolCallBlock) -> ToolResultMessage:
@@ -54,13 +103,15 @@ def _ordered(entries: Sequence[ContextEntry], fork_point: Optional[int] = None)
if row.context_seq <= previous_seq:
raise ProjectionError(f"duplicate context_seq: {row.context_seq}")
previous_seq = row.context_seq
- if row.kind in {"compaction", "context_edit"}:
- raise ProjectionError(f"{row.kind} requires P3 context management (row {row.row_id})")
- if row.kind == "agent_state":
- if row.payload.get("version") != 1 or not isinstance(row.payload.get("state"), dict):
- raise ProjectionError(f"unsupported agent_state payload (row {row.row_id})")
+ shape = _PAYLOAD_SHAPES.get(row.kind)
+ if shape is not None:
+ # Every field a later step reads is checked here, so a malformed row fails at load.
+ if not shape(row.payload) or (row.kind == "compaction" and row.payload["first_kept_seq"] > row.context_seq):
+ raise ProjectionError(f"unsupported {row.kind} payload (row {row.row_id})")
elif row.message is None:
raise ProjectionError(f"{row.kind} has no message (row {row.row_id})")
+ elif row.kind == "response" and "request" in row.payload and not _REQUEST_FACTS(row.payload["request"]):
+ raise ProjectionError(f"unsupported response request facts (row {row.row_id})")
if row.message is not None and any(
isinstance(block, TextBlock) and block.ref is not None for block in row.message.content
):
@@ -78,17 +129,116 @@ def _ordered(entries: Sequence[ContextEntry], fork_point: Optional[int] = None)
return rows
+# --- persisted payload shapes (transcript-rows.schema.json) --------------------
+
+Check = Callable[[Any], bool]
+
+
+def _object(required: Mapping[str, Check], optional: Mapping[str, Check] = {}) -> Check:
+ """An exact JSON object: no unknown key, every required key present, every value valid."""
+
+ def check(value: Any) -> bool:
+ if not isinstance(value, Mapping) or set(value) - set(required) - set(optional):
+ return False
+ if any(key not in value for key in required):
+ return False
+ return all(test(value[key]) for key, test in {**required, **optional}.items() if key in value)
+
+ return check
+
+
+def _reads(reader: Callable[[Any], Any]) -> Check:
+ """Valid when the foundation's own reader accepts it."""
+
+ def check(value: Any) -> bool:
+ try:
+ reader(value)
+ except (TypeError, ValueError):
+ return False
+ return True
+
+ return check
+
+
+def _one_of(*values: Any) -> Check:
+ return lambda value: any(type(value) is type(item) and value == item for item in values)
+
+
+def _nullable(check: Check) -> Check:
+ return lambda value: value is None or check(value)
+
+
+def _list(check: Check) -> Check:
+ return lambda value: isinstance(value, list) and all(check(item) for item in value)
+
+
+def _string(value: Any) -> bool:
+ return isinstance(value, str)
+
+
+def _integer(value: Any) -> bool:
+ return type(value) is int
+
+
+def _count(value: Any) -> bool:
+ return type(value) is int and value >= 0
+
+
+#: ``ModelResponse.request``: what C-9 records about the request a response answered.
+_REQUEST_FACTS = _object({"tokens": _count})
+_PAYLOAD_SHAPES: dict[str, Check] = {
+ "compaction": _object(
+ {
+ "version": _one_of(1),
+ "mode": _one_of("normal", "rolling", "dropped"),
+ "reason": _one_of("manual", "threshold", "overflow"),
+ "summary": _string,
+ "checkpoint": _string,
+ "state": _list(_string),
+ "first_kept_seq": lambda value: _integer(value) and value > 0,
+ "summarized_to_seq": _count,
+ "files_read": _list(_string),
+ "files_modified": _list(_string),
+ "skills": _list(_object({"name": _string, "revision": _string})),
+ "tokens_before": _count,
+ "tokens_after_estimate": _count,
+ "threshold": _integer,
+ },
+ {
+ "focus": _nullable(_string),
+ "previous_compaction_id": _nullable(_string),
+ "current_request": _nullable(_string),
+ "current_request_message_id": _nullable(_string),
+ "summarizer": _nullable(
+ _object({"origin": _reads(origin_from_dict), "prompt_version": _string, "rounds": _count})
+ ),
+ "usage": _reads(usage_from_dict),
+ },
+ ),
+ "context_edit": _object(
+ {
+ "version": _one_of(1),
+ "target_event_id": _string,
+ "replacement": _object({"text": _string}),
+ "reason": _one_of("clear_old_tool_result"),
+ }
+ ),
+ "agent_state": _object(
+ {"version": _one_of(1), "state": lambda value: isinstance(value, dict)},
+ {"context": _object({"failures": _count, "ineffective": _count, "paused": lambda value: type(value) is bool})},
+ ),
+}
+
+
def _index_results(
rows: Sequence[ContextEntry],
-) -> tuple[dict[tuple[int, str], ToolResultMessage], dict[str, tuple[ContextEntry, ToolCallBlock]]]:
+) -> tuple[dict[tuple[int, str], ContextEntry], dict[str, tuple[ContextEntry, ToolCallBlock]]]:
"""Associate late recovery rows with their original response, in row order."""
pending: dict[str, tuple[ContextEntry, ToolCallBlock]] = {}
- results: dict[tuple[int, str], ToolResultMessage] = {}
+ results: dict[tuple[int, str], ContextEntry] = {}
seen: set[str] = set()
for row in rows:
- if row.kind == "agent_state":
- continue
message = row.message
if isinstance(message, ToolResultMessage):
owner = pending.pop(message.tool_call_id, None)
@@ -99,7 +249,7 @@ def _index_results(
response, call = owner
if message.tool_name != call.name:
raise ProjectionError(f"result identity does not match call {call.id}")
- results[response.context_seq, call.id] = message
+ results[response.context_seq, call.id] = row
elif isinstance(message, AssistantMessage):
for call in message.tool_calls:
if call.id in pending:
@@ -115,36 +265,82 @@ def open_tool_calls(entries: Sequence[ContextEntry]) -> tuple[tuple[ContextEntry
return tuple(deepcopy(list(pending.values())))
-def project(
- entries: Sequence[ContextEntry],
- *,
- system: str = "",
- rehydrated: Sequence[Message] = (),
- fork_point: Optional[int] = None,
-) -> Projection:
- """Project committed ancestry, with an optional inclusive fork cut.
+def context_view(entries: Sequence[ContextEntry], *, fork_point: Optional[int] = None) -> ContextView:
+ """The context in units: the latest checkpoint's message, then the rows from its ``first_kept_seq``.
- Results (including late recovery rows) are placed immediately after their
- response in call order. A missing result always gets INTERRUPTED. Neither
- projection nor the returned detached objects can change persisted rows.
+ Results (including late recovery rows) follow their response in call
+ order; a missing result is INTERRUPTED; a result whose call was summarized
+ leaves with it. The latest edit of a tool result replaces its content.
"""
rows = _ordered(entries, fork_point)
results, _ = _index_results(rows)
- messages: list[Message] = list(rehydrated)
+ rows_by_id = {row.row_id: row for row in rows}
state: Mapping[str, Any] = {}
+ context_state: Mapping[str, Any] = {}
+ compaction: Optional[ContextEntry] = None
+ edits: dict[str, str] = {}
for row in rows:
if row.kind == "agent_state":
state = row.payload["state"]
+ # Only C-9's own commits carry the guard state; a hook-state row leaves it as it was.
+ context_state = row.payload.get("context", context_state)
+ elif row.kind == "compaction":
+ compaction = row
+ elif row.kind == "context_edit":
+ target = rows_by_id.get(row.payload["target_event_id"])
+ if target is None or target.kind != "tool_result" or target.context_seq >= row.context_seq:
+ raise ProjectionError(f"context_edit row {row.row_id} targets no earlier tool result")
+ edits[target.row_id] = row.payload["replacement"]["text"]
+ first_kept = compaction.payload["first_kept_seq"] if compaction is not None else 0
+ units: list[Unit] = []
+ for row in rows:
+ if row.kind not in {"input", "response"} or row.context_seq < first_kept:
continue
message = row.message
- if isinstance(message, ToolResultMessage):
- continue
- if message is not None:
- messages.append(message)
+ entries_of_unit: list[tuple[Optional[ContextEntry], Message]] = [(row, message)]
if isinstance(message, AssistantMessage):
for call in message.tool_calls:
- messages.append(results.get((row.context_seq, call.id), interrupted_result(call)))
- return Projection(system, tuple(deepcopy(messages)), rows[-1].context_seq if rows else 0, deepcopy(state))
+ result = results.get((row.context_seq, call.id))
+ if result is None:
+ entries_of_unit.append((None, interrupted_result(call)))
+ continue
+ projected = result.message
+ if result.row_id in edits:
+ projected = replace(projected, content=(text(edits[result.row_id]),))
+ entries_of_unit.append((result, projected))
+ units.append(Unit(row.context_seq, tuple(entries_of_unit)))
+ checkpoint = None
+ if compaction is not None:
+ checkpoint = UserMessage(
+ (text(compaction.payload["summary"]), *(text(item) for item in compaction.payload["state"]))
+ )
+ return ContextView(
+ compaction=compaction,
+ checkpoint=checkpoint,
+ units=tuple(deepcopy(units)),
+ edited=frozenset(edits),
+ context_seq=rows[-1].context_seq if rows else 0,
+ state=deepcopy(state),
+ context_state=deepcopy(context_state),
+ )
+
+
+def project(
+ entries: Sequence[ContextEntry],
+ *,
+ system: str = "",
+ rehydrated: Sequence[Message] = (),
+ fork_point: Optional[int] = None,
+) -> Projection:
+ """Project committed ancestry, with an optional inclusive fork cut.
+
+ Rehydrated messages come first, then the latest checkpoint's message, then
+ the kept rows (``context_view``). Neither projection nor the returned
+ detached objects can change persisted rows.
+ """
+ view = context_view(entries, fork_point=fork_point)
+ messages = (*deepcopy(tuple(rehydrated)), *view.messages)
+ return Projection(system, messages, view.context_seq, view.state, view.context_state)
def validate_message_append(
diff --git a/core/agent_core/harness/store.py b/core/agent_core/harness/store.py
index d02ec5b74..5cfec7071 100644
--- a/core/agent_core/harness/store.py
+++ b/core/agent_core/harness/store.py
@@ -1,8 +1,11 @@
"""C-5 transcript store interface (``agent-core-contracts/transcript.md``).
-The loop is the single writer of a Session's context. Each method commits one
-context entry and returns it with its ``context_seq``; the adapter implements
-this over the ``messages`` and ``agent_events`` tables.
+The loop is the single writer of a Session's context. ``load`` reads it; the
+other writes commit one context entry and return it with its ``context_seq``,
+except ``append_payloads`` (several entries in one transaction) and
+``append_audit`` (a non-context row; its id). The SQLite store implements this
+over the ``messages`` and ``agent_events`` tables, and one contract suite runs
+the same tests on it and on the in-memory store (C-5 ``transcript.md`` §2).
"""
from __future__ import annotations
@@ -21,7 +24,10 @@ class ContextEntry:
``row_id`` is ``messages.id`` for inputs and responses, ``agent_events.id``
otherwise. ``message`` is set for inputs, responses, and tool results;
- ``payload`` carries the versioned shape of the other kinds.
+ ``payload`` carries the versioned shape of the other kinds. ``created_at``
+ is the row's commit time in epoch seconds; every store sets it, as written
+ and as loaded, and C-9 reads a response's to tell whether the provider
+ cache has gone cold.
"""
session_id: str
@@ -30,6 +36,7 @@ class ContextEntry:
row_id: str
message: Optional[Message] = None
payload: Mapping[str, Any] = field(default_factory=dict)
+ created_at: Optional[float] = None
class TranscriptStore(Protocol):
@@ -41,7 +48,14 @@ class TranscriptStore(Protocol):
"""Admit an already stored input row into the context as rendered for the model."""
...
- async def append_response(self, session_id: str, message: AssistantMessage, *, final: bool) -> ContextEntry: ...
+ async def append_response(
+ self, session_id: str, message: AssistantMessage, *, final: bool, request: Optional[Mapping[str, Any]] = None
+ ) -> ContextEntry:
+ """Commit a response; ``request`` (C-9 ``ModelResponse.request``) is stored with it and read back in ``payload``.
+
+ The loop passes ``request`` only when context management is on.
+ """
+ ...
async def append_tool_result(
self, session_id: str, message: ToolResultMessage, *, details: Mapping[str, Any]
@@ -50,3 +64,15 @@ class TranscriptStore(Protocol):
async def append_payload(
self, session_id: str, kind: Literal["compaction", "context_edit", "agent_state"], payload: Mapping[str, Any]
) -> ContextEntry: ...
+
+ async def append_payloads(
+ self, session_id: str, entries: Sequence[tuple[Literal["compaction", "context_edit", "agent_state"], Mapping[str, Any]]]
+ ) -> Sequence[ContextEntry]:
+ """Commit several payload entries in order, in one transaction: all of them or none (C-9 section 10)."""
+ ...
+
+ async def append_audit(
+ self, session_id: str, kind: Literal["checkpoint_turn", "attempt"], payload: Mapping[str, Any]
+ ) -> str:
+ """An audit row outside the context (C-9 ``CheckpointTurn`` or ``ModelAttempt``); its id."""
+ ...
diff --git a/core/agent_core/messages.py b/core/agent_core/messages.py
index 9d7eb409f..b82413448 100644
--- a/core/agent_core/messages.py
+++ b/core/agent_core/messages.py
@@ -351,7 +351,7 @@ def _block_from_dict(data: Any, allowed_types: tuple[str, ...]) -> Any:
_USAGE_REQUIRED = {"input_tokens": int, "output_tokens": int, "cache_read_tokens": int, "cache_write_tokens": int}
-def _usage_to_dict(usage: Usage) -> dict[str, Any]:
+def usage_to_dict(usage: Usage) -> dict[str, Any]:
out: dict[str, Any] = {name: getattr(usage, name) for name in _USAGE_REQUIRED}
_put(out, "reasoning_tokens", usage.reasoning_tokens)
return out
@@ -376,7 +376,7 @@ def message_to_dict(message: Message) -> dict[str, Any]:
"stop_reason": message.stop_reason,
}
if message.usage is not None:
- out["usage"] = _usage_to_dict(message.usage)
+ out["usage"] = usage_to_dict(message.usage)
_put(out, "error_message", message.error_message)
return out
if isinstance(message, ToolResultMessage):
diff --git a/docs/plans/agent-core-contracts/README.md b/docs/plans/agent-core-contracts/README.md
index 886a85bc2..2d79fc962 100644
--- a/docs/plans/agent-core-contracts/README.md
+++ b/docs/plans/agent-core-contracts/README.md
@@ -15,7 +15,7 @@ on it fork; after that, a change needs orchestrator approval and lands here firs
| C-7 | Tools, output governance, job handle | `tools` → `agent`, adapter | [`tools.md`](tools.md), [`job.schema.json`](job.schema.json) | P1 |
| C-8 | Backend registration | catalog → every backend list | [`backend-registration.md`](backend-registration.md) | P2 |
| C-5, C-7 | Recovery invariants for jobs, tool calls, and delivery, with owners and proofs | `tools`, `loop`, adapter | [`recovery.md`](recovery.md) | P1 |
-| C-9 | Context management (draft, not frozen) | `harness` → `agent`, adapter | plan §5.2; rows in [`transcript-rows.schema.json`](transcript-rows.schema.json) | P3 |
+| C-9 | Context management: tiers, trigger, cut, forked checkpoint, overflow ladder, guards | `harness` → `agent`, adapter | [`context.md`](context.md); rows in [`transcript-rows.schema.json`](transcript-rows.schema.json) | P3 (frozen 2026-10-04) |
Conventions:
diff --git a/docs/plans/agent-core-contracts/agent-event.schema.json b/docs/plans/agent-core-contracts/agent-event.schema.json
index 20af67313..682f4e3b6 100644
--- a/docs/plans/agent-core-contracts/agent-event.schema.json
+++ b/docs/plans/agent-core-contracts/agent-event.schema.json
@@ -23,6 +23,9 @@
"compaction_started",
"compaction_finished",
"compaction_failed",
+ "compaction_skipped",
+ "compaction_paused",
+ "context_exhausted",
"run_ended",
"error"
]
@@ -208,6 +211,7 @@
"required": [
"event_id",
"reason",
+ "mode",
"tokens_before",
"tokens_after_estimate"
],
@@ -222,6 +226,13 @@
"overflow"
]
},
+ "mode": {
+ "enum": [
+ "normal",
+ "rolling",
+ "dropped"
+ ]
+ },
"tokens_before": {
"type": "integer",
"minimum": 0
@@ -284,6 +295,101 @@
}
}
},
+ {
+ "if": {
+ "properties": {
+ "type": {
+ "const": "compaction_skipped"
+ }
+ }
+ },
+ "then": {
+ "description": "A manual compaction found nothing older than the kept tail to summarize (context.md section 10). The adapter replies that there is nothing to compact yet; the run ends `completed`.",
+ "required": [
+ "reason"
+ ],
+ "properties": {
+ "reason": {
+ "enum": [
+ "manual"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "if": {
+ "properties": {
+ "type": {
+ "const": "compaction_paused"
+ }
+ }
+ },
+ "then": {
+ "description": "Auto-compaction paused for the Session (context.md section 10); emitted once, at the transition. The adapter tells the user.",
+ "required": [
+ "cause"
+ ],
+ "properties": {
+ "cause": {
+ "enum": [
+ "failures",
+ "ineffective"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "if": {
+ "properties": {
+ "type": {
+ "const": "context_exhausted"
+ }
+ }
+ },
+ "then": {
+ "description": "The overflow ladder could not make the request fit (context.md section 8 d): what fills the context, for the adapter's stop message. The run then ends `context_exhausted`.",
+ "required": [
+ "limit",
+ "parts"
+ ],
+ "properties": {
+ "limit": {
+ "type": "integer",
+ "description": "L_in of the hop."
+ },
+ "parts": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": [
+ "name",
+ "tokens"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "name": {
+ "enum": [
+ "system",
+ "tools",
+ "history",
+ "current_request",
+ "latest_tool_batch",
+ "output"
+ ]
+ },
+ "tokens": {
+ "type": "integer",
+ "minimum": 0
+ }
+ }
+ },
+ "description": "Estimated tokens of the request's parts: `history` is everything before the last unit (the checkpoint included), the last unit is `current_request` (an input) or `latest_tool_batch` (a response and its results), and `output` is the reserved max_tokens plus the margin M."
+ }
+ }
+ }
+ },
{
"if": {
"properties": {
diff --git a/docs/plans/agent-core-contracts/context.md b/docs/plans/agent-core-contracts/context.md
new file mode 100644
index 000000000..be51b4a91
--- /dev/null
+++ b/docs/plans/agent-core-contracts/context.md
@@ -0,0 +1,401 @@
+# C-9 Context management
+
+Frozen 2026-10-04 by owner decision. The `harness` owns the rules (`core/agent_core/harness/context.py`,
+`projection.py`); the loop applies them before every model request (`core/agent_core/agent/loop.py`); the adapter
+supplies the Session-specific parts (§9). Row shapes: [`transcript-rows.schema.json`](transcript-rows.schema.json);
+events: [`agent-event.schema.json`](agent-event.schema.json).
+
+Three tiers, cheapest first:
+
+1. **Output governance at write time** (C-7): no tool result exceeds 2,000 lines / 50 KB.
+2. **Clearing old tool results**, recorded as `context_edit` rows (§4). On by default.
+3. **Checkpoint**, recorded as a `context_compaction` row, written by the model in a forked request (§5–§7).
+
+Compaction and clearing only append rows; they never rewrite or delete one. A fork anchored before a checkpoint
+projects the full original context (C-5 §4).
+
+## 1. Limits
+
+The hop capabilities Model Hub returns for the route resolved for the request (C-6) give the limits. `O` is set
+when the request is built, as its `max_tokens` (`output_tokens()`, `checkpoint_max_tokens()`). One pure function,
+`harness/context.budget(request, capabilities, transcript, anchor)`, derives `W, L_in, M, T, keep` and the request's
+`est` (§2) and reads `O` from the request, once per request (§10, invariant 1). No state keeps these values between
+requests, so a route change is picked up at once; a smaller window than expected is handled by the overflow path
+(§8). Every fit decision is `budget()` on a request actually composed (§10, invariant 1), including the two the
+stage only considers: the fork it would send first, and the minimal request of the stop check.
+
+```text
+W = context_window (128,000 when unknown)
+L_in = input_limit (W when unknown)
+O = the request's max_tokens: for a conversation request max_output_tokens (8,192 when unknown), capped by the
+ Agent's output budget; for a checkpoint request min(16,000, that)
+M = max(8,000, ceil(0.03 * W))
+T = min(L_in - O - M, floor(0.9 * W)) the compaction threshold
+keep = min(20,000, floor(0.25 * T)) the verbatim tail of a normal checkpoint
+```
+
+A conversation request **fits** when `est + O + M <= L_in`, where `est` is its estimate (§2); `M` absorbs the
+estimate's error. A request **can fit** when `est + O <= L_in`. A checkpoint request (§6) is sent only when it can
+fit: at `est = T` it uses a few hundred tokens of `M` for the checkpoint request, and the provider remains the judge.
+
+## 2. Token estimate
+
+`tokens(x) = ceil(utf8_bytes(x) / 4)`: characters / 4 undercounts Chinese by about 65%, UTF-8 bytes / 4 is within 6%.
+A message counts its text, its thinking text and signature (replayed reasoning payloads), each tool call's name,
+JSON arguments, and signature, and 1,600 tokens per image.
+
+The **anchor** is the latest response in the context that neither failed nor was aborted, reports non-zero usage,
+and records the request it answered on its row (`ModelResponse.request.tokens`: `tokens()` of that whole request as
+sent). It is rebuilt from the rows, so it holds across a new Agent and a new Turn.
+
+```text
+est = usage(R) + tokens(this request) - R.request.tokens - tokens(R) while the anchor R holds
+ = tokens(this request) otherwise
+usage(R) = input_tokens + cache_read_tokens + cache_write_tokens + output_tokens
+```
+
+The anchor holds while (a) this request goes to the route that answered it (`R.origin` equals the request
+endpoint's origin, because tokenizers differ), and (b) the transcript up to `R` is unchanged: the messages the rows
+put before `R` now are the ones they put before it when `R`'s request was built, and `R` follows them. A checkpoint,
+or an edit of a result before `R`, breaks (b). A changed system prompt, tool set, or rehydrated state
+does not invalidate the anchor: the difference between this request's `tokens()` and `R.request.tokens` carries it.
+So does anything after `R`, an edit there included.
+
+## 3. Before every model request
+
+Every conversation request takes the request pipeline (§10, invariant 1). Its C-9 stage, inside the tool loop and
+before a retry alike:
+
+1. **Stop** (§8 d) when the request cannot fit and neither can its minimal request: the request the drop (§8 c)
+ would leave with everything but the last unit moved out (the drop's own row, with its `state` and, when the cut
+ splits a turn, its `<current-request>` copy, §5), budgeted without the anchor (its history would be gone). With
+ fewer than two units nothing can move out, and the minimal request is the request itself. The provider never
+ sees the request.
+2. **Clear** (§4) when the provider cache is cold (no model request for longer than the cache TTL, 300 s by
+ default; after a restart, measured from the latest response row's `created_at`) or `est >= 0.8 * T`.
+3. **Checkpoint** when `est >= T`, auto-compaction is not paused (§10), and there is something to summarize, at most
+ once per model request: a normal checkpoint (§6, reason `threshold`) when the fork it would send can fit,
+ otherwise the overflow ladder from (b) (§8, reason `overflow`). A checkpoint request that overflows continues at
+ (b).
+4. **Ladder** (§8) when the request does not fit. With no checkpoint request left to try (one failed for this
+ request other than by overflow, or auto-compaction is paused), a request that can fit is sent and the provider
+ judges.
+
+A request the provider rejects as overflow (`ProviderError.kind == "overflow"`, classified by
+`ai/errors.is_overflow_message`, HTTP 413, and `context_length_exceeded`) before anything was streamed, and with no
+content in its partial, enters the overflow ladder (§8) and is rebuilt and sent again. Any other overflow is never
+retried, even when the adapter reports no partial, since the user may have seen what was streamed: a partial with
+content is committed as a non-final response, and the run ends `context_exhausted`. A checkpoint turn's own
+requests (§6) never run this stage (no clearing, checkpoint, or ladder; one compaction is in flight per Session);
+each is sent only when it can fit.
+
+## 4. Clearing old tool results
+
+- Eligible: results of `read` and `bash` in the projected context (terminal screen snapshots join when they exist).
+- Protected: results after the second-latest input (the last 2 user turns; with fewer than 2 inputs since the latest
+ checkpoint, all of them), the newest 5 eligible results, skill loads (a result whose `details.skill` is set), and
+ results already cleared. Results before the latest checkpoint are not in the context.
+- Applied only when the candidates free at least 20,000 tokens, all at once, one `context_edit` row per result:
+ `{"target_event_id": <tool_result row id>, "replacement": {"text": PLACEHOLDER}, "reason": "clear_old_tool_result"}`.
+- `PLACEHOLDER` = `[Old tool result cleared to save context. Re-run the tool or re-read the file if you need it again.]`
+- Projection keeps the call id, name, and error flag, and replaces the content with the placeholder. The latest
+ edit of a target wins.
+
+## 5. Cut point
+
+The projected context after the latest checkpoint is a list of **units**: an input, or a response together with the
+results of its tool calls. A cut falls only before a unit: before a user message, or before an assistant message
+whose tool batch follows it; never at a tool result, so no call is separated from its result.
+
+- **Normal** (threshold, manual, and the first overflow step): the tail is the longest run of whole units at the end
+ whose tokens total at most `keep`, and at least the last unit. Everything before it is the head. An empty head
+ means there is nothing to summarize.
+- **Rolling** (§8 b): the cut nearest to half the tokens, moved earlier until the forked request over the head can fit
+ (§1); never past the last unit.
+- **Dropped** (§8 c): the cut nearest to half the tokens; never past the last unit.
+
+`first_kept_seq` is the `context_seq` of the first kept unit. If that unit is not an input, the cut split a turn: the
+text of the latest input in the head, or the previous checkpoint's current request when the head has none, is copied
+verbatim into the checkpoint as `<current-request>` (images as `[image: name]`), with no model call.
+
+## 6. Checkpoint turn
+
+A checkpoint is written by a **fork** of the conversation, the only delivery path:
+
+- The request uses the same hop, system prompt, tool definitions, tool choice, and reasoning settings as the
+ conversation's next request, and its messages begin with the conversation's projected messages unchanged, so its
+ prefix is byte-identical to the previous request's and a warm provider cache hits. Tool choice, thinking, and
+ effort are never changed: Anthropic renders them into the prompt. `max_tokens = min(16,000, O)`.
+- **Normal**: the prefix is the whole projected conversation. **Rolling**: the prefix is the projected context up to
+ the cut, which is a prefix of the original request.
+- One user message is appended: the checkpoint request (§11), with `Additional focus from the user: <focus>` for
+ `/compact <focus>`.
+- The turn's requests take the request pipeline (§10, invariant 1; a request that cannot fit is never sent and
+ fails the attempt as an overflow), its responses the admission (invariant 6), and its tool calls the tool pipeline
+ (invariant 2). Its responses and results are never committed to the context, and nothing is shown to the user.
+
+**Tool policy** ("dreaming": cognition allowed, actuation blocked), a declarative table judged after the turn's
+budget (invariant 2):
+
+| Tool | Rule |
+| --- | --- |
+| `read` | allowed |
+| `write`, `edit` | allowed only for a single file name directly inside this Session's scratch root, `<state>/agent_core/scratch/<session_id>/` (the path's directory is the root; a name with a separator, `.`, or `..` is denied). Scratch is flat and is reached only through a directory descriptor: when the turn starts, it creates the root and opens it once (`O_DIRECTORY \| O_NOFOLLOW`, `fstat` a real directory; a symlink authorizes nothing). Every read, temporary file (`O_CREAT \| O_EXCL \| O_NOFOLLOW`), and publication (`os.replace` with `src_dir_fd`/`dst_dir_fd`) is relative to that descriptor, so renaming or swapping the root, or a name in it, after it was opened redirects nothing; a name is never followed, and one that is not a regular file when the call runs is refused. Where the platform cannot open and rename relative to a descriptor (Windows), scratch writes are denied and `read` stays allowed. Each scratch call runs as joined work an abort waits for, so the descriptor closes only after its worker thread is done |
+| memory-read tools | reserved: allowed once they exist |
+| `bash` and every other tool | denied, never executed |
+
+- A denied call gets the error result `This is a checkpoint turn: tools that act outside your own scratch space are
+ unavailable. Write the checkpoint now.`
+- Every request of the turn is budgeted on the route resolved for it (§1): its `max_tokens` is that route's
+ `min(16,000, O)`.
+- The bound is the window, not `T`, the same way in threshold, manual, and rolling turns. Before each call,
+ `room = L_in - est - min(16,000, O) - reserved`, where `est` is the budget of the turn's latest request plus the
+ tokens of the response and results since, and `reserved` is one fixed-text result (the longer of the two below)
+ for each later call of the same response, so every result of the batch is accounted for before it exists. This is
+ the one bound that extends the latest request's budget by arithmetic (§10, invariant 1). A call runs only while
+ `room >= 4,000` tokens, and the result of every call that runs (an unknown tool's error included) is cut to
+ `room - 1,000` tokens, head kept, ending with
+ `[Output truncated to fit this checkpoint turn: showing about <shown> of <total> tokens. Read a smaller range if
+ you need more.]`, so a single result cannot push the turn out of the window. The policy's two fixed texts (the
+ denial and the used-up budget) are a few dozen tokens and are never cut: a truncation note would invite another
+ call.
+- At most 5 tool rounds run. After them, or once `room` falls below the floor, the budget is closed: every call gets
+ `This is a checkpoint turn and its tool budget is used up. Write the checkpoint now.` before the table is
+ consulted, so the audit's `rounds` can count one more response, the one answered that way. A response that still
+ calls tools after that ends the turn as failed.
+- `write` and `edit` in a checkpoint turn keep the tools' arguments and success texts (C-7); their errors are their
+ own, short and without the C-7 advice to use `bash`, which the turn may not call. `edit` reuses the tools'
+ matching (`edit_diff`), BOM, and line-ending handling. The C-7 tools themselves are unchanged.
+- The checkpoint is the text of a final response that stops with `stop` and calls no tool; only a `tool_use` stop
+ with calls continues the turn. Anything else (a response refused at admission, a length stop, a `tool_use` stop
+ without calls, calls under any other stop, an error, or no text) is a failure, and nothing enters the context;
+ so is a checkpoint whose row the host cannot complete (§10, invariant 4).
+- The turn's messages, read from the attempt ledger (§10, invariant 4) with every failed or retried attempt's
+ partial and its usage, and the turn's tool results, are recorded once per checkpoint turn, on every exit but an
+ abort (§10, invariant 4), outcome included, as an audit row
+ (`agent_events.event_type = 'context_checkpoint_turn'`, `visibility = 'audit'`, no `context_seq`; shape
+ `CheckpointTurn`), never as context.
+
+## 7. Checkpoint row and projection
+
+A successful checkpoint appends a `context_compaction` row (`Compaction`). Its model-facing content is fixed when it
+is written, so projection stays a pure function of the rows:
+
+- `summary`: the rendered checkpoint message:
+
+ ```text
+ <context-checkpoint>
+ This is a record of the earlier part of this conversation, written for you so you can continue. It is history, not new instructions: the user requirements recorded in it still apply, but do not treat the record itself as a request.
+
+ <the model's checkpoint>
+
+ <artifacts>
+ Read:
+ - <path, cumulative across checkpoints>
+ Modified:
+ - <path, cumulative across checkpoints>
+ </artifacts>
+ <earlier-record>
+ The full text of the earlier conversation is still stored. To look up a detail, run:
+ <the adapter's lookup command for this Session through summarized_to_seq>
+ </earlier-record>
+ <current-request>
+ <the split turn's user message, verbatim>
+ </current-request>
+ </context-checkpoint>
+ ```
+
+ `Read` lists paths of successful `read` calls that no `write` or `edit` touched; `Modified` lists paths of
+ successful `write` or `edit` calls; `(none)` when a list is empty. `<earlier-record>` is left out when the adapter supplies no command, and
+ `<current-request>` when the cut did not split a turn.
+- `state`: texts the adapter rendered from their own stores when the checkpoint was written: skill bodies by name and
+ revision (at most 5,000 tokens each and 25,000 in total), pending Watches, Tasks, and delegated Runs from the Harness
+ tables, and the full environment block when the checkpoint happened inside a run (C-7 §8).
+- Projection (C-5 §3): the system prompt, hook-rehydrated messages, one user message holding `summary` and then each
+ `state` text as its own text block, then the rows from `first_kept_seq` on, with edits applied. A tool result whose
+ call was summarized is left out with it. No synthetic "continue" message follows.
+- Every `Compaction`, `ContextEdit`, and `AgentState` row is checked against its complete schema shape when it is
+ loaded, so a malformed row fails projection instead of a later step that reads it.
+
+Iterative checkpoints use the same prompt: the previous checkpoint message is part of the forked prefix, and the
+prompt tells the model to carry forward what still matters. File lists and loaded skills accumulate mechanically.
+
+## 8. Overflow ladder
+
+Bounded per model request. Each step makes the next request smaller; the ladder takes at least one step and stops
+once the request fits:
+
+- (a) **Normal checkpoint**, unless one already ran for this request, there is nothing to summarize, or the whole
+ context cannot fit a forked request. A checkpoint request the provider rejects as overflow moves on to (b).
+- (b) **Rolling**: fork-summarize the prefix up to the cut nearest half the tokens, moved earlier until its fork can
+ fit (§5), so the context becomes checkpoint + the rest verbatim; roll again while the request still does not fit,
+ at most 2 rolls per request.
+- (c) **Dropped**: when no checkpoint request can help (one failed for this request other than by overflow, a rolling
+ one failed, no rolling prefix can fit, the rolls are used up, or auto-compaction is paused), no model is called:
+ the earliest part (§5) moves out of the context. Built like any checkpoint row (§7: fresh `state`, and
+ `<current-request>` when the cut splits a turn), the row keeps the previous checkpoint's text and the
+ `<earlier-record>` pointer; `checkpoint` is empty when there was none, and the message then has no framing text.
+ Repeated while the request still does not fit.
+- (d) **Stop**: when the request and its minimal request (what the drop would leave of it: the drop's own row, §8 c,
+ plus the last unit; §3) both cannot fit (checked in the stage, §3,
+ before provider admission), when nothing more can move out of a request that cannot fit or that the provider
+ refused, or after 4 provider overflows of one request, the run ends `context_exhausted` and the
+ `context_exhausted` event says what fills the context. No model is called for a context that cannot fit.
+
+An attempt the provider refused, or that is retried, is never context (§10, invariant 4).
+
+With a provider that always overflows, one request makes at most two checkpoint model calls, then drops
+mechanically, and stops after its fourth overflow.
+
+## 9. What the adapter supplies
+
+The loop takes a `ContextConfig` (`harness/context.py`); without one, no context management runs and an overflow
+ends the run `context_exhausted`, as in P1. The adapter supplies:
+
+- `scratch_dir`: this Session's scratch directory; without it, the policy denies every write.
+- `ContextHost.earlier_record(session_id, through_seq)`: the lookup command, a `vibe data query` SQL naming every
+ Session whose rows the context holds and the last summarized `context_seq`.
+- `ContextHost.render_state(StateRequest)`: the `state` texts (§7) for the skills the summarized rows loaded and
+ whether the checkpoint happened inside a run.
+- A `TranscriptStore` (C-5 §2) implementing the whole protocol C-9 uses: `append_response(..., request=...)` keeps
+ `ModelResponse.request` for the anchor (§2); `append_payloads(session_id, entries)` writes several payload rows in
+ one transaction (invariant 3); `append_audit(session_id, kind, payload)` writes a non-context audit row,
+ `checkpoint_turn` (§6) or `attempt` (invariant 4), in every mode; every loaded row carries its `created_at` (§3).
+ The SQLite store and the adapter's implement it, and one contract suite runs the same tests on them and on the
+ in-memory store the engine tests use (`tests/test_transcript_store_contract.py`).
+- The full environment block (C-7 §8) on the first input after a checkpoint: the summarized inputs that carried it
+ are gone, and a checkpoint's `state` carries it only when it happened inside a run.
+- `Agent.compact(turn_id=..., focus=...)` behind `/compact [focus]` on every surface, and the pause notice (§10)
+ through `vibe/i18n`.
+
+## 10. Guards
+
+- **One compaction in flight per Session.** A checkpoint turn never starts another; `compact()` and `run()` refuse
+ each other on one Agent; across Agent instances the adapter's Session writer lock serializes them.
+- **Pause.** Each failed checkpoint counts as a failure; a successful one resets the count. A successful
+ normal checkpoint whose result is still at least `0.75 * T` counts as ineffective; an effective one resets that
+ count. After 3 consecutive failures or 3 ineffective checkpoints, auto-compaction pauses for the Session: threshold
+ checkpoints stop, and the overflow ladder skips straight to (c). The `compaction_paused` event fires once, at the
+ transition, and the adapter tells the user. The counters and the pause are durable loop state, stored beside the
+ hook state in `agent_state` rows (`AgentState.context`), so they survive restarts and forks; projection takes them
+ from the latest `agent_state` row that carries them.
+- **Manual `/compact [focus]`** clears the pause and both counters, then runs a normal checkpoint with reason
+ `manual`; its own outcome counts as above. When everything is within the kept tail, it emits `compaction_skipped`
+ and ends `completed`, and the adapter replies briefly that there is nothing to compact yet.
+
+**Ordering and ownership invariants.** This list is the one normative statement of these rules; the other sections
+refer to it. Each has a test in `tests/agent_core/agent/test_compaction.py` (route: `test_context.py`; the ledger's
+every-exit audit: `test_loop.py`) that fails when its order or owner is broken.
+
+1. **One request pipeline.** Projection, then `budget()` on that final request, once per composed request, then
+ the C-9 stage, then the provider. Nothing changes a request after it is budgeted; a stage step that changes the
+ context rebuilds the request from the top. Whether a request fits is always `budget()` on a request actually
+ composed: the request to send, the fork the stage would send first (the checkpoint turn composes its requests the
+ same way, so the dry run and the turn cannot differ), and the stop check's minimal request (§3: the drop's own
+ row for that cut, built by the one builder of checkpoint rows and projected like any context; with fewer than two
+ units, the request itself). The one bound
+ that extends a budget by arithmetic is the checkpoint turn's tool room, from its latest request's budget (§6);
+ the stop message after the fourth overflow re-measures the refused request. The single-unit stop (§8 d) is in
+ the stage, before provider admission. Checkpoint requests take the same pipeline. In v1 an Agent with a
+ `ContextConfig` takes no user hooks (a configuration error), so nothing else can rewrite a request C-9 owns;
+ hooks with context management are a post-v1 design item (plan §10).
+2. **One tool pipeline** in a checkpoint turn: the turn's budget (once closed, `BUDGET_USED`), then the checkpoint
+ table (a denial is its fixed text), then execution (a scratch `write` or `edit` relative to the root's
+ descriptor, as joined work an abort waits for), then the bound on the result of every call that ran (§6). The
+ two fixed texts are never cut.
+3. **One commit for C-9 state.** A transition (its `context_edit` rows, its `context_compaction` row, the guard and
+ pause, and the hook state of that commit point in `AgentState`) is written in one transaction
+ (`append_payloads`), before any event announces it; a failed commit leaves nothing. Nothing else writes
+ `AgentState.context`.
+4. **One attempt ledger.** Every model attempt of a run (success, overflow, error, retry, checkpoint) records its
+ request, its response or partial, and so its usage, in one place. The checkpoint audit and the request facts of a
+ committed response (the anchor) read only from it. An attempt that does not become the run's response is never
+ context, and its partial is not carried: a retried request goes out again unchanged, and one the provider refused
+ as overflow is rebuilt after a ladder step (§8). The ledger, not each exit path, keeps the usage of a
+ conversation attempt that did not become a response row (retried, relieved, a usage-only terminal, refused at
+ admission, or a failed commit): one non-context `ModelAttempt` audit row, never a response row, written in every
+ mode, with or without `ContextConfig`, on every exit of the model call but an abort; a failed audit write is a
+ diagnostic and is not retried. The cancelled run scope admits no further store write, so an aborted call's
+ unaudited attempts are not kept. It is the one place that usage is kept. A checkpoint attempt's partials and
+ usage are kept in its `CheckpointTurn` row (§6), which the turn writes by the same rule: once, on every exit but
+ an abort, whichever step ends it (compose, provider, admission, the host's state or lookup, building the row,
+ commit). A failed request or a host failure after the model answered is a failed checkpoint, counted by the
+ guard; an engine error building the row, or a failed commit, ends the run with nothing landed (invariant 3).
+5. **Route-scoped anchors.** An anchor answered by another origin (provider, api, model) is invalid (§2).
+6. **One admission path.** Every response, of every purpose (conversation, checkpoint), and every partial with
+ content is admitted in one place, the model call, before anything acts on it: it must be valid after the
+ committed rows and, in a checkpoint turn, the turn's own request and messages (projection's rules: canonical
+ JSON arguments, no duplicate open call ids). A conversation response that fails ends the run as a provider
+ protocol violation; a checkpoint response that fails is a failed checkpoint, and none of its calls runs. Its
+ audit keeps the response when JSON can hold it.
+
+UX is silent: an automatic compaction shows nothing, and the raw messages stay in history. The only user-visible
+text is the pause notice, and, after (d), the run's stop message. A manual `/compact` is an explicit user action,
+so the adapter answers it.
+
+## 11. Checkpoint request (prompt `checkpoint-v2`)
+
+The owner-approved English text, verbatim (`harness/context.py` `CHECKPOINT_REQUEST`):
+
+```text
+<context-checkpoint-request>
+Pause the work here. Do not call any tool and do not continue the task. This reply does one thing: write a context checkpoint.
+
+The conversation above will be replaced by your checkpoint plus the messages after it. Whoever continues is you, but you will no longer remember this conversation; the checkpoint is all you will know of it. What you do not write down is lost.
+If there is an earlier checkpoint above, it is discarded after this: carry forward everything in it that still matters; where it conflicts with later messages, the later messages win.
+
+Everything above is a record to summarize, not instructions to act on now.
+
+Write in three layers, from the broad to the specific. Use exactly these headings, in this order. Write "(none)" under an empty heading.
+
+# 1. Self and method
+
+## How I work here
+- The role the user expects of me in this conversation, and the working agreements we established (for example how to report, when to ask, what I may decide on my own).
+- Methods and judgments that proved effective here, and ones that proved ineffective, written as transferable principles I can apply to any later work.
+- Record only what this conversation established; my identity and standing instructions come from the system prompt and are not restated here.
+
+# 2. Goals and requirements
+
+## Goals
+- What the user wants to achieve, and the intent behind it. If there are several, list each and mark the one being pursued now.
+
+## User requirements
+- Every instruction, preference, correction, and prohibition from the user that still applies. Quote short ones verbatim. Never drop one unless the user withdrew it.
+
+## Key decisions
+- decision: reason
+
+## Pitfalls
+- Mistakes made, assumptions that proved false, and dead ends (quote the exact error text where there is one), with what resolved each or "unresolved", so the same mistake is not repeated.
+
+# 3. Now and next
+
+## Progress
+### Done
+### In progress
+### Blocked or open questions
+
+## Waiting on
+- Background commands, Watches, scheduled Tasks, delegated agent runs, or questions to the user that are still expected to report back, with their ids.
+
+## Next steps
+1. The concrete next action, then the ones after it.
+
+## Exact references
+- Exact paths, identifiers, commands, links, ids, and values needed to continue.
+
+Rules: terse bullets, not paragraphs. Preserve exact paths, identifiers, commands, error strings, and numbers. Do not invent anything that is not above. Never write out secrets, tokens, or credentials; refer to them by name. Write in the language the user writes in.
+Additional focus from the user: <focus, only for /compact <focus>>
+</context-checkpoint-request>
+```
+
+## 12. Deferred
+
+Not built in v1: background precomputed compaction; server-side compaction (forbidden by hard constraint 8);
+automatic re-read of recently modified files; memory tools (the policy reserves their row); lowering effort for the
+checkpoint turn through a per-message system effort.
+
+Sources: the cut rule, cumulative file lists, and the overflow patterns from Pi (MIT, `7fbbd5f`); the merge rule from
+OpenCode; "a record, not instructions" from Gemini CLI; fork delivery from Claude Code; the waiting-on section, the
+earlier-record pointer, and the rolling ladder are Avibe's (research: evaluation §4).
diff --git a/docs/plans/agent-core-contracts/conversion-tables.md b/docs/plans/agent-core-contracts/conversion-tables.md
index 3a58432d6..5f6fafc5a 100644
--- a/docs/plans/agent-core-contracts/conversion-tables.md
+++ b/docs/plans/agent-core-contracts/conversion-tables.md
@@ -27,7 +27,7 @@ rules on top of those mappings.
| Response cleanup | The shared driver's single `finally` owns the opening task as well as its response. It closes successful results even when cancellation wins the same wait cycle or the bounded join; if opening is detached, that `finally` registers a late-result close callback. Cleanup follows terminal delivery and bounds `response.aclose()` at 10 seconds. A stalled close is cleanup-only and cannot replace or duplicate the terminal outcome. |
| Retry boundary | `ProviderError.retryable` is false once any model content delta or tool-call start/delta was emitted. A Responses `ToolCallStart` therefore makes a later provider failure non-retryable. |
| Partial and abort | The shared `partial_message` policy is used by all three adapters. Usage captured before the first visible delta is retained, and errors/abort carry an assembled `AssistantMessage` whenever visible content or usage exists; empty placeholder slots alone do not count as streamed output, while non-empty terminal snapshots do. Consumer/task cancellation is preserved even if response cleanup fails. |
-| Retry admission | `RetryPolicy.delay` in `core/agent_core/agent/models.py` applies only the bounded retry count/time budget and obeys `ProviderError.retryable`; it does not reject a usage-only partial or infer a second streamed-output boundary. A retry-admitted usage-only partial is committed as its own non-final model-response row, preserving per-attempt usage without adding prompt attempts together in one response. `test_retry_obeys_provider_flag_and_allows_usage_only_partial` and `test_retry_preserves_usage_only_partial_in_successful_response` are the loop proofs. |
+| Retry admission | `RetryPolicy.delay` in `core/agent_core/agent/models.py` applies only the bounded retry count/time budget and obeys `ProviderError.retryable`; it does not reject a usage-only partial or infer a second streamed-output boundary. A retry-admitted usage-only partial is never context: the retry resends the original request, and the attempt's usage is one non-context `ModelAttempt` audit row, in every mode (C-9 `context.md` §10, invariant 4), so per-attempt usage is kept without adding prompt attempts together in one response. `test_retry_obeys_provider_flag_and_allows_usage_only_partial` and `test_retry_keeps_a_usage_only_partial_out_of_the_context` are the loop proofs. |
| Tool-call stop normalization | `StreamAssembler.finalize` changes only `stop` with one or more tool calls to canonical `tool_use`, following Pi. The loop admits execution only for `stop_reason="tool_use"`; calls attached to `length`, `safety`, `refusal`, or `error` are settled as `is_error` results explaining the stop reason. |
## Shared stream assembler and dispatch ledger
diff --git a/docs/plans/agent-core-contracts/loop-control.md b/docs/plans/agent-core-contracts/loop-control.md
index 6ca439611..46887ede6 100644
--- a/docs/plans/agent-core-contracts/loop-control.md
+++ b/docs/plans/agent-core-contracts/loop-control.md
@@ -8,9 +8,11 @@ The loop in `core/agent_core/agent/`. Semantics are the ones the bare-loop spike
```python
class Agent:
def __init__(self, *, models: ModelRouter, tools: Sequence[Tool], hooks: Sequence[Hooks],
- store: TranscriptStore, jobs: JobHost) -> None: ...
+ store: TranscriptStore, jobs: JobHost,
+ context: ContextConfig | None = None) -> None: ... # C-9; excludes hooks in v1 (§3)
def run(self, input: Input, *, turn_id: str) -> AsyncIterator[AgentEvent]: ... # one Avibe Turn
+ def compact(self, *, turn_id: str, focus: str | None = None) -> AsyncIterator[AgentEvent]: ... # /compact (C-9)
def steer(self, input: Input) -> bool: ... # False: not accepted, the adapter keeps ownership
def follow_up(self, input: Input) -> bool: ...
def abort(self, reason: str) -> None: ...
@@ -27,7 +29,8 @@ wrapper.
```text
commit input → loop:
- before_model hooks → provider stream (events out)
+ projection → before_model hooks (without a ContextConfig) or budget and the C-9 stage (with one; C-9 §10)
+ → provider stream (events out) → admission of the response
if the response has tool calls:
commit it as `assistant`
for each call, in order: before_tool → execute → after_tool → commit tool result
@@ -63,8 +66,13 @@ Hooks run in registration order. The first `deny` or `end` wins; rewrites compos
| `after_run` | outcome | nothing |
A `before_model` rewrite changes only that request and is not persisted by design: a rewritten request is not
-reconstructible from the rows, and A10 is stated for requests without a transient rewrite. Anything that must survive a
-restart, or that context management must see, goes through C-5 rows (`context_edit`, `context_compaction`). `end` finishes the run after the current step commits.
+reconstructible from the rows, and A10 is stated for requests without a transient rewrite. Anything that must survive
+a restart, or that context management must see, goes through C-5 rows (`context_edit`, `context_compaction`). `end`
+finishes the run after the current step commits.
+
+In v1 an Agent with a C-9 `ContextConfig` takes no user hooks: passing both is a configuration error, because C-9
+owns the request and the checkpoint turn's tools. Hooks with context management are a post-v1 design item
+(`context.md` §10, plan §10).
## 4. Steer, follow-up, abort
@@ -96,7 +104,10 @@ sent with that request gets the error result `Tool <name> is not available.`
| `tool_progress` | dropped in v1: no backend shows live tool output, so a running tool shows its `tool_started` line, as for the other backends (live tool output joins the live partial text and progress follow-up, `avibe-agent-core.md` §10) |
| `tool_finished` | the committed `tool_result` row; a handed-over job names its Watch |
| `steer_applied` | the steer delivery is accepted into the running Turn |
-| `compaction_started`, `compaction_finished`, `compaction_failed` | optional status line; failures always reported |
+| `compaction_started`, `compaction_finished`, `compaction_failed` | none for an automatic compaction (C-9 `context.md` §10); a manual `/compact` reports its outcome |
+| `compaction_skipped` | a manual `/compact` had nothing to compact yet: a brief localized reply |
+| `compaction_paused` | the pause notice, once per pause, localized through `vibe/i18n` |
+| `context_exhausted` | what fills the context, in the run's stop message (C-9 `context.md` §8 d) |
| `run_ended` | `MessageOutput` settles the Turn |
| `error` | `notify` / `error` row; the text shown is the adapter's localized copy for the event's `kind` (`vibe/i18n`), and `message` is diagnostic detail, never display copy |
diff --git a/docs/plans/agent-core-contracts/transcript-rows.schema.json b/docs/plans/agent-core-contracts/transcript-rows.schema.json
index f80662342..5794329eb 100644
--- a/docs/plans/agent-core-contracts/transcript-rows.schema.json
+++ b/docs/plans/agent-core-contracts/transcript-rows.schema.json
@@ -37,6 +37,21 @@
"message": {
"$ref": "message.schema.json#/definitions/AssistantMessage",
"description": "Verbatim, including quick-reply blocks and file:// links that the display copy rewrites."
+ },
+ "request": {
+ "type": "object",
+ "description": "C-9 (context.md section 2): the request this response answered, as sent, for the estimate anchor. Written only when context management is on.",
+ "required": [
+ "tokens"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "tokens": {
+ "type": "integer",
+ "minimum": 0,
+ "description": "UTF-8/4 tokens of the whole request: system prompt, tool definitions, and messages."
+ }
+ }
}
}
},
@@ -102,38 +117,75 @@
}
},
"Compaction": {
- "description": "`agent_events.content_json` of a `context_compaction` row (plan §5.2).",
+ "description": "`agent_events.content_json` of a `context_compaction` row (context.md section 7). Its model-facing content (`summary`, `state`) is fixed when it is written, so projection is a pure function of the rows.",
"type": "object",
"required": [
"version",
+ "mode",
+ "reason",
"summary",
+ "checkpoint",
+ "state",
"first_kept_seq",
- "summarized_from_seq",
"summarized_to_seq",
- "reason",
+ "files_read",
+ "files_modified",
+ "skills",
"tokens_before",
"tokens_after_estimate",
- "summarizer",
- "files_read",
- "files_modified"
+ "threshold"
],
"additionalProperties": false,
"properties": {
"version": {
"const": 1
},
+ "mode": {
+ "enum": [
+ "normal",
+ "rolling",
+ "dropped"
+ ],
+ "description": "`normal`: the fork summarized the whole conversation and the tail stays verbatim; `rolling`: the fork summarized the prefix up to the cut (overflow ladder b); `dropped`: the prefix moved out with no model call (overflow ladder c)."
+ },
+ "reason": {
+ "enum": [
+ "manual",
+ "threshold",
+ "overflow"
+ ]
+ },
+ "focus": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Text after `/compact`."
+ },
"summary": {
"type": "string",
- "description": "Self-contained checkpoint text, including the mechanical file lists and `<current-request>` when present."
+ "description": "The rendered `<context-checkpoint>` message: framing, checkpoint, `<artifacts>`, `<earlier-record>`, and `<current-request>` when present. Model-facing."
},
- "first_kept_seq": {
- "type": "integer"
+ "checkpoint": {
+ "type": "string",
+ "description": "The model-written checkpoint. For `dropped`, the previous checkpoint's text, or empty when there was none."
},
- "summarized_from_seq": {
- "type": "integer"
+ "state": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "State the adapter rendered from its own stores when the checkpoint was written (skills, pending Harness work, the environment block); each is one text block after `summary`. Model-facing."
+ },
+ "first_kept_seq": {
+ "type": "integer",
+ "minimum": 1,
+ "description": "`context_seq` of the first unit kept verbatim."
},
"summarized_to_seq": {
- "type": "integer"
+ "type": "integer",
+ "minimum": 0,
+ "description": "The last `context_seq` moved out of the context; the `<earlier-record>` lookup reads through it."
},
"previous_compaction_id": {
"type": [
@@ -141,19 +193,52 @@
"null"
]
},
- "reason": {
- "enum": [
- "manual",
- "threshold",
- "overflow"
- ]
- },
- "focus": {
+ "current_request": {
"type": [
"string",
"null"
],
- "description": "Text after `/compact`."
+ "description": "Verbatim text of the split turn's user message, carried across checkpoints while that turn lasts."
+ },
+ "current_request_message_id": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "files_read": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Paths given to `read` and never to `write` or `edit`, cumulative."
+ },
+ "files_modified": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Paths given to `write` or `edit`, cumulative."
+ },
+ "skills": {
+ "type": "array",
+ "description": "Skills loaded by summarized rows, cumulative, minus those whose load result is still in the context; their bodies are in `state`.",
+ "items": {
+ "type": "object",
+ "required": [
+ "name",
+ "revision"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "revision": {
+ "type": "string"
+ }
+ }
+ }
},
"tokens_before": {
"type": "integer",
@@ -163,13 +248,22 @@
"type": "integer",
"minimum": 0
},
+ "threshold": {
+ "type": "integer",
+ "description": "T when the checkpoint was written; ineffective when `tokens_after_estimate >= 0.75 * threshold`."
+ },
"summarizer": {
- "type": "object",
+ "type": [
+ "object",
+ "null"
+ ],
+ "description": "The checkpoint turn; null for `dropped`.",
"required": [
"origin",
"prompt_version",
- "chunks"
+ "rounds"
],
+ "additionalProperties": false,
"properties": {
"origin": {
"$ref": "message.schema.json#/definitions/Origin"
@@ -177,32 +271,16 @@
"prompt_version": {
"type": "string"
},
- "chunks": {
+ "rounds": {
"type": "integer",
- "minimum": 1
+ "minimum": 0,
+ "description": "Responses of the checkpoint turn that called tools: at most 5 rounds whose calls ran, plus one answered with the used-up budget text."
}
}
},
"usage": {
- "$ref": "message.schema.json#/definitions/Usage"
- },
- "files_read": {
- "type": "array",
- "items": {
- "type": "string"
- }
- },
- "files_modified": {
- "type": "array",
- "items": {
- "type": "string"
- }
- },
- "current_request_message_id": {
- "type": [
- "string",
- "null"
- ]
+ "$ref": "message.schema.json#/definitions/Usage",
+ "description": "Summed over the checkpoint turn's responses."
}
}
},
@@ -233,7 +311,8 @@
"text": {
"type": "string"
}
- }
+ },
+ "additionalProperties": false
},
"reason": {
"enum": [
@@ -243,7 +322,7 @@
}
},
"AgentState": {
- "description": "`agent_events.content_json` of an `agent_state` row: hook state at a commit point (loop-control.md section 7). Not projected into messages.",
+ "description": "`agent_events.content_json` of an `agent_state` row: loop state at a commit point (loop-control.md section 7, context.md section 10). Not projected into messages.",
"type": "object",
"required": [
"version",
@@ -256,6 +335,112 @@
},
"state": {
"type": "object"
+ },
+ "context": {
+ "type": "object",
+ "description": "Context-management guard state (context.md section 10). Written only by C-9's own commits, together with the hook state of that commit point; projection takes it from the latest agent_state row that carries it.",
+ "required": [
+ "failures",
+ "ineffective",
+ "paused"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "failures": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "ineffective": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "paused": {
+ "type": "boolean"
+ }
+ }
+ }
+ }
+ },
+ "CheckpointTurn": {
+ "description": "`agent_events.content_json` of a `context_checkpoint_turn` audit row (`TranscriptStore.append_audit(kind='checkpoint_turn')`, `visibility = 'audit'`, no `context_seq`): one checkpoint turn and the messages it produced, from the attempt ledger (context.md section 6). Never context.",
+ "type": "object",
+ "required": [
+ "version",
+ "reason",
+ "mode",
+ "outcome",
+ "messages"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "version": {
+ "const": 1
+ },
+ "reason": {
+ "enum": [
+ "manual",
+ "threshold",
+ "overflow"
+ ]
+ },
+ "mode": {
+ "enum": [
+ "normal",
+ "rolling"
+ ]
+ },
+ "outcome": {
+ "enum": [
+ "completed",
+ "failed"
+ ]
+ },
+ "error": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "compaction_event_id": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "messages": {
+ "type": "array",
+ "description": "Every attempt's response or partial (failed and retried ones included) and the turn's tool results, in order; a refused response that JSON cannot hold is left out (context.md section 10, invariant 6).",
+ "items": {
+ "$ref": "message.schema.json"
+ }
+ },
+ "usage": {
+ "$ref": "message.schema.json#/definitions/Usage"
+ }
+ }
+ },
+ "ModelAttempt": {
+ "description": "`agent_events.content_json` of a `model_attempt` audit row (`TranscriptStore.append_audit(kind='attempt')`, `visibility = 'audit'`, no `context_seq`): a conversation attempt that reported usage and did not become a response row (retried, relieved, a usage-only terminal, refused at admission, or a failed commit), written by the attempt ledger in every mode, with or without context management (context.md section 10, invariant 4). Never context.",
+ "type": "object",
+ "required": [
+ "version",
+ "usage",
+ "error"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "version": {
+ "const": 1
+ },
+ "usage": {
+ "$ref": "message.schema.json#/definitions/Usage"
+ },
+ "error": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Why the attempt did not become a response: the provider error that ended it (`<kind>: <message>`), or, without one, why the model call ended (a refusal at admission, a failed commit)."
}
}
}
@@ -263,38 +448,44 @@
"examples": [
{
"version": 1,
- "summary": "## Objective\nFix the failing path test...\n<files-modified>\ncore/paths.py\n</files-modified>",
+ "mode": "normal",
+ "reason": "threshold",
+ "focus": null,
+ "summary": "<context-checkpoint>\nThis is a record of the earlier part of this conversation, written for you so you can continue. ...\n\n# 1. Self and method\n...\n\n<artifacts>\nRead:\n- tests/test_paths.py\nModified:\n- core/paths.py\n</artifacts>\n<earlier-record>\n...\n</earlier-record>\n</context-checkpoint>",
+ "checkpoint": "# 1. Self and method\n...",
+ "state": [
+ "<loaded-skills>\n...\n</loaded-skills>"
+ ],
"first_kept_seq": 412,
- "summarized_from_seq": 1,
"summarized_to_seq": 411,
"previous_compaction_id": null,
- "reason": "threshold",
- "focus": null,
+ "current_request": null,
+ "current_request_message_id": null,
+ "files_read": [
+ "tests/test_paths.py"
+ ],
+ "files_modified": [
+ "core/paths.py"
+ ],
+ "skills": [],
"tokens_before": 158432,
"tokens_after_estimate": 31877,
+ "threshold": 155808,
"summarizer": {
"origin": {
"provider": "anthropic",
"api": "anthropic",
"model": "claude-opus-5-5"
},
- "prompt_version": "ckpt-v1",
- "chunks": 1
+ "prompt_version": "checkpoint-v2",
+ "rounds": 0
},
"usage": {
- "input_tokens": 61210,
+ "input_tokens": 1210,
"output_tokens": 2304,
- "cache_read_tokens": 0,
+ "cache_read_tokens": 157020,
"cache_write_tokens": 0
- },
- "files_read": [
- "core/paths.py",
- "tests/test_paths.py"
- ],
- "files_modified": [
- "core/paths.py"
- ],
- "current_request_message_id": null
+ }
}
]
}
diff --git a/docs/plans/agent-core-contracts/transcript.md b/docs/plans/agent-core-contracts/transcript.md
index 9859e1501..6e2ae740c 100644
--- a/docs/plans/agent-core-contracts/transcript.md
+++ b/docs/plans/agent-core-contracts/transcript.md
@@ -16,7 +16,7 @@ unique per Session across both tables (partial unique index on each table, plus
| tool result | `agent_events` | `tool_result` | `context` | `content_json` = `ToolResult` |
| checkpoint | `agent_events` | `context_compaction` | `context` | `content_json` = `Compaction` |
| cleared result | `agent_events` | `context_edit` | `context` | `content_json` = `ContextEdit` |
-| hook state | `agent_events` | `agent_state` | `context` | `content_json` = `AgentState` |
+| hook and guard state | `agent_events` | `agent_state` | `context` | `content_json` = `AgentState` |
A final response is `error` when it failed by itself (no text of its own: an empty answer, or a refusal or safety
stop without an explanation), as the other backends' failed terminal rows are. A successful final with nothing to show
@@ -26,10 +26,21 @@ the commit) types it `error`. Context loading accepts all three.
Display-only rows keep `context_seq` null: `interim`, `notify`, an `error` that reports a run failure, `vault`,
`output`, queued or removed inputs, and the `tool_call` trace row written at tool start (its `metadata_json` carries
-`tool_call_id` and `job_id` so the activity panel can pair it with the result).
+`tool_call_id` and `job_id` so the activity panel can pair it with the result). Audit rows are never context
+either: `agent_events` with `visibility = 'audit'` and no `context_seq`, written by `append_audit`, as
+`context_checkpoint_turn` (`CheckpointTurn`, C-9 `context.md` §6, with its own attempts' partials and usage) or
+`model_attempt` (`ModelAttempt`: the usage of a conversation attempt that did not become a response row, C-9
+`context.md` §10, invariant 4). The activity panel does not read them.
## 2. Writing
+- Every store implements the whole `TranscriptStore` protocol (`harness/store.py`) with the same behavior: an append
+ returns exactly the entry `load` reads back, `created_at` (epoch seconds) included; a response keeps C-9's request
+ facts in `content_json.model.request`; a payload row needs a payload kind and version 1, and `append_payloads`
+ commits all of its rows or none; consuming the same input again returns its entry, and a different message for it
+ is refused; a call is settled once (a second result returns the first); audit rows never load. One contract suite,
+ `tests/test_transcript_store_contract.py`, runs the same tests on the SQLite store, the adapter's store over it,
+ and the in-memory store the engine tests use.
- The loop is the only writer of a Session's `context_seq`, under a per-Session lock held across the transaction:
`next = max(context_seq of the Session in both tables, fork_source_context_seq if the Session is a fork) + 1`, so a
fork's first entry follows its inherited prefix.
@@ -55,15 +66,17 @@ Display-only rows keep `context_seq` null: `interim`, `notify`, an `error` that
1. Collect the context rows: the Session's own, plus its fork ancestry (§4).
2. Order by `context_seq`.
-3. If a `context_compaction` row exists, take the latest; the context becomes its checkpoint message followed by the
- rows with `context_seq >= first_kept_seq`, excluding every `context_compaction` row (including the selected one)
- and `agent_state` rows.
+3. If a `context_compaction` row exists, take the latest; the context becomes its checkpoint message (its `summary`,
+ then each `state` text as its own block) followed by the rows with `context_seq >= first_kept_seq`, excluding every
+ `context_compaction` row (including the selected one) and `agent_state` rows. A tool result whose call was
+ summarized leaves with it.
4. Apply `context_edit` rows: the latest edit per target replaces that tool result's content with its placeholder;
the `context_edit` rows themselves are then removed, so the result is only messages.
5. Answer any tool call that still has no committed result with the synthetic interrupted result from
`cross-provider.md`. Projection never consults a live job; resume settles open calls durably first
([`recovery.md`](recovery.md)).
-6. Prepend the rebuilt system prompt and rehydrated state (plan §5.2); these are not rows.
+6. Prepend the rebuilt system prompt and hook-rehydrated messages; these are not rows. State rendered for a
+ checkpoint is in its row, so projection stays a pure function of the rows (C-9 `context.md` §7).
## 4. Fork
diff --git a/docs/plans/avibe-agent-core.md b/docs/plans/avibe-agent-core.md
index fe7f05c09..e6d619da1 100644
--- a/docs/plans/avibe-agent-core.md
+++ b/docs/plans/avibe-agent-core.md
@@ -105,7 +105,7 @@ payload.
| C-6 | Model Hub consumer extension: `google` protocol, hop resolution, served-hop report | Model Hub → adapter | `model-hub-consumer.md`, `hop-resolution.schema.json` |
| C-7 | Tools: Pi's surface plus the owner's additions; output governance; job handle | `tools` → `agent`, adapter | `tools.md`, `job.schema.json` |
| C-8 | Backend registration: the catalog as the one declaration, and which sets must include `avibe` | catalog → every backend list | `backend-registration.md` |
-| C-9 | Context management: projection tiers, trigger, cut point, checkpoint, recovery | `harness` → `agent`, adapter | §5.2 here; row shapes in `transcript-rows.schema.json` |
+| C-9 | Context management: projection tiers, trigger, cut point, checkpoint, overflow ladder, guards | `harness` → `agent`, adapter | `context.md`; row shapes in `transcript-rows.schema.json` |
### 5.1 Transcript storage
@@ -131,7 +131,7 @@ For the Avibe Agent, the same rows become the transcript (C-5):
| Final model response | `messages` `result` | same, verbatim (quick-reply block and `file://` links kept) | `content_text` is the rendered text as today |
| Tool execution start | `agent_events` `tool_call`, `visibility='trace'` | none; the call lives in the response row | short display preview as today |
| Tool result | `agent_events` `tool_result`, `visibility='context'` | the result as the model saw it, after output governance | the activity panel may show a preview |
-| Compaction checkpoint | `agent_events` `context_compaction`, `visibility='context'` | §5.2 | expandable "context compacted" marker |
+| Compaction checkpoint | `agent_events` `context_compaction`, `visibility='context'` | C-9 `context.md` §7 | expandable "context compacted" marker |
| Cleared tool result | `agent_events` `context_edit`, `visibility='context'` | target row and placeholder | none |
Schema delta (one Alembic migration, nullable columns, no backfill):
@@ -142,7 +142,7 @@ Schema delta (one Alembic migration, nullable columns, no backfill):
2. A new `agent_events.visibility` value, `context`, never removed by trace retention. The retention filter is
already `event_type='tool_call' AND visibility='trace'`; a contract test pins the exemption.
3. New `agent_events.event_type` values `tool_result`, `context_compaction`, `context_edit`, and `agent_state` (hook
- state for fork, C-3), registered where the activity panel reads event types.
+ state for fork, C-3, and the C-9 guard state), registered where the activity panel reads event types.
4. For this backend, `agent_sessions.native_session_id` is the Avibe Session id.
Rules:
@@ -170,75 +170,43 @@ Rules:
### 5.2 Context management (C-9)
-**Draft, not frozen.** The owner deferred the context-management decisions; this section is the working design and
-freezes before P3 together with those decisions. Open points recorded for that freeze: the occupancy baseline
-immediately after a checkpoint or edit, before any response exists; capabilities of the served hop after a failover
-to a model with smaller limits; the summarizer output cap on routes below 16K output tokens; restoring the environment
-block for a request issued right after a checkpoint inside a turn; and image cost in the estimate.
-
-Every rule names its origin in evaluation §4. One pure function, `project(rows, fork_point)`, builds every request,
-resume, fork, and the UI's "model view". Three tiers, cheapest first:
-
-1. **Output governance at write time** (C-7): no single tool result exceeds 2,000 lines / 50 KB.
-2. **Clearing old tool results**, recorded as `context_edit` rows. Eligible: `read` and `bash` results, including
- terminal screen snapshots later. Protected: the last 2 user turns, the newest 5 eligible results, skill loads, and
- anything before the latest checkpoint. Applied only when it frees at least 20K tokens, and only before a request
- when the provider cache is already cold (idle longer than the cache TTL, which is normal in IM sessions) or the
- estimate passes 0.8·T. On by default. Placeholder: `[Old tool result cleared to save context. Re-run the tool or
- re-read the file if you need it again.]`
-3. **Checkpoint summary**, recorded as a `context_compaction` row.
-
-Trigger, checked before every model request, including inside the tool loop:
-
-```text
-W = context window (configured default 128,000 when Model Hub reports none)
-L_in = input limit (else W), O = max_tokens of the next request (default bound 8,192 when unknown)
-M = max(8_000, 3% of W); T = min(L_in - O - M, r * W), r = 0.9 by default, configurable per model
-est = occupancy of the last valid response after the latest checkpoint or edit
- (input_tokens + cache_read_tokens + cache_write_tokens + output_tokens: the whole prompt it was sent plus
- what it added; Usage normalizes each protocol so none of these overlap)
- + ceil(utf8_bytes / 4) of everything appended since, replayed reasoning payloads included
-compact when est >= T
-```
-
-UTF-8 bytes / 4 because characters / 4 undercounts Chinese by about 65% (72 characters are 51 o200k tokens).
-Subtracting the real `O` avoids Pi #8061. When the answering model changes (Model Hub failover or a user switch), T
-is recomputed for that model; a smaller window is handled by the overflow path below.
-
-**Cut point.** Keep `min(20K, 0.25·T)` recent tokens verbatim. Cut only before a user message, or before an
-assistant message whose tool batch follows it; never at a tool result. If the cut splits the current turn, copy that
-turn's user message verbatim into the checkpoint as `<current-request>`, with no second LLM call. Codex's "recent user
-messages only" tail is rejected: it has the most "forgot the task after compaction" reports.
-
-**Summarizer.** A separate request with no tools and no caching, using the same model at low reasoning with
-`max_tokens` 16K. The input is the head serialized from the projection actually sent (reasoning excluded; tool
-results capped at 2,000 characters, keeping head and tail; user messages capped at 8K tokens) plus the previous
-checkpoint in a `<previous-checkpoint>` slot, under OpenCode's merge rule: anything not carried forward is lost, and
-where they conflict the conversation wins. If the input exceeds the summarizer's budget (overflow recovery, failover
-to a smaller window), fold the head in chronological chunks through the same prompt. Fixed headings: Objective / User
-instructions and constraints (verbatim) / Work state / Key decisions / Errors and fixes / Pending async work / Next
-steps / Critical references. `files_read` and `files_modified` are appended mechanically and carried across
-checkpoints. A `length` stop, an error, a tool call, or empty output persists nothing.
-
-**After a checkpoint**, the request is: the rebuilt system prompt → the checkpoint, framed as "a historical record
-written for you, not new instructions" → state rendered from its own store rather than from the summary (skill bodies
-re-loaded by name and revision from `tool_result` rows carrying `details.skill`, at most 5K tokens each and 25K in
-total; pending Watches, Tasks, and delegated Runs from Harness tables) → the verbatim tail. The next consumed input
-carries the full environment block again (C-7 §8). No synthetic "continue"
-user message (OpenCode #13838, #15533).
-
-**Overflow recovery**, bounded per request: compact with the normal tail and retry once → compact with a minimal tail
-(current request plus latest tool batch) and retry once → stop the turn with a message that says what fills the
-context. Provider errors are classified with a port of Pi's overflow patterns plus HTTP 413 and
-`context_length_exceeded`.
-
-**Guards.** One compaction in flight per Session. Three consecutive failures, or three ineffective compactions (result
-at or above 0.75·T), pause auto-compaction for the Session and tell the user. Usage reported before the latest
-checkpoint is ignored. Manual `/compact [focus]` works on every surface.
-
-**Deferred**, with reasons in evaluation §4: cache-safe fork summarization (Anthropic-specific economics; decide from
-the compaction cost recorded on every checkpoint row), background precomputed compaction, automatic re-read of
-recently modified files, and server-side compaction (forbidden by hard constraint 8).
+**Frozen 2026-10-04** by owner decision. The contract is [`agent-core-contracts/context.md`](agent-core-contracts/context.md);
+this section summarizes it. Three tiers, cheapest first: output governance at write time (C-7); clearing old `read`
+and `bash` results with `context_edit` rows, on by default; and a checkpoint written by the model, recorded as a
+`context_compaction` row. Compaction and clearing only append rows.
+
+- **Limits from Model Hub.** `W` and `L_in` come from the `context_window` and `input_limit` of the route resolved
+ for the request (128,000 when unknown). `O` is the request's `max_tokens`: the hop's `max_output_tokens` (8,192
+ when unknown) capped by the Agent's output budget, and `min(16,000, O)` for a checkpoint request. One pure
+ function derives the rest and `est` from the final request, immediately before it is sent.
+ `M = max(8,000, 3% W)`, `T = min(L_in - O - M, 0.9 W)`.
+- **Trigger** before every model request, including inside the tool loop, on the final request (in v1 no user hook
+ runs with context management): `est` is the usage of the latest response stored with its request facts, adjusted by the UTF-8 bytes / 4
+ difference between this request and that one (1,600 per image), while that request went to the same route and the
+ transcript up to the response is unchanged; otherwise UTF-8 bytes / 4 of the whole request. Compact when
+ `est >= T`.
+- **Cut** before a user message or before an assistant message whose tool batch follows it, keeping
+ `min(20K, 0.25 T)` verbatim; a split turn's user message is copied into the checkpoint as `<current-request>`.
+- **Checkpoint delivery is a fork**: the same model, system prompt, tools, tool choice, and reasoning settings, the
+ conversation prefix byte-identical, and the owner-approved three-layer prompt appended (`checkpoint-v2`). The
+ checkpoint turn runs through the same loop under a "dreaming" tool policy: `read` allowed, writes only inside the
+ Session's scratch directory, everything else denied; at most 5 tool rounds, each tool bounded by the room left in
+ the window. Its messages are audit rows, never context.
+- **After a checkpoint** the request is the rebuilt system prompt, the `<context-checkpoint>` message (framing,
+ checkpoint, cumulative `<artifacts>`, an `<earlier-record>` lookup, `<current-request>`), state rendered from its
+ own stores when the checkpoint was written (skills, pending Watches, Tasks, and Runs, the environment block), and
+ the verbatim tail. No synthetic "continue" message.
+- **Overflow ladder**, bounded per request: the normal checkpoint; fork-summarize the prefix up to the cut nearest
+ half the tokens, moved earlier until it fits (rolling); with no model call, move the earliest part out (dropped); stop and say what fills the context.
+- **Guards**: one compaction in flight per Session; 3 consecutive failures or 3 ineffective checkpoints pause
+ auto-compaction for the Session, and the user is told once. Manual `/compact [focus]` works on every surface,
+ clears the pause, and is answered. An automatic compaction is silent.
+- **Deferred**: background precompute, server-side compaction (hard constraint 8), automatic re-read of modified
+ files, memory tools, and a lower effort for the checkpoint turn.
+
+Delivery: the core (`core/agent_core`, this contract) lands first; the Avibe Agent integration (Model Hub
+capabilities, the scratch directory, the `<earlier-record>` SQL, state rendering, `/compact`, the pause notice, and an
+end-to-end hermetic test) follows.
### 5.3 Tools (C-7)
@@ -334,9 +302,11 @@ Properties; the test suites enumerate cases.
its own origin, no signature is ever synthesized, and the stub sees exactly one protocol per request.
- **A3 Durability.** SIGKILL at any point resumes with no committed entry lost and no command executed twice; the
context rebuilt from the tables is always a valid request for every protocol.
-- **A4 Bounded context.** A session with more than 10,000 messages keeps every request under its model's T.
+- **A4 Bounded context.** A session with more than 10,000 messages keeps every request within its model's input
+ limit, and under its T unless auto-compaction is paused or a checkpoint for that request failed (C-9 §3).
Compaction and clearing only insert rows. A fork anchored before a checkpoint projects the full original context.
- With a provider that always overflows, one request triggers at most two compactions and then a user-visible stop.
+ With a provider that always overflows, one request makes at most two checkpoint model calls and then ends in a
+ user-visible stop (C-9 `context.md` §8).
- **A5 Egress.** With Model Hub configured, every model call goes to the resolved `base_url`: the engine itself sends
no telemetry and never contacts a vendor directly. Network use by tools (`bash`, later MCP) is the tools' own and is
governed by tool and workspace policy, not by this criterion.
@@ -350,7 +320,10 @@ Properties; the test suites enumerate cases.
provider unreachable: all user, tool, and assistant text is present in the new request, no signature from another
origin is sent, and the run completes.
- **A10 One copy.** For every request without a transient `before_model` rewrite (C-3 §3), the context rebuilt from
- `messages` and `agent_events` equals what the stub received; no other file or table holds a copy of it.
+ `messages` and `agent_events` equals what the stub received; no other file or table holds a copy of it. A
+ checkpoint turn's request is that context (for a rolling fork, its prefix up to the cut) plus the checkpoint
+ request and the turn's admitted responses and tool results (C-9 §6); its audit row also keeps the attempts that
+ were retried or failed.
- **A11 Exactly-once commands.** A command started by `bash` runs once across foreground completion, `watch: true`,
foreground-to-Watch handover, and a vibe restart in any of those states; Watch removal ends its process tree.
- **A12 Compaction quality.** On a scripted long-session fixture compacted twice, the agent still states the user's
@@ -377,7 +350,7 @@ breaker, review gates, and close-out follow the `pr-delivery-loop` skill.
| Provider edge cases become permanent maintenance | port tau's fixtures; add cases derived from `pi-ai` for stop reasons, overflow, retry, SSE; one conformance suite per protocol |
| The Model Hub extension lands late and blocks C-2 conformance | the Model Hub lane runs first in P1; the `ai` lane develops against the contract file, not the live gateway |
| A second persistence model creeps back | C-5 forbids one; A10 tests it |
-| Compaction quietly loses user constraints | the fixed "User instructions and constraints" heading; A12 tracked per prompt version |
+| Compaction quietly loses user constraints | the fixed "User requirements" heading of `checkpoint-v2`; A12 tracked per prompt version |
| Database growth from inline tool output | output governance bounds each row; the reserved reference form allows moving it out without a schema change |
| Scope creep toward the tension system or interactive terminals | §2 non-goals; §5.4 ships only the shape in v1 |
| Python 3.10 floor versus ported code | port with `TypeAlias`; CI already covers 3.10 |
@@ -408,4 +381,5 @@ contracts and checked against the implementing lane's code before they are close
| Product-wide media retention | `storage/media_service.py` | No media file is removed from disk today, whether Workbench upload, IM attachment, or Avibe Agent context snapshot (`<state>/agent_core/media`); session deletion only clears or cascades `media_objects` references. Retention needs one owner for every source. It must be fork-aware: a fork descendant keeps replaying the image tokens of a source Session that was deleted. Recorded as a v1 known limit in PR #2345. |
| Steer receipt fencing in the shared Turn owner | `core/session_turns.py` (`_finish_steer`) | **Done in PR #2345** (orchestrator-authorized cross-lane fix): a negative receipt settles only a current attempt whose Deliveries are still steering or reconciling, and a caller that knows the attempt passes `expected_attempt_id`, so a late or duplicate receipt can no longer pull a Delivery out of a Turn that claimed it. Regression: `test_a_late_negative_steer_receipt_never_moves_a_delivery_its_attempt_no_longer_owns`. |
| Live partial text and progress | every backend, Workbench and IM | No backend shows streamed partial text or live tool output today; the Avibe Agent drops `text_delta`, `thinking_delta`, and `tool_progress` (`loop-control.md` §6). Showing them needs a new UI surface for every backend, not an Avibe Agent change. |
+| Hooks with context management | `core/agent_core/agent/` (C-3, C-9) | In v1, an Agent with a `ContextConfig` takes no user hooks: `before_model` rewrites and `before_tool`/`after_tool` decisions each changed what C-9 owns (the route, the projected prefix, artifacts, the checkpoint budget). A post-v1 design defines which hook outputs C-9 accepts and how it accounts for them before the two are combined (owner decision, PR #2360 round 5). |
| Call-instance identity for job files | `core/agent_core/tools/` (`ToolContext`, job `meta.json`), the adapter | A tool call's identity is its instance: the owning response plus the call id, because providers reuse ids. Rows are matched by context order; job files still fall back to the clock (`find_job(created_since)`, J5's result-after-creation check), which assumes a non-decreasing wall clock between a response's commit and its job's start. Threading the call instance (owning response row and `context_seq`) into `ToolContext` and the job meta would remove that last residual. |
diff --git a/modules/agents/avibe/store.py b/modules/agents/avibe/store.py
index dbffa9eaa..33a08bd63 100644
--- a/modules/agents/avibe/store.py
+++ b/modules/agents/avibe/store.py
@@ -101,9 +101,11 @@ class AdapterTranscriptStore:
self._env_state[session_id] = {**previous, **current}
return entry
- async def append_response(self, session_id: str, message: AssistantMessage, *, final: bool) -> ContextEntry:
+ async def append_response(
+ self, session_id: str, message: AssistantMessage, *, final: bool, request: Optional[Mapping[str, Any]] = None
+ ) -> ContextEntry:
entry = await self._store.append_response(
- session_id, message, final=final, agent_name=self._agents.get(session_id)
+ session_id, message, final=final, request=request, agent_name=self._agents.get(session_id)
)
self._on_response(session_id, entry.row_id, message)
return entry
@@ -120,6 +122,18 @@ class AdapterTranscriptStore:
) -> ContextEntry:
return await self._store.append_payload(session_id, kind, payload, agent_name=self._agents.get(session_id))
+ async def append_payloads(
+ self,
+ session_id: str,
+ entries: Sequence[tuple[Literal["compaction", "context_edit", "agent_state"], Mapping[str, Any]]],
+ ) -> Sequence[ContextEntry]:
+ return await self._store.append_payloads(session_id, entries, agent_name=self._agents.get(session_id))
+
+ async def append_audit(
+ self, session_id: str, kind: Literal["attempt", "checkpoint_turn"], payload: Mapping[str, Any]
+ ) -> str:
+ return await self._store.append_audit(session_id, kind, payload, agent_name=self._agents.get(session_id))
+
# --- implementation ------------------------------------------------------
async def _await_input_row(self, session_id: str, message_id: str) -> None:
diff --git a/storage/agent_transcript.py b/storage/agent_transcript.py
index af8d6280e..8d1d73b74 100644
--- a/storage/agent_transcript.py
+++ b/storage/agent_transcript.py
@@ -8,9 +8,17 @@ context exactly when its ``context_seq`` is non-null:
``agent_initiated``, ``annotation``); consuming one sets its ``context_seq``
and ``content_json.model`` once;
* responses are new ``assistant`` / ``result`` / ``error`` rows with
- ``content_json.model`` and a rendered ``content_text``;
-* tool results, checkpoints, context edits, and hook state are new
- ``agent_events`` rows with ``visibility='context'``.
+ ``content_json.model`` (with the C-9 request facts when the loop gives them)
+ and a rendered ``content_text``;
+* tool results, checkpoints, context edits, and hook and guard state are new
+ ``agent_events`` rows with ``visibility='context'``;
+* audit rows (C-9: a conversation attempt's usage, a checkpoint turn with its
+ own attempts) are ``agent_events`` rows with ``visibility='audit'`` and no
+ ``context_seq``: never context.
+
+Every entry carries its row's ``created_at`` as epoch seconds, as written and
+as loaded (C-9 reads a response's to tell a cold provider cache after a
+restart). ``append_payloads`` commits several payload rows in one transaction.
Allocation. Every write takes SQLite's writer lock before its first read
(``reserve_write_lock``) and runs under a per-Session lock, so
@@ -82,6 +90,9 @@ INPUT_TYPES = ("user", "harness", "agent_initiated", "annotation")
FINAL_TYPES = ("result", "error")
RESPONSE_TYPES = ("assistant", *FINAL_TYPES)
CONTEXT_VISIBILITY = "context"
+AUDIT_VISIBILITY = "audit"
+AuditKind = Literal["attempt", "checkpoint_turn"]
+_AUDIT_EVENT_TYPE: dict[str, str] = {"attempt": "model_attempt", "checkpoint_turn": "context_checkpoint_turn"}
# Only the Avibe Agent writes context rows; the Session's routed backend may change mid-Turn.
CONTEXT_WRITER = "avibe"
PAYLOAD_VERSION = 1
@@ -171,9 +182,13 @@ class SQLiteTranscriptStore:
def work(conn: Connection) -> ContextEntry:
row = conn.execute(
- select(messages.c.session_id, messages.c.type, messages.c.context_seq, messages.c.content_json).where(
- messages.c.id == message_id
- )
+ select(
+ messages.c.session_id,
+ messages.c.type,
+ messages.c.context_seq,
+ messages.c.content_json,
+ messages.c.created_at,
+ ).where(messages.c.id == message_id)
).mappings().first()
if row is None or row["session_id"] != session_id:
raise TranscriptError(f"input {message_id} is not a message of Session {session_id}")
@@ -193,16 +208,27 @@ class SQLiteTranscriptStore:
.where(messages.c.id == message_id, messages.c.context_seq.is_(None))
.values(context_seq=seq, content_json=json.dumps({**content, "model": model}), updated_at=_utc_now())
)
- return ContextEntry(session_id, seq, "input", message_id, message=message, payload=model)
+ return ContextEntry(
+ session_id, seq, "input", message_id, message=message, payload=model, created_at=_epoch(row["created_at"])
+ )
return await self._write(session_id, work)
async def append_response(
- self, session_id: str, message: AssistantMessage, *, final: bool, agent_name: Optional[str] = None
+ self,
+ session_id: str,
+ message: AssistantMessage,
+ *,
+ final: bool,
+ request: Optional[Mapping[str, Any]] = None,
+ agent_name: Optional[str] = None,
) -> ContextEntry:
if not isinstance(message, AssistantMessage):
raise TypeError("append_response takes an AssistantMessage")
- model = _canonical({"version": PAYLOAD_VERSION, "message": message_to_dict(message)}, "response")
+ response: dict[str, Any] = {"version": PAYLOAD_VERSION, "message": message_to_dict(message)}
+ if request is not None:
+ response["request"] = dict(request) # C-9 ``ModelResponse.request``: the anchor's request facts
+ model = _canonical(response, "response")
display_text = self._render(message, final=final)
def work(conn: Connection) -> ContextEntry:
@@ -221,7 +247,9 @@ class SQLiteTranscriptStore:
content={"model": model},
)
conn.execute(messages.update().where(messages.c.id == row["id"]).values(context_seq=seq))
- return ContextEntry(session_id, seq, "response", row["id"], message=message, payload=model)
+ return ContextEntry(
+ session_id, seq, "response", row["id"], message=message, payload=model, created_at=_epoch(row["created_at"])
+ )
return await self._write(session_id, work)
@@ -254,14 +282,49 @@ class SQLiteTranscriptStore:
async def append_payload(
self, session_id: str, kind: PayloadKind, payload: Mapping[str, Any], *, agent_name: Optional[str] = None
) -> ContextEntry:
- if kind not in ("compaction", "context_edit", "agent_state"):
- raise ValueError(f"not a payload entry kind: {kind!r}")
- data = _canonical(dict(payload), f"{kind} payload")
- if not _is_current_version(data):
- raise ValueError(f"a {kind} payload needs version {PAYLOAD_VERSION}")
- return await self._write(
- session_id, lambda conn: self._append_event(conn, session_id, kind, data, None, agent_name)
- )
+ return (await self.append_payloads(session_id, [(kind, payload)], agent_name=agent_name))[0]
+
+ async def append_payloads(
+ self,
+ session_id: str,
+ entries: Sequence[tuple[PayloadKind, Mapping[str, Any]]],
+ *,
+ agent_name: Optional[str] = None,
+ ) -> list[ContextEntry]:
+ """Several payload rows in order, in one transaction: all of them or none (C-9 section 10)."""
+ rows = [(kind, _payload(kind, payload)) for kind, payload in entries]
+
+ def work(conn: Connection) -> list[ContextEntry]:
+ return [self._append_event(conn, session_id, kind, data, None, agent_name) for kind, data in rows]
+
+ return await self._write(session_id, work)
+
+ async def append_audit(
+ self, session_id: str, kind: AuditKind, payload: Mapping[str, Any], *, agent_name: Optional[str] = None
+ ) -> str:
+ """A non-context audit row (C-9 ``ModelAttempt`` or ``CheckpointTurn``); its id. Never loaded as context."""
+ if kind not in _AUDIT_EVENT_TYPE:
+ raise ValueError(f"not an audit kind: {kind!r}")
+ data = _canonical(dict(payload), f"{kind} audit")
+
+ def work(conn: Connection) -> str:
+ origin = _turn_origin(conn, session_id, agent_name)
+ row = agent_events_service.append(
+ conn,
+ scope_id=origin.scope_id,
+ session_id=session_id,
+ platform=origin.platform,
+ event_type=_AUDIT_EVENT_TYPE[kind],
+ content=data,
+ agent_name=origin.agent_name,
+ backend=origin.backend,
+ turn_id=origin.turn_id,
+ visibility=AUDIT_VISIBILITY,
+ source="agent",
+ )
+ return row["id"]
+
+ return await self._write(session_id, work)
# --- implementation -------------------------------------------------------
@@ -305,7 +368,9 @@ class SQLiteTranscriptStore:
source="agent",
context_seq=seq,
)
- return ContextEntry(session_id, seq, kind, row["id"], message=message, payload=payload)
+ return ContextEntry(
+ session_id, seq, kind, row["id"], message=message, payload=payload, created_at=_epoch(row["created_at"])
+ )
def _load(self, session_id: str) -> list[ContextEntry]:
with self._engine.begin() as conn:
@@ -513,6 +578,7 @@ def _settled_result(conn: Connection, session_id: str, tool_call_id: str) -> Opt
agent_events.c.session_id,
agent_events.c.context_seq,
agent_events.c.content_json,
+ agent_events.c.created_at,
agent_events.c.event_type,
agent_events.c.visibility,
)
@@ -549,6 +615,7 @@ def source_tool_result(
agent_events.c.session_id,
agent_events.c.context_seq,
agent_events.c.content_json,
+ agent_events.c.created_at,
agent_events.c.event_type,
agent_events.c.visibility,
)
@@ -617,7 +684,9 @@ def _context_rows(conn: Connection, session_id: str, bound: Optional[int]) -> li
if bound is not None:
conditions.append(table.c.context_seq <= bound)
rows = conn.execute(
- select(table.c.id, table.c.context_seq, table.c.content_json, *columns).where(*conditions)
+ select(table.c.id, table.c.context_seq, table.c.content_json, table.c.created_at, *columns).where(
+ *conditions
+ )
).mappings()
entries.extend(to_entry(session_id, row) for row in rows)
return entries
@@ -634,7 +703,9 @@ def _message_entry(session_id: str, row: Mapping[str, Any]) -> ContextEntry:
raise TranscriptError(f"context row {row_id} has message type {row['type']!r}")
payload = _versioned(_json_object(row["content_json"], row_id).get("model"), row_id)
message = _message(payload.get("message"), expected, row_id)
- return ContextEntry(session_id, row["context_seq"], kind, row_id, message=message, payload=payload)
+ return ContextEntry(
+ session_id, row["context_seq"], kind, row_id, message=message, payload=payload, created_at=_epoch(row["created_at"])
+ )
def _event_entry(session_id: str, row: Mapping[str, Any]) -> ContextEntry:
@@ -644,7 +715,9 @@ def _event_entry(session_id: str, row: Mapping[str, Any]) -> ContextEntry:
raise TranscriptError(f"context row {row_id} is a {row['visibility']} {row['event_type']!r} event")
payload = _versioned(_json_object(row["content_json"], row_id), row_id)
message = _message(payload.get("message"), ToolResultMessage, row_id) if kind == "tool_result" else None
- return ContextEntry(session_id, row["context_seq"], kind, row_id, message=message, payload=payload)
+ return ContextEntry(
+ session_id, row["context_seq"], kind, row_id, message=message, payload=payload, created_at=_epoch(row["created_at"])
+ )
def _message(value: Any, expected: type, row_id: str) -> Any:
@@ -688,5 +761,28 @@ def _canonical(value: dict[str, Any], what: str) -> dict[str, Any]:
return json.loads(json.dumps(value))
+def _payload(kind: str, payload: Mapping[str, Any]) -> dict[str, Any]:
+ if kind not in ("compaction", "context_edit", "agent_state"):
+ raise ValueError(f"not a payload entry kind: {kind!r}")
+ data = _canonical(dict(payload), f"{kind} payload")
+ if not _is_current_version(data):
+ raise ValueError(f"a {kind} payload needs version {PAYLOAD_VERSION}")
+ return data
+
+
+def _epoch(value: Any) -> Optional[float]:
+ """A row's ``created_at`` (ISO 8601, UTC when it names no zone) as epoch seconds; None if it is not a time."""
+ text_value = str(value or "").strip()
+ if text_value.endswith("Z"):
+ text_value = text_value[:-1] + "+00:00"
+ try:
+ instant = datetime.fromisoformat(text_value)
+ except ValueError:
+ return None
+ if instant.tzinfo is None:
+ instant = instant.replace(tzinfo=timezone.utc)
+ return instant.timestamp()
+
+
def _utc_now() -> str:
return datetime.now(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
diff --git a/tests/agent_core/agent/test_compaction.py b/tests/agent_core/agent/test_compaction.py
new file mode 100644
index 000000000..775fe9142
--- /dev/null
+++ b/tests/agent_core/agent/test_compaction.py
@@ -0,0 +1,1232 @@
+"""C-9 through the loop, observed at the recording provider and the store.
+
+These cover what the pure rules in ``test_context.py`` cannot: when the loop
+applies them, what the forked checkpoint request carries, what the checkpoint
+turn may execute, how the overflow ladder steps, and the guards. The window is
+the fakes' 32,000 tokens with 4,096 output, so T = 19,904 and keep = 4,976.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import threading
+from collections import deque
+from copy import deepcopy
+from dataclasses import replace
+
+import pytest
+
+from core.agent_core.agent.checkpoint import BUDGET_USED, DENIED, CheckpointPolicy, Decision
+from core.agent_core.agent.scratch import ScratchRoot
+from core.agent_core.agent.events import (
+ AgentError,
+ AssistantTextDelta,
+ CompactionFailed,
+ CompactionFinished,
+ CompactionPaused,
+ ContextExhausted,
+ MessageCommitted,
+ RunEnded,
+ ToolStarted,
+)
+from core.agent_core.agent.hooks import Hooks
+from core.agent_core.agent.loop import Agent
+from core.agent_core.agent.models import RetryPolicy
+from core.agent_core.ai._common import endpoint_origin, prepare_messages
+from core.agent_core.ai.anthropic import build_messages_payload
+from core.agent_core.ai.openai_chat import build_chat_payload
+from core.agent_core.ai.openai_responses import build_responses_payload
+from core.agent_core.ai.provider import Done, ModelEndpoint, ProviderError, TextDelta
+from core.agent_core.agent.models import ModelSelection
+from core.agent_core.cancel import CancelToken
+from core.agent_core.harness.context import (
+ CHECKPOINT_REQUEST,
+ ContextConfig,
+ StateRequest,
+ message_tokens,
+ request_tokens,
+)
+from core.agent_core.harness.projection import project
+from core.agent_core.messages import (
+ AssistantMessage,
+ ThinkingBlock,
+ ToolCallBlock,
+ ToolResultMessage,
+ Usage,
+ UserMessage,
+ text,
+)
+from core.agent_core.tools.base import ToolResult
+from core.agent_core.tools.write import WriteTool
+from tests.agent_core.fakes import (
+ ENDPOINT,
+ SELECTION,
+ FakeJobHost,
+ FakeModelRouter,
+ FakeTool,
+ InMemoryTranscriptStore,
+ assistant,
+ input_row,
+)
+
+THRESHOLD = 19_904
+CHECKPOINT = "# 1. Self and method\n- the checkpoint"
+
+
+def tokens(count: int) -> str:
+ return "x" * (4 * count)
+
+
+def is_checkpoint(request) -> bool:
+ return any(
+ isinstance(message, UserMessage)
+ and message.content[0].text is not None
+ and message.content[0].text.startswith("<context-checkpoint-request>")
+ for message in request.messages
+ )
+
+
+def call(name: str, call_id: str, **arguments) -> list[Done]:
+ return [Done(assistant(calls=[ToolCallBlock(call_id, name, arguments)]))]
+
+
+class Model:
+ """Answers conversation requests and checkpoint-turn requests from separate scripts."""
+
+ protocol = "anthropic"
+
+ def __init__(self, conversation=(), checkpoint=()) -> None:
+ self.conversation = deque(conversation)
+ self.checkpoint = deque(checkpoint)
+ self.requests: list = []
+
+ @property
+ def conversation_requests(self):
+ return [request for request in self.requests if not is_checkpoint(request)]
+
+ @property
+ def checkpoint_requests(self):
+ return [request for request in self.requests if is_checkpoint(request)]
+
+ async def stream(self, request, cancel):
+ self.requests.append(deepcopy(request))
+ queue = self.checkpoint if is_checkpoint(request) else self.conversation
+ if not queue:
+ raise AssertionError("unscripted request")
+ script = queue.popleft()
+ for event in script(request) if callable(script) else script:
+ yield deepcopy(event)
+
+
+class Host:
+ def __init__(self) -> None:
+ self.states: list[StateRequest] = []
+ self.records: list[tuple[str, int]] = []
+
+ def earlier_record(self, session_id, through_seq):
+ self.records.append((session_id, through_seq))
+ return f"lookup {session_id} through {through_seq}"
+
+ async def render_state(self, request):
+ self.states.append(request)
+ return [f"<state skills={len(request.skills)} mid_turn={request.mid_turn}/>"]
+
+
+def make_agent(
+ model, *, store=None, tools=(), hooks=(), selection=SELECTION, context=None, cwd="/test-owned", **options
+):
+ selections = selection if isinstance(selection, tuple) else (selection,)
+ return Agent(
+ session_id="session",
+ models=FakeModelRouter(model, selections),
+ tools=tools,
+ hooks=hooks,
+ store=store or InMemoryTranscriptStore(),
+ jobs=FakeJobHost(),
+ cwd=cwd,
+ context=context or ContextConfig(),
+ **options,
+ )
+
+
+async def run(agent, value="go", row="input"):
+ return [event async for event in agent.run(input_row(row, value), turn_id=row)]
+
+
+def reader(output: str) -> FakeTool:
+ return FakeTool("read", result=ToolResult((text(output),)))
+
+
+def sized_reader(*sizes: int) -> FakeTool:
+ """A ``read`` whose results have the given sizes in tokens, in call order."""
+ remaining = deque(sizes)
+
+ async def execute(arguments, ctx):
+ return ToolResult((text(tokens(remaining.popleft())),))
+
+ return FakeTool("read", execute=execute)
+
+
+def reads(count: int, final: str = "done"):
+ return [call("read", f"read-{index}", path="f") for index in range(count)] + [[Done(assistant(final))]]
+
+
+def history():
+ """A first run whose context is past ``keep``, so a manual checkpoint has something to summarize."""
+ return [call("read", "h0", path="old"), call("read", "h1", path="old"), [Done(assistant("first"))]]
+
+
+def growing(count: int, final: str = "done"):
+ """``count`` reads of 6,000 tokens each, then a final reply; the fifth request crosses T."""
+ return [call("read", f"read-{index}", path=f"f{index}") for index in range(count)] + [[Done(assistant(final))]]
+
+
+async def test_a_threshold_checkpoint_forks_the_exact_prefix_and_leaves_checkpoint_and_tail():
+ host = Host()
+ model = Model(growing(4), [[TextDelta(0, "streamed checkpoint"), Done(assistant(CHECKPOINT))]])
+ agent = make_agent(model, tools=[reader(tokens(6_000))], context=ContextConfig(host=host))
+ events = await run(agent)
+
+ previous, fork, after = model.requests[3], model.requests[4], model.requests[5]
+ assert [is_checkpoint(request) for request in model.requests] == [False] * 4 + [True, False]
+ # Cache safety: the fork is the previous request extended, with every cache-relevant setting unchanged.
+ assert fork.messages[: len(previous.messages)] == previous.messages
+ assert fork.messages[-1].content[0].text.startswith(CHECKPOINT_REQUEST)
+ for field in ("endpoint", "system", "tools", "reasoning_effort", "supports_images", "cache", "max_tokens"):
+ assert getattr(fork, field) == getattr(previous, field)
+
+ rows = await agent.store.load("session")
+ compaction = next(row for row in rows if row.kind == "compaction")
+ before = [row for row in rows if row.context_seq < compaction.context_seq]
+ assert fork.messages[:-1] == project(before).messages # the whole conversation, then the request
+ assert compaction.payload["mode"] == "normal" and compaction.payload["reason"] == "threshold"
+ assert compaction.payload["checkpoint"] == CHECKPOINT
+ assert host.states == [StateRequest("session", (), True)]
+ assert host.records == [("session", compaction.payload["summarized_to_seq"])]
+
+ # The next request: the checkpoint message (summary, then state), then the kept tool batch.
+ checkpoint, *tail = after.messages
+ summary, state = (block.text for block in checkpoint.content)
+ assert CHECKPOINT in summary and "<current-request>\ngo\n</current-request>" in summary
+ assert "lookup session through" in summary and state == "<state skills=0 mid_turn=True/>"
+ assert [type(message).__name__ for message in tail] == ["AssistantMessage", "ToolResultMessage"]
+ assert tail[0].tool_calls[0].id == "read-3"
+ assert after.messages == project(rows[: len(rows) - 1]).messages
+ assert request_tokens(after.system, after.tools, after.messages) < THRESHOLD
+
+ # Silent: nothing streamed or executed by the checkpoint turn reaches the events.
+ assert [event.reason for event in events if isinstance(event, CompactionFinished)] == ["threshold"]
+ assert not [event for event in events if isinstance(event, AssistantTextDelta)]
+ assert len([event for event in events if isinstance(event, MessageCommitted)]) == 5
+ assert events[-1] == RunEnded("input", events[-1].seq, "completed")
+ (session_id, _, audit), = agent.store.audits
+ assert (audit["outcome"], audit["compaction_event_id"]) == ("completed", compaction.row_id)
+ assert [message["role"] for message in audit["messages"]] == ["assistant"]
+ # Append-only: every row before the checkpoint is exactly what was committed before it.
+ assert all(row.kind != "compaction" for row in before) and rows.index(compaction) == len(before)
+
+
+def _strip_cache_markers(value):
+ if isinstance(value, dict):
+ return {key: _strip_cache_markers(item) for key, item in value.items() if key != "cache_control"}
+ if isinstance(value, list):
+ return [_strip_cache_markers(item) for item in value]
+ return value
+
+
+async def _wire(request):
+ prepared = await prepare_messages(
+ request.messages,
+ target=endpoint_origin(request.endpoint),
+ supports_images=request.supports_images,
+ protocol=request.endpoint.protocol,
+ media_loader=None,
+ cancel=CancelToken(),
+ )
+ messages, images = prepared
+ build = {
+ "anthropic": build_messages_payload,
+ "openai_chat": build_chat_payload,
+ "openai_responses": build_responses_payload,
+ }[request.endpoint.protocol]
+ payload = _strip_cache_markers(build(request, messages, loaded_images=images))
+ key = "input" if request.endpoint.protocol == "openai_responses" else "messages"
+ items = payload.pop(key)
+ return payload, [json.dumps(item, ensure_ascii=False, sort_keys=True).encode() for item in items]
+
+
[email protected]("protocol", ["anthropic", "openai_chat", "openai_responses"])
+async def test_the_fork_is_a_byte_identical_prefix_on_every_protocol_wire(protocol):
+ endpoint = ModelEndpoint(protocol, "http://model.invalid", "test-model", "", provider="test-provider")
+ capabilities = replace(SELECTION.capabilities, supports_reasoning=True, reasoning_efforts=("high",))
+ selection = ModelSelection(endpoint, capabilities)
+ model = Model(growing(4), [[Done(assistant(CHECKPOINT))]])
+ agent = make_agent(model, tools=[reader(tokens(6_000))], selection=selection)
+ agent.reasoning_effort = "high"
+ await run(agent)
+ previous, fork = model.requests[3], model.requests[4]
+ assert is_checkpoint(fork) and fork.reasoning_effort == "high"
+ previous_settings, previous_items = await _wire(previous)
+ fork_settings, fork_items = await _wire(fork)
+ assert fork_settings == previous_settings # model, system, tools, tool choice, thinking, effort, output cap
+ assert fork_items[: len(previous_items)] == previous_items
+ assert len(fork_items) > len(previous_items)
+
+
+def scratch_case(tmp_path):
+ scratch = tmp_path / "scratch" / "session"
+ outside = tmp_path / "outside"
+ scratch.mkdir(parents=True)
+ outside.mkdir()
+ (scratch / "escape").symlink_to(outside, target_is_directory=True)
+ return scratch, outside
+
+
+async def test_the_checkpoint_policy_allows_reads_and_scratch_writes_and_never_runs_anything_else(tmp_path):
+ scratch, outside = scratch_case(tmp_path)
+ cwd = str(tmp_path)
+ tools = {name: FakeTool(name) for name in ("write", "edit", "bash", "other")}
+ tools["read"] = reader(tokens(3_000))
+ calls = [
+ ToolCallBlock("bash", "bash", {"command": "rm -rf /"}),
+ ToolCallBlock("read", "read", {"path": "notes.md"}),
+ ToolCallBlock("write-in", "write", {"path": "scratch/session/plan.md", "content": "a\n"}),
+ ToolCallBlock("edit-in", "edit", {"path": str(scratch / "plan.md"), "oldText": "a", "newText": "b"}),
+ ToolCallBlock("write-out", "write", {"path": str(outside / "f"), "content": "no"}),
+ ToolCallBlock("write-up", "write", {"path": "scratch/session/../../outside/f", "content": "no"}),
+ ToolCallBlock("write-link", "write", {"path": "scratch/session/escape/f", "content": "no"}),
+ ToolCallBlock("edit-out", "edit", {"path": "notes.md", "edits": [{"oldText": "a", "newText": "b"}]}),
+ ToolCallBlock("other", "other", {}),
+ ]
+ model = Model(
+ history(),
+ [[Done(AssistantMessage(tuple(calls), assistant().origin, "tool_use"))], [Done(assistant(CHECKPOINT))]],
+ )
+ context = ContextConfig(scratch_dir=str(scratch))
+ agent = make_agent(model, tools=list(tools.values()), context=context, cwd=cwd)
+ await run(agent)
+ before = await agent.store.load("session")
+ events = [event async for event in agent.compact(turn_id="compact")]
+
+ executed = {name: [ctx.tool_call_id for _, ctx in tool.calls] for name, tool in tools.items()}
+ # Scratch writes and edits go through the root's descriptor, never through a tool or a pathname.
+ assert executed == {"read": ["h0", "h1", "read"], "write": [], "edit": [], "bash": [], "other": []}
+ assert (scratch / "plan.md").read_text() == "b\n" and not os.listdir(outside)
+ results = {message.tool_call_id: message for message in model.requests[-1].messages[-len(calls) :]}
+ denied = {key for key, message in results.items() if message.content[0].text == DENIED}
+ assert denied == {"bash", "write-out", "write-up", "write-link", "edit-out", "other"}
+ assert all(results[key].is_error for key in denied)
+ # The turn's own calls and results are audit only: the context has none of them.
+ rows = await agent.store.load("session")
+ assert rows[: len(before)] == before
+ assert [row.kind for row in rows[len(before) :]] == ["compaction"]
+ assert not [event for event in events if isinstance(event, ToolStarted)]
+ assert len(agent.store.audits[0][2]["messages"]) == 2 + len(calls)
+ assert events[-1].reason == "completed"
+
+
[email protected]("malformed", ["duplicate call ids", "arguments that are not JSON"])
+async def test_a_malformed_checkpoint_response_fails_the_checkpoint_before_any_call_runs(malformed):
+ # Admission is one path for every response (invariant 6): the checkpoint turn's are checked before any call.
+ if malformed == "duplicate call ids":
+ calls = (ToolCallBlock("same", "read", {"path": "a"}), ToolCallBlock("same", "read", {"path": "b"}))
+ else:
+ calls = (ToolCallBlock("odd", "read", {"path": "a"}),)
+ calls[0].arguments["path"] = float("nan") # valid when built, changed after: the arguments are mutable
+ read = reader(tokens(3_000))
+ model = Model(history(), [[Done(AssistantMessage(calls, assistant().origin, "tool_use"))]])
+ agent = make_agent(model, tools=[read])
+ await run(agent)
+ before = await agent.store.load("session")
+ events = [event async for event in agent.compact(turn_id="compact")]
+
+ assert [ctx.tool_call_id for _, ctx in read.calls] == ["h0", "h1"] # no call of the checkpoint turn ran
+ failed = [event for event in events if isinstance(event, CompactionFailed)]
+ assert len(failed) == 1 and failed[0].error.startswith("Provider protocol violation")
+ rows = await agent.store.load("session")
+ assert rows[: len(before)] == before and [row.kind for row in rows[len(before) :]] == ["agent_state"]
+ assert rows[-1].payload["context"]["failures"] == 1 # a failed checkpoint, counted by the guard
+ audit = agent.store.audits[-1][2]
+ assert audit["outcome"] == "failed" and audit["error"] == failed[0].error
+ # The audit keeps the refused response when JSON can hold it.
+ assert len(audit["messages"]) == (1 if malformed == "duplicate call ids" else 0)
+
+
+async def test_a_target_the_platform_cannot_compare_with_the_scratch_dir_is_denied(tmp_path, monkeypatch):
+ # On Windows, commonpath raises ValueError for paths on different drives (D:\\notes.txt vs C:\\scratch).
+ def other_drive(paths):
+ raise ValueError("Paths don't have the same drive")
+
+ policy = CheckpointPolicy(cwd=str(tmp_path), scratch_dir=str(tmp_path / "scratch"))
+ monkeypatch.setattr("core.agent_core.agent.checkpoint.os.path.commonpath", other_drive)
+ write = ToolCallBlock("w", "write", {"path": str(tmp_path / "elsewhere"), "content": "no"})
+ assert policy.decide(write) == Decision(denial=DENIED)
+
+
+async def test_the_checkpoint_turn_gets_five_tool_rounds_then_must_write():
+ tools = [reader(tokens(3_000)), FakeTool("bash")]
+ rounds = [call("read", f"r{index}", path="f") for index in range(5)]
+ sixth = [ToolCallBlock("r5", "read", {"path": "f"}), ToolCallBlock("b5", "bash", {"command": "ls"})]
+ rounds.append([Done(AssistantMessage(tuple(sixth), assistant().origin, "tool_use"))])
+ rounds.append(call("read", "r6", path="f"))
+ model = Model(history(), rounds)
+ agent = make_agent(model, tools=tools)
+ await run(agent)
+ before = await agent.store.load("session")
+ tools[0].result = ToolResult((text("small"),))
+ events = [event async for event in agent.compact(turn_id="compact")]
+ assert [ctx.tool_call_id for _, ctx in tools[0].calls] == ["h0", "h1", "r0", "r1", "r2", "r3", "r4"]
+ # Once the budget is used up, every call is told so, whatever the table says about it.
+ answered = [(message.tool_call_id, message.content[0].text) for message in model.requests[-1].messages[-2:]]
+ assert answered == [("r5", BUDGET_USED), ("b5", BUDGET_USED)]
+ assert not tools[1].calls
+ failed = [event for event in events if isinstance(event, CompactionFailed)]
+ assert len(failed) == 1 and "kept calling tools" in failed[0].error
+ after = await agent.store.load("session")
+ assert after[: len(before)] == before and [row.kind for row in after[len(before) :]] == ["agent_state"]
+ assert after[-1].payload["context"] == {"failures": 1, "ineffective": 0, "paused": False}
+ assert events[-1].reason == "error"
+
+
+async def test_a_threshold_checkpoint_may_read_while_the_window_has_room_and_never_past_it():
+ # Crossing T at ~20,000 tokens leaves ~7,100 tokens of room in the 32,000 window: the read runs, cut to fit.
+ peek = [call("read", "peek", path="f"), [Done(assistant(CHECKPOINT))]]
+ model = Model(reads(4), peek)
+ tool = sized_reader(6_000, 6_000, 6_000, 2_000, 10_000)
+ agent = make_agent(model, tools=[tool])
+ await run(agent)
+ assert [ctx.tool_call_id for _, ctx in tool.calls] == ["read-0", "read-1", "read-2", "read-3", "peek"]
+ first, second = model.checkpoint_requests
+ room = 32_000 - request_tokens(first.system, first.tools, first.messages) - 4_096
+ room -= message_tokens(second.messages[-2]) # the response carrying the call
+ result = second.messages[-1]
+ assert result.content[-1].text.startswith("[Output truncated to fit this checkpoint turn: showing about")
+ assert message_tokens(result) <= room - 1_000
+ assert request_tokens(second.system, second.tools, second.messages) + 4_096 <= 32_000
+
+ # Crossing T at ~24,000 tokens leaves under the 4,000-token floor: the read is denied and never runs.
+ model = Model(reads(4), [call("read", "peek", path="f"), [Done(assistant(CHECKPOINT))]])
+ tool = reader(tokens(6_000))
+ agent = make_agent(model, tools=[tool])
+ await run(agent)
+ assert [ctx.tool_call_id for _, ctx in tool.calls] == ["read-0", "read-1", "read-2", "read-3"]
+ assert model.checkpoint_requests[-1].messages[-1].content[0].text == BUDGET_USED
+
+ # A response that leaves under 1,000 tokens of room still gets the policy's fixed text, never a cut of it:
+ # a truncation note would tell the model to read again, and another call fails the turn.
+ long = AssistantMessage(
+ (ThinkingBlock(tokens(6_500)), ToolCallBlock("peek", "read", {"path": "f"})), assistant().origin, "tool_use"
+ )
+ model = Model(reads(4), [[Done(long)], [Done(assistant(CHECKPOINT))]])
+ tool = sized_reader(6_000, 6_000, 6_000, 2_000)
+ agent = make_agent(model, tools=[tool])
+ events = await run(agent)
+ first, second = model.checkpoint_requests
+ room = 32_000 - request_tokens(first.system, first.tools, first.messages) - 4_096 - message_tokens(long)
+ assert room < 1_000 + message_tokens(second.messages[-1]) # the bound would have cut it
+ assert second.messages[-1].content == (text(BUDGET_USED),)
+ assert [event.mode for event in events if isinstance(event, CompactionFinished)] == ["normal"]
+
+
+async def test_a_checkpoint_turn_reserves_room_for_every_result_of_its_batch():
+ # Sixty parallel reads at a threshold checkpoint: the first runs, the rest get the fixed text. Room for all of
+ # those results is reserved before any call runs, so the next checkpoint request still fits and succeeds.
+ calls = tuple(ToolCallBlock(f"c{index}", "read", {"path": f"f{index}"}) for index in range(60))
+ batch = AssistantMessage(calls, assistant().origin, "tool_use")
+ model = Model(reads(4), [[Done(batch)], [Done(assistant(CHECKPOINT))]])
+ tool = sized_reader(6_000, 6_000, 6_000, 2_000, 9_000)
+ agent = make_agent(model, tools=[tool])
+ events = await run(agent)
+ assert [event.mode for event in events if isinstance(event, CompactionFinished)] == ["normal"]
+ second = model.checkpoint_requests[-1]
+ results = [message for message in second.messages if isinstance(message, ToolResultMessage)][-60:]
+ assert [message.tool_call_id for message in results] == [call.id for call in calls]
+ assert sum(message.content[0].text == BUDGET_USED for message in results) >= 59
+ assert request_tokens(second.system, second.tools, second.messages) + 4_096 <= 32_000
+
+
+class FailingHost(Host):
+ def __init__(self, step: str) -> None:
+ super().__init__()
+ self.step = step
+
+ def earlier_record(self, session_id, through_seq):
+ if self.step == "earlier_record":
+ raise RuntimeError("lookup unavailable")
+ return super().earlier_record(session_id, through_seq)
+
+ async def render_state(self, request):
+ if self.step == "render_state":
+ raise RuntimeError("state store unavailable")
+ return await super().render_state(request)
+
+
+_TWIN_READS = (ToolCallBlock("same", "read", {"path": "a"}), ToolCallBlock("same", "read", {"path": "b"}))
+
+
+#: An 8,000-token window: the forked request over the history cannot fit it.
+SMALL = ModelSelection(ENDPOINT, replace(SELECTION.capabilities, context_window=8_000))
+
+
[email protected]("step", ["compose", "provider", "admission", "render_state", "earlier_record", "row", "commit"])
+async def test_a_checkpoint_turn_is_finalized_once_whatever_step_fails(step, monkeypatch):
+ # Invariant 4 for checkpoint turns: one audit on every exit. A failed request (compose, provider, admission) or a
+ # host failure after the model answered is a failed checkpoint, counted; an engine error building the row or a
+ # store failure ends the run with nothing landed (invariant 3), and still leaves the audit.
+ answers = {
+ "provider": [ProviderError("server", "upstream failed", False)],
+ "admission": [Done(AssistantMessage(_TWIN_READS, assistant().origin, "tool_use"))],
+ }
+ store = FailingTransactionStore(failures=0)
+ await run(make_agent(Model(history()), store=store, tools=[reader(tokens(3_000))]))
+ before = await store.load("session")
+ if step == "row":
+ def broken(*args, **kwargs):
+ raise ValueError("engine bug")
+
+ monkeypatch.setattr("core.agent_core.agent.loop.compaction_payload", broken)
+ store.failures = 1 if step == "commit" else 0
+ model = Model([], [answers.get(step, [Done(assistant(CHECKPOINT))])])
+ agent = make_agent(
+ model,
+ store=store,
+ tools=[reader(tokens(3_000))],
+ selection=SMALL if step == "compose" else SELECTION,
+ context=ContextConfig(host=FailingHost(step)),
+ )
+ events = [event async for event in agent.compact(turn_id="compact")]
+
+ assert [audit["outcome"] for _, _, audit in store.audits] == ["failed"]
+ # The turn's response from the ledger; a request never sent, or a provider error with no partial, has none.
+ assert len(store.audits[0][2]["messages"]) == (0 if step in ("compose", "provider") else 1)
+ rows = await store.load("session")
+ if step in ("row", "commit"):
+ assert rows == before and events[-1].reason == "error"
+ else:
+ assert [row.kind for row in rows[len(before) :]] == ["agent_state"]
+ assert rows[-1].payload["context"]["failures"] == 1
+ failed = [event for event in events if isinstance(event, CompactionFailed)]
+ assert len(failed) == 1 and store.audits[0][2]["error"] == failed[0].error
+
+
+async def test_a_manual_compact_with_nothing_older_than_the_tail_is_skipped_without_a_model_call():
+ model = Model([[Done(assistant("short"))]])
+ agent = make_agent(model)
+ await run(agent)
+ before = await agent.store.load("session")
+ events = [event async for event in agent.compact(turn_id="compact")]
+ assert [type(event).__name__ for event in events] == ["RunStarted", "CompactionSkipped", "RunEnded"]
+ assert events[-1].reason == "completed"
+ assert len(model.requests) == 1 and await agent.store.load("session") == before
+
+
+FAILURES = [
+ [Done(assistant(CHECKPOINT, stop_reason="length"))],
+ [Done(AssistantMessage((ThinkingBlock("only thinking"),), assistant().origin, "stop"))],
+ [ProviderError("server", "upstream failed", False)],
+]
+
+
+ "response",
+ [
+ assistant(CHECKPOINT, stop_reason="tool_use"), # a tool-use stop with no call is not a final answer
+ assistant(CHECKPOINT, calls=[ToolCallBlock("c", "read", {"path": "f"})], stop_reason="stop"),
+ assistant(CHECKPOINT, stop_reason="refusal"),
+ ],
+)
+async def test_only_a_stop_with_text_and_no_calls_is_a_checkpoint(response):
+ model = Model(history(), [[Done(response)]])
+ tool = reader(tokens(3_000))
+ agent = make_agent(model, tools=[tool])
+ await run(agent)
+ events = [event async for event in agent.compact(turn_id="compact")]
+ assert [type(event).__name__ for event in events if "Compaction" in type(event).__name__] == [
+ "CompactionStarted",
+ "CompactionFailed",
+ ]
+ assert not [row for row in await agent.store.load("session") if row.kind == "compaction"]
+ assert [ctx.tool_call_id for _, ctx in tool.calls] == ["h0", "h1"] # the call was never run
+
+
+async def test_the_checkpoint_usage_keeps_every_reported_field():
+ def with_usage(message, reasoning):
+ usage = Usage(input_tokens=100, output_tokens=10, cache_read_tokens=5, reasoning_tokens=reasoning)
+ return [Done(replace(message, usage=usage))]
+
+ turn = [with_usage(assistant(calls=[ToolCallBlock("r", "read", {"path": "f"})]), 7), with_usage(assistant(CHECKPOINT), 3)]
+ model = Model(history(), turn)
+ agent = make_agent(model, tools=[reader(tokens(3_000))])
+ await run(agent)
+ assert [event async for event in agent.compact(turn_id="compact")][-1].reason == "completed"
+ expected = {"input_tokens": 200, "output_tokens": 20, "cache_read_tokens": 10, "cache_write_tokens": 0, "reasoning_tokens": 10}
+ compaction = next(row for row in await agent.store.load("session") if row.kind == "compaction")
+ assert compaction.payload["usage"] == expected
+ assert agent.store.audits[0][2]["usage"] == expected
+
+
+async def test_failed_checkpoints_leave_the_context_and_three_pause_auto_compaction_until_manual():
+ store = InMemoryTranscriptStore()
+ model = Model(reads(7), FAILURES)
+ agent = make_agent(model, store=store, tools=[sized_reader(6_000, 6_000, 6_000, 2_000, 500, 500, 500)])
+ events = await run(agent)
+ # Requests 5, 6 and 7 each cross T, try once, fail, and are sent unchanged; request 8 is paused.
+ assert len(model.checkpoint_requests) == 3 and len(model.conversation_requests) == 8
+ assert not [row for row in await store.load("session") if row.kind == "compaction"]
+ assert [event.error.split(":")[0] for event in events if isinstance(event, CompactionFailed)] == [
+ "The checkpoint turn stopped with length and no usable checkpoint.",
+ "The checkpoint turn ended without checkpoint text.",
+ "server",
+ ]
+ assert [event.cause for event in events if isinstance(event, CompactionPaused)] == ["failures"]
+ assert [audit["outcome"] for _, _, audit in store.audits] == ["failed"] * 3
+
+ # Durable: a new Agent over the same rows stays paused and sends no checkpoint request.
+ model = Model([call("read", "again", path="f"), [Done(assistant("ok"))]])
+ resumed = make_agent(model, store=store, tools=[reader(tokens(1))])
+ events = await run(resumed, row="next")
+ assert not model.checkpoint_requests and not [e for e in events if isinstance(e, CompactionPaused)]
+
+ # Manual /compact clears the pause, and its success resets the counters.
+ model = Model([], [[Done(assistant(CHECKPOINT))]])
+ manual = make_agent(model, store=store, tools=[reader(tokens(1))])
+ events = [event async for event in manual.compact(turn_id="compact", focus="the parser")]
+ assert model.checkpoint_requests[0].messages[-1].content[0].text.endswith(
+ "Additional focus from the user: the parser\n</context-checkpoint-request>"
+ )
+ assert [type(event).__name__ for event in events if "Compaction" in type(event).__name__] == [
+ "CompactionStarted",
+ "CompactionFinished",
+ ]
+ state = [row for row in await store.load("session") if row.kind == "agent_state"][-1]
+ assert state.payload["context"] == {"failures": 0, "ineffective": 0, "paused": False}
+ assert store.transactions[-1] == ["agent_state", "compaction"] # the cleared pause commits with the checkpoint
+
+
+async def test_the_guard_is_durable_before_its_outcome_is_announced():
+ store = InMemoryTranscriptStore()
+ model = Model(reads(7), FAILURES)
+ agent = make_agent(model, store=store, tools=[sized_reader(6_000, 6_000, 6_000, 2_000, 500, 500, 500)])
+ seen = []
+ async for event in agent.run(input_row("input", "go"), turn_id="input"):
+ if isinstance(event, (CompactionFailed, CompactionPaused)):
+ # A crash right after this event must not lose the transition it announces.
+ state = [row for row in await store.load("session") if row.kind == "agent_state"][-1]
+ seen.append((type(event).__name__, state.payload["context"]["failures"], state.payload["context"]["paused"]))
+ assert seen == [
+ ("CompactionFailed", 1, False),
+ ("CompactionFailed", 2, False),
+ ("CompactionFailed", 3, True),
+ ("CompactionPaused", 3, True),
+ ]
+
+
+async def test_a_failed_checkpoint_attempt_keeps_every_partial_in_its_audit():
+ retried = assistant("", stop_reason="error")
+ retried = replace(retried, usage=Usage(input_tokens=50, output_tokens=0))
+ streamed = replace(assistant("half a checkpoint", stop_reason="error"), usage=Usage(input_tokens=70, output_tokens=9))
+ turn = [
+ [ProviderError("server", "upstream reset", True, partial=retried)],
+ [ProviderError("server", "upstream failed", False, partial=streamed)],
+ ]
+ model = Model(history(), turn)
+ agent = make_agent(model, tools=[reader(tokens(3_000))], retry=RetryPolicy(initial_delay_s=0))
+ await run(agent)
+ assert [event async for event in agent.compact(turn_id="compact")][-1].reason == "error"
+ (_, _, audit), = agent.store.audits
+ assert audit["outcome"] == "failed"
+ assert [message["content"] for message in audit["messages"]] == [[], [{"type": "text", "text": "half a checkpoint"}]]
+ assert audit["usage"] == {"input_tokens": 120, "output_tokens": 9, "cache_read_tokens": 0, "cache_write_tokens": 0}
+
+
+async def test_a_checkpoint_turn_measures_each_request_on_the_route_resolved_for_it():
+ # The route resolves again for the turn's second request and lands on a 12,000-token window with 2,048 output.
+ small = ModelSelection(ENDPOINT, replace(SELECTION.capabilities, context_window=12_000, max_output_tokens=2_048))
+ store = InMemoryTranscriptStore()
+ await run(make_agent(Model(history()), store=store, tools=[reader(tokens(3_000))]))
+ tool = reader("small")
+ model = Model([], [call("read", "first", path="f"), call("read", "second", path="f"), [Done(assistant(CHECKPOINT))]])
+ agent = make_agent(model, store=store, tools=[tool], selection=(SELECTION, small))
+ assert [event async for event in agent.compact(turn_id="compact")][-1].reason == "completed"
+ first, second, third = model.checkpoint_requests
+ assert (first.max_tokens, second.max_tokens) == (4_096, 2_048)
+ # On the small window the second read no longer fits the floor: denied, never run.
+ assert [ctx.tool_call_id for _, ctx in tool.calls] == ["first"]
+ assert third.messages[-1].content[0].text == BUDGET_USED
+
+
+def billed(message: AssistantMessage, ratio: float = 1.0):
+ """A script answering with ``message``, billed ``ratio`` x the request's UTF-8/4 size (a tokenizer)."""
+
+ def script(request):
+ size = request_tokens(request.system, request.tools, request.messages)
+ return [Done(replace(message, usage=Usage(input_tokens=int(size * ratio), output_tokens=10)))]
+
+ return script
+
+
+ENGLISH = "The quick brown fox jumps over the lazy dog. " * 4
+
+
+def english(count: int) -> str:
+ """About ``count`` UTF-8/4 tokens of English, which a real tokenizer counts about 20% lower."""
+ return (ENGLISH * (count * 4 // len(ENGLISH) + 1))[: count * 4]
+
+
+async def _english_turn(store, *, context=True):
+ read = billed(assistant(calls=[ToolCallBlock("r", "read", {"path": "notes.md"})]), 0.8)
+ model = Model([read, billed(assistant("Summary of the notes."), 0.8)])
+ agent = Agent(
+ session_id="session",
+ models=FakeModelRouter(model),
+ tools=[reader(english(18_000))],
+ hooks=(),
+ store=store,
+ jobs=FakeJobHost(),
+ cwd="/test-owned",
+ context=ContextConfig() if context else None,
+ )
+ await run(agent, english(100), row="first")
+
+
+async def test_a_new_turn_on_a_large_english_conversation_uses_the_stored_anchor_and_does_not_compact_early():
+ # The second Turn's request is about 20,300 UTF-8/4 tokens, past T, but the last response's real usage
+ # (80% of the bytes) plus what came after it is about 16,900: no checkpoint.
+ store = InMemoryTranscriptStore()
+ await _english_turn(store)
+ model = Model([[Done(assistant("ok"))]], [[Done(assistant(CHECKPOINT))]])
+ events = await run(make_agent(model, store=store), english(2_000), row="second")
+ assert not model.checkpoint_requests and events[-1].reason == "completed"
+ request = model.conversation_requests[0]
+ assert request_tokens(request.system, request.tools, request.messages) >= THRESHOLD
+
+ # The same conversation written without request facts has no anchor: the bytes say compact.
+ store = InMemoryTranscriptStore()
+ await _english_turn(store, context=False)
+ model = Model([[Done(assistant("ok"))]], [[Done(assistant(CHECKPOINT))]])
+ await run(make_agent(model, store=store), english(2_000), row="second")
+ assert len(model.checkpoint_requests) == 1
+
+
+async def test_the_request_right_after_a_checkpoint_is_measured_and_rolls_when_it_does_not_fit():
+ big = [[Done(assistant(tokens(16_000)))], [Done(assistant("short"))]]
+ model = Model(reads(6), big)
+ agent = make_agent(model, tools=[sized_reader(5_000, 5_000, 5_000, 2_000, 2_000, 2_000)])
+ events = await run(agent)
+ assert [event.mode for event in events if isinstance(event, CompactionFinished)] == ["normal", "rolling"]
+ for request in model.conversation_requests:
+ assert request_tokens(request.system, request.tools, request.messages) + 4_096 + 8_000 <= 32_000
+
+
+async def test_three_ineffective_checkpoints_pause_auto_compaction():
+ bloated = [[Done(assistant(tokens(15_000)))] for _ in range(3)]
+ model = Model(reads(7), bloated)
+ agent = make_agent(model, tools=[sized_reader(6_000, 6_000, 6_000, 6_000, 5_000, 5_000, 5_000)])
+ events = await run(agent)
+ finished = [event for event in events if isinstance(event, CompactionFinished)]
+ assert len(finished) == 3 and all(event.tokens_after_estimate >= 0.75 * THRESHOLD for event in finished)
+ assert [event.cause for event in events if isinstance(event, CompactionPaused)] == ["ineffective"]
+ assert len(model.checkpoint_requests) == 3 # the fourth crossing is skipped
+
+
+OVERFLOW = ProviderError("overflow", "prompt is too long: 40000 tokens > 32000 maximum", False, status=400)
+
+
+async def test_a_provider_overflow_below_T_takes_a_normal_checkpoint_and_retries():
+ model = Model(
+ [call("read", "r0", path="f"), call("read", "r1", path="f"), [OVERFLOW], [Done(assistant("done"))]],
+ [[Done(assistant(CHECKPOINT))]],
+ )
+ agent = make_agent(model, tools=[reader(tokens(4_000))])
+ events = await run(agent)
+ assert [is_checkpoint(request) for request in model.requests] == [False, False, False, True, False]
+ rows = await agent.store.load("session")
+ compaction = next(row for row in rows if row.kind == "compaction")
+ assert (compaction.payload["mode"], compaction.payload["reason"]) == ("normal", "overflow")
+ assert model.requests[-1].messages == project(rows[:-1]).messages
+ assert events[-1].reason == "completed"
+
+
+def _long_context(count: int):
+ return [call("read", f"r{index}", path="f") for index in range(count)]
+
+
+#: A 200,000-token window, where 45,000 tokens of history are well below T.
+LARGE = ModelSelection(ENDPOINT, replace(SELECTION.capabilities, context_window=200_000))
+
+
+async def _history_on_a_large_window(store, sizes, *, row="before"):
+ model = Model(reads(len(sizes), final="noted"))
+ agent = make_agent(model, store=store, tools=[sized_reader(*sizes)], selection=LARGE)
+ events = await run(agent, row=row)
+ assert not model.checkpoint_requests and events[-1].reason == "completed"
+
+
+async def test_the_ladder_rolls_when_no_fork_can_take_the_whole_context():
+ # The route moves to the 32,000-token window with 45,000 tokens of history: a smaller window than expected.
+ store = InMemoryTranscriptStore()
+ await _history_on_a_large_window(store, [5_000] * 9)
+ before = await store.load("session")
+ model = Model([[Done(assistant("done"))]], [[Done(assistant("ROLL ONE"))], [Done(assistant("ROLL TWO"))]])
+ agent = make_agent(model, store=store)
+ events = await run(agent)
+ first, second = model.checkpoint_requests
+ request = model.conversation_requests[-1]
+ rows = await store.load("session")
+ compactions = [row for row in rows if row.kind == "compaction"]
+ assert [(row.payload["mode"], row.payload["reason"]) for row in compactions] == [("rolling", "overflow")] * 2
+ # (b): the first fork carries only the earliest part, a prefix of the request that did not fit.
+ whole = project(rows[: compactions[0].context_seq - 1]).messages
+ assert first.messages[:-1] == whole[: len(first.messages) - 1] and len(first.messages) - 1 < len(whole)
+ assert abs(request_tokens("", (), first.messages[:-1]) - request_tokens("", (), whole) / 2) < 5_100
+ assert compactions[0].payload["first_kept_seq"] > before[0].context_seq
+ # Rolling again: the second fork's prefix starts with the first checkpoint.
+ assert "ROLL ONE" in second.messages[0].content[0].text
+ assert "ROLL TWO" in request.messages[0].content[0].text
+ assert rows[-1].kind == "response" and request.messages == project(rows[:-1]).messages
+ assert request_tokens(request.system, request.tools, request.messages) + 4_096 + 8_000 <= 32_000
+ assert events[-1].reason == "completed"
+
+
+async def test_the_ladder_drops_mechanically_once_a_checkpoint_request_fails():
+ store = InMemoryTranscriptStore()
+ await _history_on_a_large_window(store, [5_000] * 12)
+ model = Model([], [[Done(assistant(CHECKPOINT))]])
+ manual = make_agent(model, store=store, selection=LARGE)
+ assert [event async for event in manual.compact(turn_id="compact")][-1].reason == "completed"
+ await _history_on_a_large_window(store, [5_000] * 4, row="more")
+
+ model = Model([[Done(assistant("done"))]], [[ProviderError("server", "down", False)]])
+ agent = make_agent(model, store=store)
+ events = await run(agent)
+ assert len(model.checkpoint_requests) == 1 # the rolling request; after it fails, no model is called
+ assert [event.reason for event in events if isinstance(event, CompactionFailed)] == ["overflow"]
+ manual_row, *drops = [row for row in await store.load("session") if row.kind == "compaction"]
+ finished = [(event.reason, event.mode) for event in events if isinstance(event, CompactionFinished)]
+ assert drops and finished == [("overflow", "dropped")] * len(drops)
+ for dropped in drops:
+ assert dropped.payload["mode"] == "dropped" and dropped.payload["summarizer"] is None
+ # The older checkpoint is kept, with its framing; only the earliest verbatim part moved out.
+ assert dropped.payload["checkpoint"] == CHECKPOINT
+ assert dropped.payload["summary"].startswith("<context-checkpoint>\nThis is a record")
+ assert dropped.payload["first_kept_seq"] > manual_row.payload["first_kept_seq"]
+ assert model.conversation_requests[-1].messages[0].content[0].text == drops[-1].payload["summary"]
+ assert events[-1].reason == "completed"
+
+
+async def test_the_ladder_stops_with_what_fills_the_context_when_nothing_more_can_move():
+ # One result of 30,000 tokens: only the current request and that tool batch are left, and they do not fit.
+ model = Model([call("read", "huge", path="f")])
+ agent = make_agent(model, tools=[reader(tokens(30_000))])
+ events = await run(agent)
+ exhausted = next(event for event in events if isinstance(event, ContextExhausted))
+ assert exhausted.limit == 32_000
+ parts = {part.name: part.tokens for part in exhausted.parts}
+ assert set(parts) == {"system", "tools", "history", "latest_tool_batch", "output"}
+ assert parts["latest_tool_batch"] > 30_000 and parts["output"] == 4_096 + 8_000
+ assert [(e.kind) for e in events if isinstance(e, AgentError)] == ["context_exhausted"]
+ assert events[-1].reason == "context_exhausted"
+ assert not model.checkpoint_requests # nothing to summarize, so no model call
+ assert len(model.requests) == 1 # the oversized request never reached the provider
+
+
+async def test_the_single_unit_stop_budgets_the_request_that_would_remain():
+ # The last response was billed far above its bytes (many short messages, protocol framing), so the anchored
+ # estimate is past the window. Dropping the old units leaves a small request: the ladder moves on, no stop.
+ store = InMemoryTranscriptStore()
+
+ def billed_high(request):
+ return [Done(replace(assistant("noted"), usage=Usage(input_tokens=30_000, output_tokens=10)))]
+
+ first = Model([call("read", "r0", path="f"), call("read", "r1", path="f"), billed_high])
+ await run(make_agent(first, store=store, tools=[reader(tokens(1_000))]), row="first")
+ model = Model([[Done(assistant("done"))]], [[Done(assistant(CHECKPOINT))]])
+ events = await run(make_agent(model, store=store), tokens(1_000), row="second")
+ assert not [event for event in events if isinstance(event, ContextExhausted)]
+ assert events[-1].reason == "completed"
+ assert [event.mode for event in events if isinstance(event, CompactionFinished)] == ["rolling"]
+ request = model.conversation_requests[0] # the only one sent, after the checkpoint
+ assert request_tokens(request.system, request.tools, request.messages) + 4_096 <= 32_000
+
+
+async def test_the_stage_judges_the_fork_it_would_send_exactly_as_the_turn_composes_it():
+ # Rehydrated state rides in every request, the fork's included: the stage's dry run counts it, so it never starts
+ # a normal checkpoint whose first request the turn would then refuse; it goes straight to the rolling step.
+ state = UserMessage((text(tokens(4_000)),))
+ model = Model([*growing(3)[:2], call("read", "big", path="f"), [Done(assistant("done"))]], [[Done(assistant(CHECKPOINT))]] * 3)
+ agent = make_agent(model, tools=[sized_reader(6_000, 6_000, 12_000)], rehydrate=lambda _: [state])
+ events = await run(agent)
+ assert not [event for event in events if isinstance(event, CompactionFailed)]
+ assert [event.mode for event in events if isinstance(event, CompactionFinished)][0] == "rolling"
+ assert events[-1].reason == "completed"
+ assert all(request.messages[0] == state for request in model.requests)
+
+
+async def test_the_stop_check_counts_the_split_turn_input_the_drop_would_copy():
+ # The last unit is a tool batch after a large input: moving everything else out still copies that input into
+ # <current-request>, so nothing can make the request fit. It stops before any checkpoint call or row.
+ model = Model([call("read", "big", path="f")], [[Done(assistant(CHECKPOINT))]])
+ agent = make_agent(model, tools=[reader(tokens(12_000))])
+ events = await run(agent, tokens(18_000))
+ assert events[-1].reason == "context_exhausted"
+ assert [event for event in events if isinstance(event, ContextExhausted)]
+ assert not model.checkpoint_requests
+ assert not [row for row in await agent.store.load("session") if row.kind == "compaction"]
+
+
+async def test_the_stop_check_budgets_exactly_the_request_the_drop_leaves(monkeypatch):
+ # One assembler of checkpoint + tail: the minimal request the stop check budgets is the request the conversation
+ # sends once the drop has moved everything but the last unit out.
+ seen = []
+ minimal = Agent._minimal
+
+ async def spy(self, *args, **kwargs):
+ composed, plan = await minimal(self, *args, **kwargs)
+ seen.append(composed)
+ return composed, plan
+
+ monkeypatch.setattr(Agent, "_minimal", spy)
+ host = Host()
+ failing = [Done(assistant(CHECKPOINT, stop_reason="length"))] # the rolling checkpoint fails: the ladder drops
+ model = Model([[Done(assistant("ok"))], call("read", "big", path="f"), [Done(assistant("done"))]], [failing])
+ agent = make_agent(model, tools=[reader(tokens(16_000))], context=ContextConfig(host=host))
+ await run(agent, tokens(12_000), row="first")
+ events = await run(agent, "now read the big file", row="second")
+ assert [event.mode for event in events if isinstance(event, CompactionFinished)] == ["dropped"]
+ assert events[-1].reason == "completed"
+ assert seen and seen[0] == model.conversation_requests[-1]
+
+
+async def test_an_overflow_after_streamed_output_is_never_retried():
+ # The adapter streamed text, then reported overflow without a partial: the user saw output, so no retry.
+ model = Model([*history(), [TextDelta(0, "partial answer"), OVERFLOW]], [[Done(assistant(CHECKPOINT))]])
+ agent = make_agent(model, tools=[reader(tokens(3_000))])
+ await run(agent)
+ events = await run(agent, row="second")
+ assert events[-1].reason == "context_exhausted"
+ assert not model.checkpoint_requests and len(model.conversation_requests) == 4
+
+
+async def test_a_provider_that_always_overflows_stops_after_two_checkpoint_calls():
+ def overflow(request):
+ return [OVERFLOW]
+
+ model = Model([*_long_context(8), *[overflow] * 10], [overflow] * 10)
+ agent = make_agent(model, tools=[reader(tokens(1_500))])
+ events = await run(agent)
+ assert len(model.checkpoint_requests) == 2
+ assert len(model.conversation_requests) == 8 + 4 # the reads, then the request and its three retries
+ assert events[-1].reason == "context_exhausted"
+ modes = [row.payload["mode"] for row in await agent.store.load("session") if row.kind == "compaction"]
+ assert set(modes) == {"dropped"}
+
+
+async def test_one_compaction_is_in_flight_per_session():
+ entered, release = asyncio.Event(), asyncio.Event()
+
+ async def slow(request):
+ entered.set()
+ await release.wait()
+ yield Done(assistant(CHECKPOINT))
+
+ class SlowModel(Model):
+ async def stream(self, request, cancel):
+ self.requests.append(deepcopy(request))
+ if is_checkpoint(request):
+ async for event in slow(request):
+ yield event
+ return
+ for event in self.conversation.popleft():
+ yield event
+
+ model = SlowModel(history())
+ agent = make_agent(model, tools=[reader(tokens(3_000))])
+ await run(agent)
+ compaction = agent.compact(turn_id="compact")
+ task = asyncio.create_task(asyncio.wait_for(anext(compaction), 5))
+ first = await task
+ pending = asyncio.create_task(anext(compaction))
+ await entered.wait()
+ with pytest.raises(RuntimeError, match="active run"):
+ await anext(agent.run(input_row("other", "hi"), turn_id="other"))
+ with pytest.raises(RuntimeError, match="active run"):
+ await anext(agent.compact(turn_id="again"))
+ assert await agent.steer(input_row("steer", "no")) is False
+ release.set()
+ events = [first, await pending] + [event async for event in compaction]
+ assert events[-1].reason == "completed"
+ assert len(model.checkpoint_requests) == 1
+
+
+async def test_clearing_runs_when_the_cache_is_cold_and_spares_recent_turns():
+ now = [1_000.0]
+ store = InMemoryTranscriptStore(clock=lambda: now[0])
+ context = ContextConfig(clock=lambda: now[0])
+ script = [*_long_context(9), [Done(assistant("one"))], [Done(assistant("two"))], [Done(assistant("three"))]]
+ model = Model(script)
+ agent = make_agent(model, store=store, tools=[reader(tokens(6_000))], selection=LARGE, context=context)
+ await run(agent, row="turn-1")
+ await run(agent, row="turn-2")
+ assert not [row for row in await store.load("session") if row.kind == "context_edit"] # warm, below 0.8 T
+ results = deepcopy([row for row in await store.load("session") if row.kind == "tool_result"])
+ now[0] += 301 # idle past the cache TTL
+ await run(agent, row="turn-3")
+ rows = await store.load("session")
+ edits = [row for row in rows if row.kind == "context_edit"]
+ by_id = {row.row_id: row.message.tool_call_id for row in results}
+ # Nine results before the last two turns; the newest five eligible stay, the four older ones go.
+ assert sorted(by_id[row.payload["target_event_id"]] for row in edits) == ["r0", "r1", "r2", "r3"]
+ assert [row for row in rows if row.kind == "tool_result"] == results # the originals are never rewritten
+ sent = [m for m in model.requests[-1].messages if isinstance(m, ToolResultMessage)]
+ assert [m.content[0].text.startswith("[Old tool result cleared") for m in sent] == [True] * 4 + [False] * 5
+ assert model.requests[-1].messages == project(rows[:-1]).messages
+ assert store.transactions == [["context_edit"] * 4] # one transition, one transaction
+
+
+async def test_chinese_output_reaches_the_threshold_by_its_utf8_size():
+ chinese = "压缩" * 3_000 # 6,000 characters, 18,000 bytes: 4,500 tokens, where characters / 4 says 1,500
+ model = Model(growing(5), [[Done(assistant(CHECKPOINT))]])
+ agent = make_agent(model, tools=[reader(chinese)])
+ await run(agent)
+ crossing = next(index for index, request in enumerate(model.requests) if is_checkpoint(request))
+ assert crossing == 5 # five results of 4,500 tokens cross 19,904; at characters / 4 none would
+
+
+async def test_a_long_session_keeps_every_conversation_request_under_T():
+ model = Model(
+ [*[call("read", f"r{index}", path=f"f{index % 7}") for index in range(60)], [Done(assistant("done"))]],
+ [[Done(assistant(f"{CHECKPOINT} {index}"))] for index in range(60)],
+ )
+ agent = make_agent(model, tools=[reader(tokens(2_500))])
+ events = await run(agent)
+ assert events[-1].reason == "completed"
+ for request in model.conversation_requests:
+ assert request_tokens(request.system, request.tools, request.messages) < THRESHOLD
+ rows = await agent.store.load("session")
+ compactions = [row for row in rows if row.kind == "compaction"]
+ assert len(compactions) >= 3
+ # Iterative: each later fork's prefix starts with the previous checkpoint, and file lists accumulate.
+ assert all(
+ request.messages[0].content[0].text.startswith("<context-checkpoint>")
+ for request in model.checkpoint_requests[1:]
+ )
+ assert compactions[-1].payload["files_read"] == [f"f{index}" for index in range(7)]
+ assert all(row.payload["previous_compaction_id"] == prior.row_id for prior, row in zip(compactions, compactions[1:]))
+ # A fork anchored before the first checkpoint projects the original context.
+ original = project(rows, fork_point=compactions[0].context_seq - 1).messages
+ assert len(original) > len(project(rows).messages)
+
+
+# --- C-9 ordering and ownership invariants (context.md section 10) -----------------------------
+
+
+def fits_the_window(request) -> bool:
+ return request_tokens(request.system, request.tools, request.messages) + 4_096 + 8_000 <= 32_000
+
+
+class FailingTransactionStore(InMemoryTranscriptStore):
+ """Its next ``append_payloads`` transactions fail as a database would: nothing of them lands."""
+
+ def __init__(self, failures: int) -> None:
+ super().__init__()
+ self.failures = failures
+
+ async def append_payloads(self, session_id, entries):
+ if self.failures:
+ self.failures -= 1
+ raise RuntimeError("transaction failed")
+ return await super().append_payloads(session_id, entries)
+
+
+async def test_invariant_3_a_c9_transition_commits_in_one_transaction_or_not_at_all():
+ # A checkpoint that comes out ineffective moves the guard; its guard and its row share one transaction.
+ store = FailingTransactionStore(failures=1)
+ model = Model(reads(4), [[Done(assistant(tokens(15_000)))]])
+ agent = make_agent(model, store=store, tools=[sized_reader(6_000, 6_000, 6_000, 6_000)])
+ events = await run(agent)
+ rows = await store.load("session")
+ # Nothing of the failed transition is anywhere: no checkpoint, no guard state, no announcement.
+ assert not [row for row in rows if row.kind == "compaction" or "context" in row.payload]
+ assert [type(event).__name__ for event in events if "Compaction" in type(event).__name__] == ["CompactionStarted"]
+ assert events[-1].reason == "error"
+ model = Model(reads(1), [[Done(assistant(tokens(15_000)))]])
+ agent = make_agent(model, store=store, tools=[sized_reader(1)])
+ await run(agent, row="again")
+ assert store.transactions[-1] == ["agent_state", "compaction"]
+
+
+
+
+# --- round 5 decisions -------------------------------------------------------------------------------
+
+
+def test_context_management_and_user_hooks_are_mutually_exclusive_in_v1():
+ with pytest.raises(ValueError, match="mutually exclusive"):
+ make_agent(Model(), hooks=[Hooks()])
+
+
[email protected]("context", [True, False])
+async def test_a_usage_only_partial_never_enters_the_context_and_the_retry_resends_the_request(context):
+ billed = replace(assistant("", stop_reason="error"), usage=Usage(input_tokens=900, output_tokens=0))
+ model = Model([[ProviderError("rate_limit", "busy", True, partial=billed)], [Done(assistant("done"))]])
+ store = InMemoryTranscriptStore()
+ agent = Agent(
+ session_id="session",
+ models=FakeModelRouter(model),
+ tools=(),
+ hooks=(),
+ store=store,
+ jobs=FakeJobHost(),
+ cwd="/test-owned",
+ retry=RetryPolicy(initial_delay_s=0),
+ context=ContextConfig() if context else None,
+ )
+ events = await run(agent)
+ assert events[-1].reason == "completed"
+ first, second = model.requests
+ assert second.messages == first.messages # the original request, unchanged
+ responses = [row.message for row in await store.load("session") if row.kind == "response"]
+ assert all(response.content for response in responses)
+ # In every mode, the attempt's billed usage is exactly one audit row, outside the context.
+ assert [attempt["usage"]["input_tokens"] for _, _, attempt in store.attempts] == [900]
+
+
+def flat_scratch(tmp_path):
+ scratch = tmp_path / "state" / "scratch" / "session"
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ return scratch, outside
+
+
+async def _scratch_compact(tmp_path, scratch, calls, tools):
+ model = Model(
+ history(),
+ [[Done(AssistantMessage(tuple(calls), assistant().origin, "tool_use"))], [Done(assistant(CHECKPOINT))]],
+ )
+ agent = make_agent(
+ model, tools=[reader(tokens(3_000)), *tools], context=ContextConfig(scratch_dir=str(scratch)), cwd=str(tmp_path)
+ )
+ await run(agent)
+ events = [event async for event in agent.compact(turn_id="compact")]
+ assert events[-1].reason == "completed"
+ results = {m.tool_call_id: m for m in model.checkpoint_requests[-1].messages if isinstance(m, ToolResultMessage)}
+ return results
+
+
+async def test_scratch_writes_are_flat_inside_a_root_the_turn_creates(tmp_path):
+ scratch, outside = flat_scratch(tmp_path)
+ assert not scratch.exists()
+ write = WriteTool()
+ calls = [
+ ToolCallBlock("flat", "write", {"path": "state/scratch/session/plan.md", "content": "plan"}),
+ ToolCallBlock("nested", "write", {"path": "state/scratch/session/sub/plan.md", "content": "no"}),
+ ]
+ results = await _scratch_compact(tmp_path, scratch, calls, [write])
+ assert not results["flat"].is_error and (scratch / "plan.md").read_text() == "plan"
+ # A subdirectory is never authorized, so no parent is ever created and no parent component can race.
+ assert results["nested"].content[0].text == DENIED and not (scratch / "sub").exists()
+
+
+async def test_a_scratch_root_that_is_a_symlink_authorizes_nothing(tmp_path):
+ scratch, outside = flat_scratch(tmp_path)
+ scratch.parent.mkdir(parents=True)
+ scratch.symlink_to(outside, target_is_directory=True)
+ calls = [ToolCallBlock("w", "write", {"path": "state/scratch/session/plan.md", "content": "no"})]
+ results = await _scratch_compact(tmp_path, scratch, calls, [WriteTool()])
+ assert results["w"].content[0].text == DENIED and not os.listdir(outside)
+
+
+async def test_an_abort_waits_for_a_scratch_worker_before_closing_the_root(tmp_path, monkeypatch):
+ # A worker thread outlives a cancelled await: the root's descriptor closes only after the worker is done with it.
+ scratch, outside = scratch_case(tmp_path)
+ entered, release, seen = threading.Event(), threading.Event(), []
+ original = ScratchRoot.write
+
+ def blocked(self, name, arguments):
+ entered.set()
+ release.wait(5)
+ try:
+ os.fstat(self._fd)
+ seen.append("open")
+ except OSError:
+ seen.append("closed")
+ return original(self, name, arguments)
+
+ monkeypatch.setattr(ScratchRoot, "write", blocked)
+ write = ToolCallBlock("w", "write", {"path": str(scratch / "plan.md"), "content": "plan"})
+ model = Model(history(), [[Done(AssistantMessage((write,), assistant().origin, "tool_use"))]])
+ agent = make_agent(model, tools=[reader(tokens(3_000))], context=ContextConfig(scratch_dir=str(scratch)))
+ await run(agent)
+ compacting = asyncio.ensure_future(_drain(agent.compact(turn_id="compact")))
+ await asyncio.to_thread(entered.wait, 5)
+ agent.abort("stop")
+ threading.Timer(0.2, release.set).start()
+ events = await compacting
+ assert events[-1].reason == "aborted"
+ assert seen == ["open"]
+ assert (scratch / "plan.md").read_text() == "plan"
+ assert sorted(os.listdir(scratch)) == ["escape", "plan.md"] and not os.listdir(outside) # no temp file left
+
+
+async def _drain(stream):
+ return [event async for event in stream]
+
+
[email protected]("swap", ["root", "target"])
+async def test_a_scratch_write_never_lands_outside_after_a_swap_between_policy_and_execution(tmp_path, monkeypatch, swap):
+ scratch, outside = flat_scratch(tmp_path)
+ decide = CheckpointPolicy.decide
+
+ def decide_then_swap(policy, call):
+ decision = decide(policy, call)
+ if swap == "root":
+ # The root renamed and its pathname pointed at an outside directory, after the policy opened it.
+ scratch.rename(scratch.parent / "moved")
+ scratch.symlink_to(outside, target_is_directory=True)
+ else:
+ (scratch / "plan.md").symlink_to(outside / "plan.md")
+ return decision
+
+ monkeypatch.setattr(CheckpointPolicy, "decide", decide_then_swap)
+ calls = [ToolCallBlock("w", "write", {"path": "state/scratch/session/plan.md", "content": "plan"})]
+ results = await _scratch_compact(tmp_path, scratch, calls, [WriteTool()])
+ assert not os.listdir(outside) # nothing outside: no content, no temp file, no directory
+ if swap == "root":
+ # The opened directory still receives it, under its new name; its old pathname is never resolved.
+ assert not results["w"].is_error and (scratch.parent / "moved" / "plan.md").read_text() == "plan"
+ else:
+ # A name that became a symlink is never followed and never replaced.
+ assert results["w"].content[0].text.endswith("it is not a regular file.")
+ assert (scratch / "plan.md").is_symlink()
+
+
+async def test_scratch_edit_reads_and_publishes_through_the_root_descriptor(tmp_path):
+ scratch, outside = flat_scratch(tmp_path)
+ scratch.mkdir(parents=True)
+ (scratch / "plan.md").write_bytes("\ufeffa\r\nb\r\n".encode())
+ (scratch / "link.md").symlink_to(outside / "secret.md")
+ (outside / "secret.md").write_text("a\n")
+ calls = [
+ ToolCallBlock("e", "edit", {"path": "state/scratch/session/plan.md", "edits": [{"oldText": "b", "newText": "c"}]}),
+ ToolCallBlock("l", "edit", {"path": "state/scratch/session/link.md", "edits": [{"oldText": "a", "newText": "x"}]}),
+ ToolCallBlock("d", "write", {"path": "state/scratch/session/..", "content": "no"}),
+ ]
+ results = await _scratch_compact(tmp_path, scratch, calls, [])
+ assert results["e"].content[0].text == "Successfully replaced 1 block(s) in state/scratch/session/plan.md."
+ assert (scratch / "plan.md").read_bytes() == "\ufeffa\r\nc\r\n".encode() # BOM and CRLF kept
+ assert results["l"].is_error and (outside / "secret.md").read_text() == "a\n" # a symlink is never followed
+ assert results["d"].content[0].text == DENIED
+
+
+async def test_without_descriptor_relative_rename_scratch_writes_are_denied_and_reads_stay(tmp_path, monkeypatch):
+ scratch, outside = flat_scratch(tmp_path)
+ monkeypatch.setattr(os, "supports_dir_fd", frozenset(os.supports_dir_fd) - {os.rename}) # as on Windows
+ calls = [
+ ToolCallBlock("w", "write", {"path": "state/scratch/session/plan.md", "content": "no"}),
+ ToolCallBlock("r", "read", {"path": "notes.md"}),
+ ]
+ results = await _scratch_compact(tmp_path, scratch, calls, [])
+ assert results["w"].content[0].text == DENIED and not (scratch / "plan.md").exists()
+ assert not results["r"].is_error
diff --git a/tests/agent_core/agent/test_context.py b/tests/agent_core/agent/test_context.py
new file mode 100644
index 000000000..e4e816c66
--- /dev/null
+++ b/tests/agent_core/agent/test_context.py
@@ -0,0 +1,464 @@
+"""C-9 rules as pure functions (``agent-core-contracts/context.md``).
+
+The loop tests in ``test_compaction.py`` cover when these rules run; these pin
+the rules themselves: the estimate, the limits, the cut, what is cleared, and
+the checkpoint's model-facing text and row.
+"""
+
+from __future__ import annotations
+
+import math
+import random
+import re
+from dataclasses import replace
+from pathlib import Path
+
+import pytest
+
+from core.agent_core.ai.provider import ModelCapabilities, ModelEndpoint, ModelRequest
+from core.agent_core.harness.context import (
+ CLEARED_PLACEHOLDER,
+ SkillRef,
+ budget,
+ carried_skills,
+ checkpoint_request,
+ clearable_results,
+ compaction_payload,
+ fit_result,
+ half_cut,
+ checkpoint_max_tokens,
+ last_anchor,
+ message_tokens,
+ normal_cut,
+ output_tokens,
+ request_facts,
+ request_tokens,
+ rolling_cut,
+ text_tokens,
+ unit_tokens,
+)
+from core.agent_core.harness.projection import context_view, project
+from core.agent_core.harness.store import ContextEntry
+from core.agent_core.tools.base import ToolSpec
+from core.agent_core.messages import (
+ AssistantMessage,
+ ImageBlock,
+ TextBlock,
+ ThinkingBlock,
+ ToolCallBlock,
+ ToolResultMessage,
+ Usage,
+ UserMessage,
+ text,
+)
+from tests.agent_core.fakes import ENDPOINT, ORIGIN, assistant, user
+
+CONTRACT = Path(__file__).resolve().parents[3] / "docs/plans/agent-core-contracts/context.md"
+
+
+class Rows:
+ """Committed rows built in context order."""
+
+ def __init__(self) -> None:
+ self.rows: list[ContextEntry] = []
+
+ def add(self, kind, message=None, *, payload=None, row_id=None) -> ContextEntry:
+ seq = len(self.rows) + 1
+ row = ContextEntry("session", seq, kind, row_id or f"{kind}-{seq}", message, payload or {})
+ self.rows.append(row)
+ return row
+
+ def input(self, value: str) -> ContextEntry:
+ return self.add("input", user(value))
+
+ def response(self, *calls, value: str = "", usage=None, stop_reason=None) -> ContextEntry:
+ message = assistant(value, calls=calls, stop_reason=stop_reason)
+ if usage is not None:
+ message = AssistantMessage(message.content, message.origin, message.stop_reason, usage=usage)
+ return self.add("response", message)
+
+ def result(self, call: ToolCallBlock, value: str, *, skill=None) -> ContextEntry:
+ details = {"skill": {"name": skill[0], "revision": skill[1]}} if skill else {}
+ return self.add(
+ "tool_result", ToolResultMessage(call.id, call.name, (text(value),)), payload={"details": details}
+ )
+
+ def tool(self, name: str, value: str, *, call_id: str, skill=None, **arguments) -> ToolCallBlock:
+ call = ToolCallBlock(call_id, name, arguments)
+ self.response(call)
+ self.result(call, value, skill=skill)
+ return call
+
+
+def test_the_estimate_counts_utf8_bytes_so_chinese_is_not_undercounted():
+ chinese = "上下文管理在这里决定什么时候压缩对话" * 4 # 72 characters, 216 UTF-8 bytes
+ assert len(chinese) == 72
+ assert text_tokens(chinese) == 54 # characters / 4 would claim 18
+ assert message_tokens(user(chinese)) == 54
+ image = UserMessage((TextBlock(text="see"), ImageBlock("image/png", "media-token")))
+ assert message_tokens(image) == 1 + 1_600
+ call = ToolCallBlock("id", "read", {"path": "中"}, signature="sig")
+ reply = AssistantMessage((ThinkingBlock("ab", signature="cdef"), call), ORIGIN, "tool_use")
+ replayed = len("ab") + len("cdef") + len("read") + len('{"path":"中"}'.encode()) + len("sig")
+ assert message_tokens(reply) == math.ceil(replayed / 4)
+
+
+def make_request(messages=(), *, system="system", tools=(), endpoint=ENDPOINT, max_tokens=4_096) -> ModelRequest:
+ return ModelRequest(endpoint, system, tuple(messages), tuple(tools), max_tokens)
+
+
+ "window,input_limit,hop_output,configured,output,margin,threshold,keep",
+ [
+ (200_000, None, 32_000, 64_000, 32_000, 8_000, 160_000, 20_000),
+ (1_000_000, None, 32_000, 32_000, 32_000, 30_000, 900_000, 20_000),
+ (None, None, None, 8_192, 8_192, 8_000, 111_808, 20_000), # unknown: W = 128,000, O = 8,192
+ (400_000, 272_000, 128_000, 128_000, 128_000, 12_000, 132_000, 20_000),
+ (32_000, None, 64_000, 4_096, 4_096, 8_000, 19_904, 4_976), # O is the request's, capped by the Agent
+ ],
+)
+def test_limits_follow_the_frozen_formula_from_the_route_capabilities(
+ window, input_limit, hop_output, configured, output, margin, threshold, keep
+):
+ capabilities = ModelCapabilities(context_window=window, input_limit=input_limit, max_output_tokens=hop_output)
+ assert output_tokens(capabilities, configured) == output
+ assert checkpoint_max_tokens(capabilities, configured) == min(16_000, output)
+ plan = budget(make_request(system="", max_tokens=output), capabilities, transcript=())
+ assert (plan.output, plan.margin, plan.threshold, plan.keep) == (output, margin, threshold, keep)
+ limit = input_limit or window or 128_000
+ at_limit = budget(make_request(system="x" * 4 * (limit - output - margin), max_tokens=output), capabilities, transcript=())
+ assert at_limit.fits and not replace(at_limit, est=at_limit.est + 1).fits
+
+
+def _usage(total: int) -> Usage:
+ return Usage(input_tokens=total - 10, output_tokens=10)
+
+
+CAPABILITIES = ModelCapabilities(context_window=32_000, max_output_tokens=4_096)
+
+
+def _anchored_rows():
+ """A read, then a response R billed 5,000 whose row records its request, R's result, and a later reply."""
+ rows = Rows()
+ rows.input("x" * 400)
+ rows.tool("read", "w" * 4_000, call_id="before", path="a")
+ read = ToolCallBlock("r", "read", {"path": "f"})
+ sent = make_request(context_view(rows.rows).messages)
+ anchored = rows.add(
+ "response",
+ AssistantMessage((read,), ORIGIN, "tool_use", usage=_usage(5_000)),
+ payload={"request": request_facts(sent)},
+ )
+ result = rows.result(read, "y" * 4_000)
+ rows.response(value="z" * 40)
+ return rows, anchored, result
+
+
+def _est(rows, request=None):
+ view = context_view(rows.rows)
+ request = request or make_request(view.messages)
+ return budget(request, CAPABILITIES, transcript=view.messages, anchor=last_anchor(rows.rows, view)).est
+
+
+def _edit_of(entry):
+ return {
+ "version": 1,
+ "target_event_id": entry.row_id,
+ "replacement": {"text": CLEARED_PLACEHOLDER},
+ "reason": "clear_old_tool_result",
+ }
+
+
+def test_the_anchor_holds_while_the_transcript_up_to_its_response_is_unchanged():
+ rows, anchored, result = _anchored_rows()
+ messages = context_view(rows.rows).messages
+ after = message_tokens(result.message) + message_tokens(messages[-1])
+ assert _est(rows) == 5_000 + after
+ # Outside the transcript, a change adjusts the anchored usage by its UTF-8/4 delta.
+ longer = "system " * 100
+ delta = request_tokens(longer, (), ()) - request_tokens("system", (), ())
+ assert _est(rows, make_request(messages, system=longer)) == 5_000 + after + delta
+ tool = ToolSpec("t", "d" * 400, {})
+ tool_delta = request_tokens("system", (tool,), ()) - request_tokens("system", (), ())
+ assert _est(rows, make_request(messages, tools=(tool,))) == 5_000 + after + tool_delta
+ rehydrated = user("state " * 50)
+ assert _est(rows, make_request((rehydrated, *messages))) == 5_000 + after + message_tokens(rehydrated)
+ # An edit after the anchored response is counted by its bytes.
+ rows.add("context_edit", payload=_edit_of(result))
+ cleared = context_view(rows.rows).messages
+ assert _est(rows) == 5_000 + message_tokens(cleared[-2]) + message_tokens(cleared[-1])
+
+
+def test_an_edit_or_checkpoint_before_the_anchor_or_another_route_invalidates_it():
+ def whole(rows, request=None):
+ request = request or make_request(context_view(rows.rows).messages)
+ return request_tokens(request.system, request.tools, request.messages)
+
+ rows, anchored, result = _anchored_rows()
+ other_route = ModelEndpoint("anthropic", "http://model.invalid", "other-model", "", provider="test-provider")
+ request = make_request(context_view(rows.rows).messages, endpoint=other_route)
+ assert _est(rows, request) == whole(rows, request) # another model's tokenizer
+ # A context_edit of a result before the anchored response changes what its usage measured.
+ before = next(row for row in rows.rows if row.kind == "tool_result")
+ rows.add("context_edit", payload=_edit_of(before))
+ assert _est(rows) == whole(rows)
+ # A checkpoint that keeps the anchored response verbatim still replaces what came before it.
+ rows, anchored, result = _anchored_rows()
+ view = context_view(rows.rows)
+ cut = next(index for index, unit in enumerate(view.units) if unit.seq == anchored.context_seq)
+ payload = compaction_payload(
+ view, cut, mode="normal", reason="threshold", focus=None, checkpoint="checkpoint", skills=(), state=(),
+ earlier_record=None, tokens_before=0, threshold=0, summarizer=None, usage=None,
+ )
+ rows.add("compaction", payload=payload)
+ assert context_view(rows.rows).units[0].seq == anchored.context_seq
+ assert _est(rows) == whole(rows)
+ # A failed or aborted response, or one without usage or request facts, never anchors.
+ for message, facts in [
+ (AssistantMessage((), ORIGIN, "error", usage=_usage(9_999)), True),
+ (AssistantMessage((), ORIGIN, "aborted", usage=_usage(9_999)), True),
+ (AssistantMessage((text("a"),), ORIGIN, "stop", usage=Usage()), True),
+ (AssistantMessage((text("a"),), ORIGIN, "stop", usage=_usage(9_999)), False),
+ ]:
+ only = Rows()
+ only.input("x")
+ only.add("response", message, payload={"request": {"tokens": 1}} if facts else {})
+ assert last_anchor(only.rows, context_view(only.rows)) is None
+
+
+def _random_rows(seed: int) -> list[ContextEntry]:
+ rng = random.Random(seed)
+ rows = Rows()
+ late: list[tuple[ToolCallBlock, str]] = []
+ rows.input("start " * rng.randint(1, 40))
+ for step in range(rng.randint(2, 25)):
+ if rng.random() < 0.3:
+ for call, value in late:
+ rows.result(call, value) # recovery settles open calls before the next input
+ late.clear()
+ rows.input("next " * rng.randint(1, 40))
+ continue
+ calls = [ToolCallBlock(f"c{step}-{index}", "bash", {"n": index}) for index in range(rng.randint(0, 3))]
+ rows.response(*calls, value="thinking " * rng.randint(0, 20))
+ for call in calls:
+ value = "out " * rng.randint(1, 400)
+ if rng.random() < 0.2:
+ late.append((call, value))
+ else:
+ rows.result(call, value)
+ for call, value in late:
+ rows.result(call, value)
+ return rows.rows
+
+
+def _assert_paired(messages) -> None:
+ """Every tool call is followed by exactly its committed results, in call order."""
+ index = 0
+ while index < len(messages):
+ message = messages[index]
+ assert not isinstance(message, ToolResultMessage), "a tool result without its call"
+ calls = message.tool_calls if isinstance(message, AssistantMessage) else ()
+ results = messages[index + 1 : index + 1 + len(calls)]
+ assert [result.tool_call_id for result in results] == [call.id for call in calls]
+ assert all(result.content[0].text.startswith("out") for result in results)
+ index += 1 + len(calls)
+
+
[email protected]("seed", range(150))
+def test_a_cut_never_separates_a_tool_call_from_its_result(seed):
+ rows = _random_rows(seed)
+ view = context_view(rows)
+ rng = random.Random(seed)
+ cuts = {
+ normal_cut(view.units, rng.choice([0, 50, 500, 5_000])),
+ half_cut(view.units),
+ rolling_cut(view.units, lambda cut: rng.random() < 0.5),
+ }
+ for cut in cuts - {None}:
+ assert 0 < cut < len(view.units)
+ assert view.units[cut].lead.kind in {"input", "response"}
+ checkpoint = compaction_payload(
+ view,
+ cut,
+ mode="normal",
+ reason="threshold",
+ focus=None,
+ checkpoint="SUMMARY",
+ skills=(),
+ state=(),
+ earlier_record=None,
+ tokens_before=0,
+ threshold=0,
+ summarizer=None,
+ usage=None,
+ )
+ checkpoint["summary"] = "SUMMARY"
+ compacted = [*rows, ContextEntry("session", len(rows) + 1, "compaction", "checkpoint", payload=checkpoint)]
+ messages = project(compacted).messages
+ assert messages[0].content[0].text == "SUMMARY"
+ _assert_paired(messages[1:])
+ assert len(messages) - 1 == sum(len(unit.messages) for unit in view.units[cut:])
+
+
+ "sizes,keep,cut",
+ [
+ ([10, 10, 10, 10], 25, 2), # the longest tail of whole units within keep
+ ([10, 10, 10, 40], 25, 3), # at least the last unit, even when it alone is over keep
+ ([10, 10], 100, None), # everything fits the tail: nothing to summarize
+ ([30], 10, None),
+ ],
+)
+def test_the_normal_cut_keeps_whole_recent_units_within_keep(sizes, keep, cut):
+ rows = Rows()
+ for size in sizes:
+ rows.input("x" * 4 * size)
+ view = context_view(rows.rows)
+ assert [unit_tokens(unit) for unit in view.units] == sizes
+ assert normal_cut(view.units, keep) == cut
+
+
+def test_the_half_cut_is_nearest_to_half_and_the_rolling_cut_moves_earlier_until_the_fork_fits():
+ rows = Rows()
+ for size in (100, 100, 100, 100, 100, 100):
+ rows.input("x" * 400 * size)
+ units = context_view(rows.rows).units
+ assert half_cut(units) == 3
+ assert rolling_cut(units, lambda cut: cut <= 1) == 1
+ assert rolling_cut(units, lambda cut: False) is None
+ assert half_cut(units[:1]) is None
+
+
+def test_clearing_spares_recent_turns_the_newest_results_and_skill_loads():
+ rows = Rows()
+ big = "o" * 20_000 # 5,000 tokens each
+ rows.input("turn 1")
+ old = [rows.tool("bash", big, call_id=f"old-{index}", command="ls") for index in range(9)]
+ rows.tool("bash", big, call_id="skill", command="vibe skill load x", skill=("x", "r1"))
+ rows.tool("write", big, call_id="write", path="f")
+ rows.input("turn 2")
+ rows.tool("read", big, call_id="recent-1", path="f")
+ rows.input("turn 3")
+ rows.tool("read", big, call_id="recent-2", path="f")
+ view = context_view(rows.rows)
+ cleared = {entry.message.tool_call_id for entry in clearable_results(view)}
+ # Results after the second-latest input are protected, then the newest 5 eligible results.
+ assert cleared == {call.id for call in old[:6]}
+
+ too_small = Rows()
+ too_small.input("turn 1")
+ for index in range(9):
+ too_small.tool("read", "o" * 1_000, call_id=f"small-{index}", path="f")
+ too_small.input("turn 2")
+ too_small.input("turn 3")
+ assert clearable_results(context_view(too_small.rows)) == ()
+
+
+def test_the_checkpoint_request_is_the_owner_approved_prompt_verbatim():
+ contract = CONTRACT.read_text()
+ section = contract[contract.index("## 11. Checkpoint request") :]
+ block = re.search(r"```text\n(.*?)\n```", section, re.S).group(1)
+ focus_line = "Additional focus from the user: <focus, only for /compact <focus>>\n"
+ assert focus_line in block
+ assert checkpoint_request().content[0].text == block.replace(focus_line, "")
+ focused = checkpoint_request(" keep the migration plan ").content[0].text
+ assert focused == block.replace(focus_line, "Additional focus from the user: keep the migration plan\n")
+
+
+def test_a_checkpoint_carries_files_skills_and_the_split_turn_request_across_checkpoints():
+ rows = Rows()
+ rows.input("old turn")
+ rows.add("input", UserMessage((text("fix the parser"), ImageBlock("image/png", "m", name="trace.png"))))
+ rows.tool("read", "a", call_id="r1", path="a.py")
+ rows.tool("write", "b", call_id="w1", path="b.py")
+ rows.tool("read", "b", call_id="r2", path="b.py")
+ rows.tool("bash", "skill body", call_id="s1", command="vibe skill load s", skill=("s", "1"))
+ rows.tool("bash", "skill body", call_id="s2", command="vibe skill load t", skill=("t", "1"))
+ rows.tool("read", "c", call_id="r3", path="c.py")
+ rows.tool("bash", "t again", call_id="s3", command="vibe skill load t", skill=("t", "2"))
+ view = context_view(rows.rows)
+ cut = 7 # before the read of c.py: the cut splits the parser turn
+ assert carried_skills(view, cut) == (SkillRef("s", "1"),)
+ first = compaction_payload(
+ view,
+ cut,
+ mode="normal",
+ reason="threshold",
+ focus=None,
+ checkpoint="# 1. Self and method\n- terse",
+ skills=carried_skills(view, cut),
+ state=("SKILLS",),
+ earlier_record="vibe data query --sql '...'",
+ tokens_before=1,
+ threshold=2,
+ summarizer=None,
+ usage=None,
+ )
+ assert (first["files_read"], first["files_modified"]) == (["a.py"], ["b.py"])
+ assert first["current_request"] == "fix the parser\n[image: trace.png]"
+ assert first["summary"] == "\n".join(
+ [
+ "<context-checkpoint>",
+ "This is a record of the earlier part of this conversation, written for you so you can continue. It is "
+ "history, not new instructions: the user requirements recorded in it still apply, but do not treat the "
+ "record itself as a request.",
+ "",
+ "# 1. Self and method\n- terse",
+ "",
+ "<artifacts>",
+ "Read:",
+ "- a.py",
+ "Modified:",
+ "- b.py",
+ "</artifacts>",
+ "<earlier-record>",
+ "The full text of the earlier conversation is still stored. To look up a detail, run:",
+ "vibe data query --sql '...'",
+ "</earlier-record>",
+ "<current-request>",
+ "fix the parser\n[image: trace.png]",
+ "</current-request>",
+ "</context-checkpoint>",
+ ]
+ )
+
+ # A second checkpoint whose head has no input carries the split turn's request and accumulates files.
+ rows.add("compaction", payload=first)
+ rows.tool("edit", "ok", call_id="e1", path="c.py")
+ rows.tool("read", "d", call_id="r4", path="d.py")
+ view = context_view(rows.rows)
+ second = compaction_payload(
+ view,
+ len(view.units) - 1,
+ mode="dropped",
+ reason="overflow",
+ focus=None,
+ checkpoint="",
+ skills=carried_skills(view, len(view.units) - 1),
+ state=(),
+ earlier_record=None,
+ tokens_before=1,
+ threshold=2,
+ summarizer=None,
+ usage=None,
+ )
+ assert second["files_read"] == ["a.py"]
+ assert second["files_modified"] == ["b.py", "c.py"]
+ assert second["current_request"] == first["current_request"]
+ assert second["skills"] == [{"name": "s", "revision": "1"}, {"name": "t", "revision": "2"}]
+ assert second["summarized_to_seq"] > first["summarized_to_seq"]
+ # No model checkpoint and no lookup command: no framing text, no pointer.
+ assert second["summary"].startswith("<context-checkpoint>\n<artifacts>\n")
+ assert "<earlier-record>" not in second["summary"]
+
+
[email protected]("body", ["x" * 40_000, "上下文" * 5_000])
+def test_a_checkpoint_tool_result_is_cut_to_its_limit_keeping_the_head_and_saying_so(body):
+ image = ImageBlock("image/png", "media-token")
+ content = (text(body), image)
+ fitted = fit_result(content, 3_000)
+ assert message_tokens(ToolResultMessage("c", "read", fitted)) <= 3_000
+ assert body.startswith(fitted[0].text) and len(fitted[0].text) > 0
+ assert image not in fitted # 1,600 tokens no longer fit after the head
+ assert fitted[-1].text.startswith("[Output truncated to fit this checkpoint turn: showing about 3000 of")
+ assert fit_result(content, 50_000) == content
diff --git a/tests/agent_core/agent/test_loop.py b/tests/agent_core/agent/test_loop.py
index 44a3d820f..dcb512f07 100644
--- a/tests/agent_core/agent/test_loop.py
+++ b/tests/agent_core/agent/test_loop.py
@@ -36,8 +36,17 @@ from core.agent_core.agent.hooks import (
)
from core.agent_core.agent.loop import Agent
from core.agent_core.agent.models import RetryPolicy
-from core.agent_core.ai.provider import Done, ModelCapabilities, ProviderError, TextDelta, ThinkingDelta, ToolCallStart
+from core.agent_core.ai.provider import (
+ Done,
+ ModelCapabilities,
+ ModelRequest,
+ ProviderError,
+ TextDelta,
+ ThinkingDelta,
+ ToolCallStart,
+)
from core.agent_core.agent.models import ModelSelection
+from core.agent_core.harness.context import ContextConfig, budget
from core.agent_core.harness.projection import project
from core.agent_core.messages import AssistantMessage, ThinkingBlock, ToolCallBlock, ToolResultMessage, Usage, UserMessage, text
from core.agent_core.tools.base import ToolResult
@@ -606,14 +615,14 @@ async def test_retry_obeys_provider_flag_and_allows_usage_only_partial(streamed,
assert events[-1].reason == "error"
assert sleeps == []
else:
- # A usage-only partial is persisted as a non-final model response, not
- # merged into the successful attempt. The provider owns retryability.
+ # A partial of a retried attempt is never context. The provider owns retryability.
assert len(provider.requests) == agent.models.resolutions == 2
assert sleeps == [3.0]
assert events[-1].reason == "completed"
-async def test_retry_preserves_usage_only_partial_in_successful_response():
+async def test_retry_keeps_a_usage_only_partial_out_of_the_context():
+ # A usage-only partial is attempt data, never context: the retry resends the original request.
store = InMemoryTranscriptStore()
first_partial = AssistantMessage(
content=(),
@@ -639,17 +648,53 @@ async def test_retry_preserves_usage_only_partial_in_successful_response():
)
assert events[-1].reason == "completed"
+ assert provider.requests[1].messages == provider.requests[0].messages
responses = [row.message for row in await store.load("session") if row.kind == "response"]
- assert len(responses) == 2
- assert responses[0].usage == Usage(input_tokens=5, output_tokens=2, cache_write_tokens=1)
- assert responses[1].usage == Usage(
- input_tokens=7,
- output_tokens=3,
- cache_read_tokens=4,
- )
+ assert [response.usage for response in responses] == [successful.usage]
+ # Without context management too, the attempt's usage is exactly one non-context audit row.
+ assert [attempt["usage"]["input_tokens"] for _, _, attempt in store.attempts] == [5]
+
+
+class _FailingResponses(InMemoryTranscriptStore):
+ async def append_response(self, session_id, message, *, final, request=None):
+ raise RuntimeError("disk full")
+
+def _billed(content, stop_reason="stop", input_tokens=9):
+ return AssistantMessage(tuple(content), assistant().origin, stop_reason, usage=Usage(input_tokens=input_tokens))
-async def test_retry_usage_partial_is_not_committed_twice_when_budget_expires(monkeypatch):
+
+_TWIN = (ToolCallBlock("same", "echo", {}), ToolCallBlock("same", "echo", {}))
+
+
+ "scripts,context,store_type,audited,reason",
+ [
+ # Attempts that never became a response: each is exactly one audit row, whatever the exit.
+ pytest.param([[ProviderError("rate_limit", "busy", True, partial=_billed((), "error"))], [Done(assistant("ok"))]], False, InMemoryTranscriptStore, 1, "completed", id="retried"),
+ pytest.param([[ProviderError("overflow", "prompt is too long", False, partial=_billed((), "error"))]], True, InMemoryTranscriptStore, 1, "context_exhausted", id="relieved"),
+ pytest.param([[ProviderError("server", "down", False, partial=_billed((), "error"))]], False, InMemoryTranscriptStore, 1, "error", id="usage-only terminal"),
+ pytest.param([[Done(_billed(_TWIN, "tool_use"))]], False, InMemoryTranscriptStore, 1, "error", id="rejected response"),
+ pytest.param([[ProviderError("server", "down", False, partial=_billed(_TWIN, "error"))]], False, InMemoryTranscriptStore, 1, "error", id="rejected partial"),
+ pytest.param([[Done(_billed((text("ok"),)))]], False, _FailingResponses, 1, "error", id="commit failed"),
+ # Attempts that became a response keep their usage in its row: no audit row.
+ pytest.param([[Done(_billed((text("ok"),)))]], False, InMemoryTranscriptStore, 0, "completed", id="committed"),
+ pytest.param([[ProviderError("server", "down", False, partial=_billed((text("half"),), "error"))]], False, InMemoryTranscriptStore, 0, "error", id="committed partial"),
+ ],
+)
+async def test_the_ledger_audits_every_attempt_that_never_became_a_response(scripts, context, store_type, audited, reason):
+ # Invariant 4: the ledger owns the attempt audit on every exit of the model call, not each exit path.
+ store = store_type()
+ options = {"context": ContextConfig()} if context else {}
+ agent = make_agent(ScriptedProvider(scripts), store=store, retry=RetryPolicy(initial_delay_s=0), **options)
+ events = await collect(agent)
+ assert events[-1].reason == reason
+ assert [attempt["usage"]["input_tokens"] for _, _, attempt in store.attempts] == [9] * audited
+ committed = [row.message.usage for row in await store.load("session") if row.kind == "response"]
+ assert len(committed) + audited == sum(1 for script in scripts if script) # every attempt counted once
+
+
+async def test_retry_usage_partial_never_enters_the_context_when_budget_expires(monkeypatch):
real_sleep = asyncio.sleep
async def slow_sleep(delay):
@@ -675,10 +720,8 @@ async def test_retry_usage_partial_is_not_committed_twice_when_budget_expires(mo
events = await collect(agent)
- responses = [row.message for row in await store.load("session") if row.kind == "response"]
assert len(provider.requests) == 1
- assert len(responses) == 1
- assert responses[0].usage == Usage(input_tokens=5)
+ assert not [row for row in await store.load("session") if row.kind == "response"]
assert events[-1].reason == "error"
@@ -907,9 +950,10 @@ async def test_output_budget_uses_configured_budget_and_known_or_default_provide
@pytest.mark.parametrize("window,expected", [(None, 128000), (32000, 32000)])
-def test_router_selection_exposes_effective_context_budget_without_forging_capabilities(window, expected):
+def test_the_context_budget_defaults_an_unknown_window_without_forging_capabilities(window, expected):
selection = ModelSelection(ENDPOINT, ModelCapabilities(context_window=window))
- assert selection.context_window == expected
+ request = ModelRequest(ENDPOINT, "", (), (), 8192)
+ assert budget(request, selection.capabilities, transcript=()).window == expected
assert selection.capabilities.context_window == window
diff --git a/tests/agent_core/agent/test_projection.py b/tests/agent_core/agent/test_projection.py
index 2ae7eb2b7..dc7a3d642 100644
--- a/tests/agent_core/agent/test_projection.py
+++ b/tests/agent_core/agent/test_projection.py
@@ -43,10 +43,146 @@ def test_projection_sorts_rows_cuts_at_fork_restores_state_and_places_results_in
assert rows[3].payload["state"] == {"counter": [1]}
[email protected]("kind", ["compaction", "context_edit"])
-def test_P3_context_rows_fail_explicitly_instead_of_silently_replaying_old_context(kind):
- with pytest.raises(ProjectionError, match=f"{kind} requires P3"):
- project([ContextEntry("session", 1, kind, "unsupported", payload={})])
+def _edit(seq, row_id, target, replacement):
+ payload = {
+ "version": 1,
+ "target_event_id": target,
+ "replacement": {"text": replacement},
+ "reason": "clear_old_tool_result",
+ }
+ return ContextEntry("session", seq, "context_edit", row_id, payload=payload)
+
+
+def _checkpoint_payload(first_kept_seq, *, summary="SUMMARY", state=("STATE",), **fields):
+ payload = {
+ "version": 1,
+ "mode": "normal",
+ "reason": "threshold",
+ "focus": None,
+ "summary": summary,
+ "checkpoint": "checkpoint",
+ "state": list(state),
+ "first_kept_seq": first_kept_seq,
+ "summarized_to_seq": first_kept_seq - 1,
+ "previous_compaction_id": None,
+ "current_request": None,
+ "current_request_message_id": None,
+ "files_read": ["a.py"],
+ "files_modified": [],
+ "skills": [{"name": "s", "revision": "1"}],
+ "tokens_before": 10,
+ "tokens_after_estimate": 5,
+ "threshold": 8,
+ "summarizer": {"origin": {"provider": "p", "api": "anthropic", "model": "m"}, "prompt_version": "v", "rounds": 0},
+ "usage": {"input_tokens": 1, "output_tokens": 2, "cache_read_tokens": 0, "cache_write_tokens": 0},
+ }
+ payload.update(fields)
+ return payload
+
+
+def _checkpoint_row(seq, first_kept_seq, *, summary="SUMMARY", state=("STATE",), **fields):
+ payload = _checkpoint_payload(first_kept_seq, summary=summary, state=state, **fields)
+ return ContextEntry("session", seq, "compaction", f"checkpoint-{seq}", payload=payload)
+
+
+def _checkpointed_rows():
+ read, bash = ToolCallBlock("a", "read", {"path": "x"}), ToolCallBlock("b", "bash", {"command": "ls"})
+ return [
+ ContextEntry("session", 1, "input", "in-1", user("start")),
+ ContextEntry("session", 2, "response", "r-1", assistant(calls=[read])),
+ ContextEntry("session", 3, "input", "in-2", user("next")),
+ ContextEntry("session", 4, "response", "r-2", assistant(calls=[bash])),
+ # A late recovery result of a call the checkpoint summarizes.
+ ContextEntry("session", 5, "tool_result", "res-a", ToolResultMessage("a", "read", (text("A"),))),
+ ContextEntry("session", 6, "tool_result", "res-b", ToolResultMessage("b", "bash", (text("B"),), True)),
+ _edit(7, "edit-1", "res-b", "first placeholder"),
+ _edit(8, "edit-2", "res-b", "latest placeholder"),
+ _checkpoint_row(9, 3, state=("STATE-1", "STATE-2")),
+ ContextEntry("session", 10, "input", "in-3", user("after")),
+ ]
+
+
+def test_checkpoints_and_edits_project_purely_and_deterministically():
+ rows = _checkpointed_rows()
+ before = deepcopy(rows)
+ projected = project(list(reversed(rows)), system="system", rehydrated=[user("rehydrated")])
+ assert projected == project(rows, system="system", rehydrated=[user("rehydrated")])
+ assert rows == before
+ checkpoint, *rest = projected.messages[1:]
+ assert [block.text for block in checkpoint.content] == ["SUMMARY", "STATE-1", "STATE-2"]
+ assert [type(message).__name__ for message in rest] == [
+ "UserMessage",
+ "AssistantMessage",
+ "ToolResultMessage",
+ "UserMessage",
+ ]
+ cleared = rest[2]
+ assert (cleared.tool_call_id, cleared.tool_name, cleared.is_error) == ("b", "bash", True)
+ assert cleared.content[0].text == "latest placeholder"
+ # The summarized call's late result left with it: no orphan reaches a provider.
+ assert all(getattr(message, "tool_call_id", None) != "a" for message in projected.messages)
+
+
+ "fork_point,result_b",
+ [(8, "latest placeholder"), (7, "first placeholder"), (6, "B")],
+)
+def test_a_fork_before_a_checkpoint_or_edit_projects_the_original_context(fork_point, result_b):
+ projected = project(_checkpointed_rows(), fork_point=fork_point)
+ assert [getattr(message, "tool_call_id", None) for message in projected.messages] == [
+ None,
+ None,
+ "a",
+ None,
+ None,
+ "b",
+ ]
+ assert projected.messages[2].content[0].text == "A"
+ assert projected.messages[5].content[0].text == result_b
+
+
+def _state_row(context):
+ return ContextEntry("session", 2, "agent_state", "state", payload={"version": 1, "state": {}, "context": context})
+
+
+ "row",
+ [
+ _edit(2, "edit", "in-1", "x"),
+ _edit(2, "edit", "missing", "x"),
+ ContextEntry("session", 2, "context_edit", "edit", payload={"version": 1, "target_event_id": "in-1"}),
+ _checkpoint_row(2, 3),
+ ContextEntry("session", 2, "compaction", "checkpoint", payload={"version": 1, "first_kept_seq": 1}),
+ # Every field the C-9 rules read later is checked when the row loads, not when it is next used.
+ _checkpoint_row(2, 1, skills=[{}]),
+ _checkpoint_row(2, 1, files_read="a.py"),
+ _checkpoint_row(2, 1, files_modified=[1]),
+ _checkpoint_row(2, 1, mode="partial"),
+ _checkpoint_row(2, 1, current_request=["text"]),
+ _checkpoint_row(2, 1, summarized_to_seq="1"),
+ _checkpoint_row(2, 1, threshold=1.5),
+ _checkpoint_row(2, 1, summarizer={"origin": {}, "prompt_version": "v", "rounds": 0}),
+ _checkpoint_row(2, 1, usage={"input_tokens": -1}),
+ _checkpoint_row(2, 1, unexpected=True),
+ _state_row({"failures": "1", "ineffective": 0, "paused": False}),
+ _state_row({"failures": 0, "ineffective": 0}),
+ _state_row({"failures": 0, "ineffective": 0, "paused": 1}),
+ ],
+)
+def test_malformed_context_rows_fail_explicitly_instead_of_projecting_a_wrong_context(row):
+ with pytest.raises(ProjectionError):
+ project([ContextEntry("session", 1, "input", "in-1", user("start")), row])
+
+
+def test_a_complete_checkpoint_row_and_guard_state_load():
+ rows = [
+ ContextEntry("session", 1, "input", "in-1", user("start")),
+ _state_row({"failures": 1, "ineffective": 2, "paused": True}),
+ _checkpoint_row(3, 1, summarizer=None, current_request="go", current_request_message_id="in-1"),
+ ]
+ projected = project(rows)
+ assert projected.context_state == {"failures": 1, "ineffective": 2, "paused": True}
+ assert [block.text for block in projected.messages[0].content] == ["SUMMARY", "STATE"]
def test_malformed_or_duplicate_results_are_not_silently_dropped():
diff --git a/tests/agent_core/fakes.py b/tests/agent_core/fakes.py
index 233c156a7..aa6df8c8d 100644
--- a/tests/agent_core/fakes.py
+++ b/tests/agent_core/fakes.py
@@ -1,13 +1,15 @@
"""Small hermetic C-2/C-5/C-7 fakes shared by agent-core lanes.
The provider records detached requests before running each script. The store
-implements only committed entries and fork ancestry, not loop/projection logic.
+implements the ``TranscriptStore`` contract (committed entries and fork ancestry),
+not loop/projection logic; the contract suite runs it against the SQLite store.
Jobs have explicit test-controlled state and never spawn processes.
"""
from __future__ import annotations
import asyncio
+import time
from collections import deque
from copy import deepcopy
from typing import AsyncIterator, Callable, Mapping, Optional, Sequence
@@ -83,10 +85,24 @@ class FakeModelRouter:
class InMemoryTranscriptStore:
- def __init__(self) -> None:
+ """The ``TranscriptStore`` contract in memory, and nothing more.
+
+ ``tests/test_transcript_store_contract.py`` runs the same contract tests on this store and on the SQLite one.
+ What tests read besides the protocol is observation only: ``final``, the audit rows (``audits``,
+ ``attempts``), and the kinds each ``append_payloads`` transaction committed (``transactions``).
+ """
+
+ def __init__(self, *, clock: Callable[[], float] = time.time) -> None:
self.rows: dict[str, list[ContextEntry]] = {}
self.forks: dict[str, Snapshot] = {}
self.final: dict[str, bool] = {}
+ # C-9 checkpoint-turn audit rows: (session_id, row id, payload), never context.
+ self.audits: list[tuple[str, str, dict]] = []
+ # C-9 model-attempt audit rows (usage of attempts that never became context).
+ self.attempts: list[tuple[str, str, dict]] = []
+ # Kinds committed by each ``append_payloads`` transaction.
+ self.transactions: list[list[str]] = []
+ self._clock = clock
self._next_id = 0
def fork(self, snapshot: Snapshot, *, session_id: str) -> None:
@@ -101,31 +117,90 @@ class InMemoryTranscriptStore:
prefix = [row for row in await self.load(anchor.session_id) if row.context_seq <= anchor.context_seq]
return deepcopy(prefix + self.rows.get(session_id, []))
- async def _append(self, session_id, kind, *, message=None, payload=None, row_id=None) -> ContextEntry:
- entries = await self.load(session_id)
- seq = max((entry.context_seq for entry in entries), default=0) + 1
- if row_id is None:
- self._next_id += 1
- row_id = f"row_{self._next_id}"
- if any(entry.row_id == row_id for entry in entries):
- raise ValueError(f"input already consumed: {row_id}")
- row = ContextEntry(session_id, seq, kind, row_id, deepcopy(message), deepcopy(payload or {}))
- self.rows.setdefault(session_id, []).append(row)
- return deepcopy(row)
+ def _entries(self, session_id, items) -> list[ContextEntry]:
+ """Rows for ``(kind, message, payload, row_id)`` items, numbered after the Session's context."""
+ entries = self.rows.get(session_id, [])
+ anchor = self.forks.get(session_id)
+ seq = max([entry.context_seq for entry in entries] + [anchor.context_seq if anchor else 0])
+ rows = []
+ for kind, message, payload, row_id in items:
+ seq += 1
+ if row_id is None:
+ self._next_id += 1
+ row_id = f"row_{self._next_id}"
+ rows.append(ContextEntry(session_id, seq, kind, row_id, deepcopy(message), deepcopy(payload), self._clock()))
+ return rows
+
+ async def _append(self, session_id, items) -> list[ContextEntry]:
+ rows = self._entries(session_id, items)
+ self.rows.setdefault(session_id, []).extend(rows) # all of them or none
+ return deepcopy(rows)
async def consume_input(self, session_id, message_id, message: UserMessage) -> ContextEntry:
- return await self._append(session_id, "input", row_id=message_id, message=message)
-
- async def append_response(self, session_id, message: AssistantMessage, *, final: bool) -> ContextEntry:
- row = await self._append(session_id, "response", message=message)
+ for entry in await self.load(session_id):
+ if entry.row_id == message_id:
+ # A retried commit of the same input is the committed entry; anything else would rewrite it.
+ if entry.message != message:
+ raise ValueError(f"input {message_id} is already in the context")
+ return entry
+ return (await self._append(session_id, [("input", message, {}, message_id)]))[0]
+
+ async def append_response(self, session_id, message: AssistantMessage, *, final: bool, request=None) -> ContextEntry:
+ payload = {"request": dict(request)} if request is not None else {}
+ row = (await self._append(session_id, [("response", message, payload, None)]))[0]
self.final[row.row_id] = final
return row
async def append_tool_result(self, session_id, message: ToolResultMessage, *, details: Mapping) -> ContextEntry:
- return await self._append(session_id, "tool_result", message=message, payload={"details": dict(details)})
+ settled = _settled_result(await self.load(session_id), message.tool_call_id)
+ if settled is not None:
+ return settled # a call instance is settled once, whoever writes
+ payload = {"details": dict(details)} if details else {}
+ return (await self._append(session_id, [("tool_result", message, payload, None)]))[0]
async def append_payload(self, session_id, kind, payload: Mapping) -> ContextEntry:
- return await self._append(session_id, kind, payload=payload)
+ return (await self._append(session_id, [(kind, None, _payload(kind, payload), None)]))[0]
+
+ async def append_payloads(self, session_id, entries) -> list[ContextEntry]:
+ committed = await self._append(session_id, [(kind, None, _payload(kind, payload), None) for kind, payload in entries])
+ self.transactions.append([row.kind for row in committed])
+ return committed
+
+ async def append_audit(self, session_id, kind, payload: Mapping) -> str:
+ if kind not in ("attempt", "checkpoint_turn"):
+ raise ValueError(f"not an audit kind: {kind!r}")
+ self._next_id += 1
+ row_id = f"audit_{self._next_id}"
+ record = (session_id, row_id, deepcopy(dict(payload)))
+ (self.audits if kind == "checkpoint_turn" else self.attempts).append(record)
+ return row_id
+
+
+def _payload(kind, payload: Mapping) -> dict:
+ """A payload row's content, as the contract admits it: a payload kind, at the current version."""
+ if kind not in ("compaction", "context_edit", "agent_state"):
+ raise ValueError(f"not a payload entry kind: {kind!r}")
+ if payload.get("version") != 1:
+ raise ValueError(f"a {kind} payload needs version 1")
+ return deepcopy(dict(payload))
+
+
+def _settled_result(entries: Sequence[ContextEntry], tool_call_id: str) -> Optional[ContextEntry]:
+ """The first result after the latest response carrying a call with this id, as the SQLite store finds it."""
+ owner = None
+ for index, entry in enumerate(entries):
+ if entry.kind == "response" and any(call.id == tool_call_id for call in entry.message.tool_calls):
+ owner = index
+ if owner is None:
+ return None
+ return next(
+ (
+ entry
+ for entry in entries[owner + 1 :]
+ if entry.kind == "tool_result" and entry.message.tool_call_id == tool_call_id
+ ),
+ None,
+ )
class FakeTool:
diff --git a/tests/test_agent_transcript.py b/tests/test_agent_transcript.py
index e5b45142d..7a1bd4152 100644
--- a/tests/test_agent_transcript.py
+++ b/tests/test_agent_transcript.py
@@ -169,22 +169,30 @@ def _tool_result(call_id: str, body: str) -> ToolResultMessage:
return ToolResultMessage(tool_call_id=call_id, tool_name="bash", content=(text(body),))
-COMPACTION = {
+COMPACTION = { # the current C-9 ``Compaction`` shape (transcript-rows.schema.json)
"version": 1,
- "summary": "## Objective\n修复路径测试",
+ "mode": "normal",
+ "reason": "manual",
+ "focus": None,
+ "summary": "<context-checkpoint>\n## Objective\n修复路径测试\n</context-checkpoint>",
+ "checkpoint": "## Objective\n修复路径测试",
+ "state": [],
"first_kept_seq": 3,
- "summarized_from_seq": 1,
"summarized_to_seq": 2,
"previous_compaction_id": None,
- "reason": "manual",
- "focus": None,
- "tokens_before": 100,
- "tokens_after_estimate": 40,
- "summarizer": {"origin": {"provider": "anthropic", "api": "anthropic", "model": "claude-opus-5-5"},
- "prompt_version": "ckpt-v1", "chunks": 1},
+ "current_request": None,
+ "current_request_message_id": None,
"files_read": ["core/paths.py"],
"files_modified": [],
- "current_request_message_id": None,
+ "skills": [],
+ "tokens_before": 100,
+ "tokens_after_estimate": 40,
+ "threshold": 80,
+ "summarizer": {
+ "origin": {"provider": "anthropic", "api": "anthropic", "model": "claude-opus-5-5"},
+ "prompt_version": "checkpoint-v2",
+ "rounds": 0,
+ },
}
@@ -268,6 +276,25 @@ async def test_rows_outside_the_context_never_load(engine) -> None:
assert conn.execute(select(messages.c.context_seq).where(messages.c.id == queued)).scalar() is None
[email protected]("kind,event_type", [("attempt", "model_attempt"), ("checkpoint_turn", "context_checkpoint_turn")])
+async def test_an_audit_row_is_kept_outside_the_context(engine, kind, event_type) -> None:
+ with engine.begin() as conn:
+ home = _scope(conn, "C-home")
+ _session(conn, "ses_main", home)
+ consumed = _row(conn, "ses_main", home, "go")
+ store = SQLiteTranscriptStore(engine)
+ entry = await store.consume_input("ses_main", consumed, _user("go"))
+ payload = {"version": 1, "usage": {"input_tokens": 9, "output_tokens": 0, "cache_read_tokens": 0, "cache_write_tokens": 0}, "error": "rate_limit: busy"}
+
+ row_id = await store.append_audit("ses_main", kind, payload, agent_name="avibe")
+
+ assert list(await store.load("ses_main")) == [entry]
+ with engine.connect() as conn:
+ row = conn.execute(select(agent_events).where(agent_events.c.id == row_id)).mappings().one()
+ assert (row["event_type"], row["visibility"], row["context_seq"]) == (event_type, "audit", None)
+ assert json.loads(row["content_json"]) == payload
+
+
async def test_an_input_enters_the_context_once(engine) -> None:
with engine.begin() as conn:
home = _scope(conn, "C-home")
diff --git a/tests/test_transcript_store_contract.py b/tests/test_transcript_store_contract.py
new file mode 100644
index 000000000..00dea7054
--- /dev/null
+++ b/tests/test_transcript_store_contract.py
@@ -0,0 +1,394 @@
+"""The ``TranscriptStore`` contract, run against every store (C-5 ``transcript.md`` §2, C-9 ``context.md`` §9).
+
+Each contract test runs on the in-memory store the engine tests use, on the SQLite store, and on the adapter's
+store over it: a protocol method the real store lacks, or a behavior the fake has and the contract does not state,
+fails here, so what a test proves on the fake holds for the real store. The second half drives C-9 through the
+loop on the fake and on SQLite, across a restart: the request facts, the commit times, the one-transaction commits,
+and the attempt audit the loop relies on.
+"""
+
+from __future__ import annotations
+
+import inspect
+import json
+import time
+
+import pytest
+from sqlalchemy import select
+
+from core.agent_core.agent.hooks import Snapshot
+from core.agent_core.agent.loop import Agent
+from core.agent_core.agent.models import RetryPolicy
+from core.agent_core.ai.provider import Done, ProviderError
+from core.agent_core.harness.context import ContextConfig, request_tokens
+from core.agent_core.harness.store import TranscriptStore
+from core.agent_core.messages import AssistantMessage, ToolCallBlock, ToolResultMessage, Usage, text, usage_to_dict
+from modules.agents.avibe.store import AdapterTranscriptStore
+from storage import agent_events_service, messages_service
+from storage.agent_transcript import SQLiteTranscriptStore, resolve_fork_anchor_seq
+from storage.db import create_sqlite_engine
+from storage.importer import ensure_sqlite_state
+from storage.models import agent_events
+from storage.settings_service import upsert_scope
+from tests.agent_core.agent.test_compaction import (
+ CHECKPOINT,
+ LARGE,
+ THRESHOLD,
+ Model,
+ billed,
+ english,
+ growing,
+ make_agent,
+ reader,
+ run,
+ tokens,
+)
+from tests.agent_core.fakes import (
+ FakeJobHost,
+ FakeModelRouter,
+ InMemoryTranscriptStore,
+ ScriptedProvider,
+ assistant,
+ input_row,
+ user,
+)
+
+NOW = "2026-10-04T00:00:00.000000Z"
+SESSION = "session"
+_AUDIT_KINDS = {"model_attempt": "attempt", "context_checkpoint_turn": "checkpoint_turn"}
+
+
+class _Fake:
+ def __init__(self) -> None:
+ self.store = InMemoryTranscriptStore()
+ self._ids = 0
+
+ def stored_input(self, session_id: str) -> str:
+ self._ids += 1
+ return f"msg_{self._ids}"
+
+ def fork(self, child: str, source: str, anchor) -> None:
+ self.store.fork(Snapshot(source, anchor.context_seq, {}), session_id=child)
+
+ def audits(self) -> list[tuple[str, dict]]:
+ return [("checkpoint_turn", payload) for _, _, payload in self.store.audits] + [
+ ("attempt", payload) for _, _, payload in self.store.attempts
+ ]
+
+ def close(self) -> None:
+ pass
+
+
+class _SQLite:
+ """A tmp state database (the suite's isolated home) with one Session, and its store or the adapter's."""
+
+ def __init__(self, *, adapter: bool) -> None:
+ ensure_sqlite_state()
+ self.engine = create_sqlite_engine()
+ with self.engine.begin() as conn:
+ self.scope = upsert_scope(conn, platform="slack", scope_type="channel", native_id="contract", now=NOW)
+ _session(conn, SESSION, self.scope)
+ store = SQLiteTranscriptStore(self.engine)
+ self.store = (
+ AdapterTranscriptStore(store, self.engine, environment=lambda _: {}, on_response=lambda *_: None)
+ if adapter
+ else store
+ )
+
+ def stored_input(self, session_id: str) -> str:
+ """An input row as the Delivery path stores it, before the loop consumes it."""
+ with self.engine.begin() as conn:
+ row = messages_service.append(
+ conn,
+ scope_id=self.scope,
+ session_id=session_id,
+ platform="slack",
+ author="user",
+ source="user",
+ message_type="user",
+ text="input",
+ )
+ return row["id"]
+
+ def fork(self, child: str, source: str, anchor) -> None:
+ with self.engine.begin() as conn:
+ metadata = {
+ "created_via": "session_fork",
+ "fork_source_session_id": source,
+ "fork_source_message_id": anchor.row_id,
+ "fork_source_context_seq": resolve_fork_anchor_seq(conn, source, anchor.row_id),
+ }
+ _session(conn, child, self.scope, metadata)
+
+ def audits(self) -> list[tuple[str, dict]]:
+ with self.engine.connect() as conn:
+ rows = conn.execute(
+ select(agent_events.c.event_type, agent_events.c.content_json, agent_events.c.context_seq).where(
+ agent_events.c.visibility == "audit"
+ )
+ ).all()
+ assert all(row.context_seq is None for row in rows)
+ return [(_AUDIT_KINDS[row.event_type], json.loads(row.content_json)) for row in rows]
+
+ def close(self) -> None:
+ self.engine.dispose()
+
+
+def _session(conn, session_id: str, scope_id: str, metadata: dict | None = None) -> None:
+ conn.exec_driver_sql(
+ "insert into agent_sessions (id, scope_id, agent_name, agent_backend, agent_variant, session_anchor, "
+ "workdir, native_session_id, status, visibility, pinned, agent_status, metadata_json, created_at, "
+ "updated_at, last_active_at) values (?, ?, 'avibe', 'avibe', 'avibe', ?, '/tmp', ?, 'active', "
+ "'foreground', 0, 'idle', ?, ?, ?, ?)",
+ (session_id, scope_id, session_id, session_id, json.dumps(metadata or {}), NOW, NOW, NOW),
+ )
+
+
+def _backend(name: str):
+ return _Fake() if name == "fake" else _SQLite(adapter=name == "adapter")
+
+
[email protected](params=["fake", "sqlite", "adapter"])
+def backend(request):
+ backend = _backend(request.param)
+ yield backend
+ backend.close()
+
+
+async def _started(backend):
+ """A Session that has consumed one input: every later context row answers a Turn."""
+ return await backend.store.consume_input(SESSION, backend.stored_input(SESSION), user("hello"))
+
+
+def _result(call_id: str, value: str) -> ToolResultMessage:
+ return ToolResultMessage(call_id, "read", (text(value),))
+
+
+# --- the contract ------------------------------------------------------------------------------------
+
+
+def test_the_store_implements_every_protocol_method_with_its_parameters(backend):
+ declared = {name: member for name, member in vars(TranscriptStore).items() if inspect.iscoroutinefunction(member)}
+ assert declared # the protocol is read, not assumed
+ for name, method in declared.items():
+ implemented = getattr(backend.store, name, None)
+ assert implemented is not None and inspect.iscoroutinefunction(implemented), name
+ accepted = inspect.signature(implemented).parameters
+ wanted = list(inspect.signature(method).parameters.values())[1:]
+ for parameter in wanted:
+ assert parameter.name in accepted, (name, parameter.name)
+ assert accepted[parameter.name].kind == parameter.kind, (name, parameter.name)
+ # An optional protocol parameter is optional in the store too.
+ assert (accepted[parameter.name].default is inspect.Parameter.empty) == (
+ parameter.default is inspect.Parameter.empty
+ ), (name, parameter.name)
+ names = {parameter.name for parameter in wanted}
+ extra = [p for p in accepted.values() if p.name not in names and p.default is inspect.Parameter.empty]
+ assert not extra, (name, extra) # anything more the store takes is optional
+
+
+async def test_each_append_returns_the_entry_load_reads_back_in_commit_order(backend):
+ store = backend.store
+ call = ToolCallBlock("call-1", "read", {"path": "f"})
+ before = time.time()
+ written = [
+ await _started(backend),
+ await store.append_response(SESSION, assistant(calls=[call]), final=False, request={"tokens": 120}),
+ await store.append_tool_result(SESSION, _result("call-1", "body"), details={"path": "f"}),
+ await store.append_payload(SESSION, "agent_state", {"version": 1, "state": {}}),
+ await store.append_response(SESSION, assistant("done"), final=True),
+ ]
+ after = time.time()
+ loaded = list(await store.load(SESSION))
+ assert loaded == written
+ assert [entry.kind for entry in loaded] == ["input", "response", "tool_result", "agent_state", "response"]
+ assert [entry.context_seq for entry in loaded] == list(range(1, 6))
+ assert [entry.message for entry in loaded if entry.message is not None] == [
+ user("hello"),
+ assistant(calls=[call]),
+ _result("call-1", "body"),
+ assistant("done"),
+ ]
+ # A response keeps the request facts it was sent with (C-9 section 2), and only those.
+ assert loaded[1].payload["request"] == {"tokens": 120} and "request" not in loaded[4].payload
+ assert loaded[2].payload["details"] == {"path": "f"}
+ # Every row carries its commit time, in epoch seconds, in commit order (C-9 section 3 reads it).
+ times = [entry.created_at for entry in loaded]
+ assert all(isinstance(value, float) and before - 0.001 <= value <= after + 0.001 for value in times), times
+ assert times == sorted(times)
+
+
+async def test_a_payload_row_needs_a_payload_kind_and_the_current_version(backend):
+ store = backend.store
+ before = [await _started(backend)]
+ with pytest.raises(ValueError):
+ await store.append_payload(SESSION, "tool_result", {"version": 1})
+ with pytest.raises(ValueError):
+ await store.append_payload(SESSION, "agent_state", {"state": {}})
+ assert list(await store.load(SESSION)) == before
+
+
+async def test_append_payloads_commits_every_entry_in_order_or_none(backend):
+ store = backend.store
+ before = [await _started(backend)]
+ batch = [
+ ("context_edit", {"version": 1, "edit": 1}),
+ ("compaction", {"version": 1, "summary": "s"}),
+ ("agent_state", {"version": 1, "state": {}}),
+ ]
+ written = list(await store.append_payloads(SESSION, batch))
+ assert [(entry.kind, dict(entry.payload)) for entry in written] == batch
+ assert [entry.context_seq for entry in written] == [2, 3, 4]
+ assert list(await store.load(SESSION)) == [*before, *written]
+ for invalid in (
+ [("context_edit", {"version": 1}), ("compaction", {"summary": "no version"})],
+ [("agent_state", {"version": 1, "state": {}}), ("tool_result", {"version": 1})],
+ ):
+ with pytest.raises(ValueError):
+ await store.append_payloads(SESSION, invalid)
+ assert list(await store.load(SESSION)) == [*before, *written] # nothing of a rejected batch landed
+
+
+async def test_audit_rows_are_kept_outside_the_context(backend):
+ store = backend.store
+ before = [await _started(backend)]
+ attempt = {"version": 1, "usage": {"input_tokens": 5, "output_tokens": 2}, "error": "rate_limit: busy"}
+ turn = {"version": 1, "reason": "threshold", "mode": "normal", "messages": []}
+ ids = [await store.append_audit(SESSION, "attempt", attempt), await store.append_audit(SESSION, "checkpoint_turn", turn)]
+ assert all(isinstance(row_id, str) and row_id for row_id in ids) and len(set(ids)) == 2
+ with pytest.raises(ValueError):
+ await store.append_audit(SESSION, "compaction", {"version": 1})
+ assert list(await store.load(SESSION)) == before
+ assert sorted(backend.audits(), key=repr) == sorted([("attempt", attempt), ("checkpoint_turn", turn)], key=repr)
+
+
+async def test_consuming_an_input_again_returns_its_entry_and_never_rewrites_it(backend):
+ store = backend.store
+ message_id = backend.stored_input(SESSION)
+ first = await store.consume_input(SESSION, message_id, user("hello"))
+ assert await store.consume_input(SESSION, message_id, user("hello")) == first
+ with pytest.raises((ValueError, RuntimeError)):
+ await store.consume_input(SESSION, message_id, user("changed"))
+ assert list(await store.load(SESSION)) == [first]
+
+
+async def test_a_call_is_settled_once(backend):
+ store = backend.store
+ await _started(backend)
+ await store.append_response(SESSION, assistant(calls=[ToolCallBlock("call-1", "read", {"path": "f"})]), final=False)
+ first = await store.append_tool_result(SESSION, _result("call-1", "one"), details={})
+ assert await store.append_tool_result(SESSION, _result("call-1", "two"), details={}) == first
+ assert [entry for entry in await store.load(SESSION) if entry.kind == "tool_result"] == [first]
+
+
+async def test_a_fork_loads_its_source_up_to_the_anchor_then_its_own_rows(backend):
+ store = backend.store
+ await _started(backend)
+ anchor = await store.append_response(SESSION, assistant("one"), final=True)
+ await store.consume_input(SESSION, backend.stored_input(SESSION), user("later"))
+ await store.append_response(SESSION, assistant("two"), final=True)
+ backend.fork("child", SESSION, anchor)
+ inherited = [entry for entry in await store.load(SESSION) if entry.context_seq <= anchor.context_seq]
+ assert list(await store.load("child")) == inherited
+ own = await store.consume_input("child", backend.stored_input("child"), user("child"))
+ assert own.context_seq == anchor.context_seq + 1
+ assert list(await store.load("child")) == [*inherited, own]
+
+
+async def test_a_failure_inside_the_transaction_commits_none_of_the_batch(monkeypatch):
+ # SQLite only: a database error after the first row is inserted rolls the whole batch back.
+ backend = _SQLite(adapter=False)
+ try:
+ before = [await _started(backend)]
+ original = agent_events_service.append
+ calls = []
+
+ def failing(*args, **kwargs):
+ calls.append(kwargs["event_type"])
+ if len(calls) == 2:
+ raise RuntimeError("disk I/O error")
+ return original(*args, **kwargs)
+
+ monkeypatch.setattr(agent_events_service, "append", failing)
+ with pytest.raises(RuntimeError):
+ await backend.store.append_payloads(
+ SESSION, [("context_edit", {"version": 1}), ("agent_state", {"version": 1, "state": {}})]
+ )
+ assert calls == ["context_edit", "agent_state"]
+ assert list(await backend.store.load(SESSION)) == before
+ finally:
+ backend.close()
+
+
+# --- C-9 through the loop, on the fake and on SQLite ---------------------------------------------------
+
+
[email protected](params=["fake", "sqlite"])
+def c9(request):
+ backend = _backend(request.param)
+ yield backend
+ backend.close()
+
+
+async def test_a_new_agent_anchors_on_the_stored_request_facts(c9):
+ # The second Turn's request is past T by UTF-8/4, but the stored usage of the last response says it fits.
+ read = billed(assistant(calls=[ToolCallBlock("r", "read", {"path": "notes.md"})]), 0.8)
+ first = Model([read, billed(assistant("Summary of the notes."), 0.8)])
+ await run(make_agent(first, store=c9.store, tools=[reader(english(18_000))]), english(100), row=c9.stored_input(SESSION))
+ model = Model([[Done(assistant("ok"))]], [[Done(assistant(CHECKPOINT))]])
+ events = await run(make_agent(model, store=c9.store), english(2_000), row=c9.stored_input(SESSION))
+ assert not model.checkpoint_requests and events[-1].reason == "completed"
+ request = model.conversation_requests[0]
+ assert request_tokens(request.system, request.tools, request.messages) >= THRESHOLD
+
+
+async def test_a_new_agent_clears_old_results_once_the_cache_has_gone_cold(c9):
+ idle = [0.0]
+ context = ContextConfig(clock=lambda: time.time() + idle[0])
+ reads = [[Done(assistant(calls=[ToolCallBlock(f"r{index}", "read", {"path": "f"})]))] for index in range(9)]
+ model = Model([*reads, [Done(assistant("one"))], [Done(assistant("two"))]])
+ agent = make_agent(model, store=c9.store, tools=[reader(tokens(6_000))], selection=LARGE, context=context)
+ await run(agent, row=c9.stored_input(SESSION))
+ await run(agent, row=c9.stored_input(SESSION))
+ assert not [row for row in await c9.store.load(SESSION) if row.kind == "context_edit"] # warm, below 0.8 T
+ idle[0] = 301 # past the cache TTL; the restarted Agent knows only the stored commit times
+ model = Model([[Done(assistant("three"))]])
+ restarted = make_agent(model, store=c9.store, tools=[reader(tokens(6_000))], selection=LARGE, context=context)
+ await run(restarted, row=c9.stored_input(SESSION))
+ edits = [row for row in await c9.store.load(SESSION) if row.kind == "context_edit"]
+ assert len(edits) == 4 # nine results before the last two turns; the newest five eligible stay
+
+
+async def test_a_checkpoint_commits_with_its_state_and_a_new_agent_continues_from_it(c9):
+ model = Model(growing(4), [[Done(assistant(CHECKPOINT))]])
+ events = await run(make_agent(model, store=c9.store, tools=[reader(tokens(6_000))]), row=c9.stored_input(SESSION))
+ assert events[-1].reason == "completed"
+ rows = await c9.store.load(SESSION)
+ assert [row.kind for row in rows].count("compaction") == 1
+ model = Model([[Done(assistant("next"))]])
+ events = await run(make_agent(model, store=c9.store), "next", row=c9.stored_input(SESSION))
+ assert events[-1].reason == "completed"
+ sent = model.conversation_requests[0].messages
+ assert CHECKPOINT in sent[0].content[0].text
+ kept = [message.tool_call_id for message in sent if isinstance(message, ToolResultMessage)]
+ assert "read-0" not in kept # what the checkpoint summarized is gone after the restart too
+
+
+async def test_a_usage_only_attempt_is_one_audit_row_and_never_context_without_context_management(c9):
+ partial = AssistantMessage((), assistant().origin, "error", usage=Usage(input_tokens=5, output_tokens=2))
+ answer = AssistantMessage(assistant("done").content, assistant().origin, "stop", usage=Usage(input_tokens=7))
+ provider = ScriptedProvider([[ProviderError("rate_limit", "busy", True, partial=partial)], [Done(answer)]])
+ agent = Agent(
+ session_id=SESSION,
+ models=FakeModelRouter(provider),
+ tools=[],
+ hooks=(),
+ store=c9.store,
+ jobs=FakeJobHost(),
+ cwd="/test-owned",
+ retry=RetryPolicy(initial_delay_s=0),
+ )
+ events = [event async for event in agent.run(input_row(c9.stored_input(SESSION), "go"), turn_id="turn")]
+ assert events[-1].reason == "completed"
+ assert [row.message.usage for row in await c9.store.load(SESSION) if row.kind == "response"] == [answer.usage]
+ assert [(kind, payload["usage"]) for kind, payload in c9.audits()] == [("attempt", usage_to_dict(partial.usage))]